@tencentcloud/lite-chat 1.4.2 → 1.5.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +30 -0
- package/basic.es.js +3 -1
- package/basic.js +3 -1
- package/package.json +6 -12
- package/plugins/avchatroom.es.js +1 -1
- package/plugins/avchatroom.js +1 -1
- package/plugins/cloud-search.es.js +1 -1
- package/plugins/cloud-search.js +1 -1
- package/plugins/conversation-group.es.js +1 -1
- package/plugins/conversation-group.js +1 -1
- package/plugins/conversation.es.js +1 -1
- package/plugins/conversation.js +1 -1
- package/plugins/follow.es.js +1 -1
- package/plugins/follow.js +1 -1
- package/plugins/friend.es.js +1 -1
- package/plugins/friend.js +1 -1
- package/plugins/group.es.js +1 -1
- package/plugins/group.js +1 -1
- package/plugins/message-enhancer.es.js +3 -1
- package/plugins/message-enhancer.js +3 -1
- package/plugins/offline-message-synchronizer.es.js +1 -1
- package/plugins/offline-message-synchronizer.js +1 -1
- package/plugins/rich-media-message.es.js +1 -1
- package/plugins/rich-media-message.js +1 -1
- package/plugins/signaling.es.js +1 -1
- package/plugins/signaling.js +1 -1
- package/plugins/topic.es.js +1 -1
- package/plugins/topic.js +1 -1
- package/professional.es.js +5 -1
- package/professional.js +5 -1
- package/standard.es.js +5 -1
- package/standard.js +5 -1
package/professional.es.js
CHANGED
|
@@ -1 +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,t,s){var o;t&&(this.listeners[e]=null===(o=this.listeners[e])||void 0===o?void 0:o.filter((e=>{const o=e.fn===t,n=!s||e.context===s;return!(o&&n)})))}emit(e,...t){const s=this.listeners[e];s&&s.forEach((e=>{const{fn:s,context:o}=e;s.apply(o,t)}))}once(e,t,s){const o=(...n)=>{t.apply(s,n),this.off(e,o)};this.on(e,o)}}const t={ANDROID:2,IOS:3,MAC:4,WEB:7,WX_MP:8,QQ_MP:9,TT_MP:10,BAIDU_MP:11,ALI_MP:12,IPAD:13,UNI_NATIVE_APP:15,DONUT_NATIVE_APP:19,NS_NATIVE_APP:20,RN_NATIVE_APP:21},s=["heartbeat.alive","im_open_status.wslogin","im_open_status.wslogout","group_open_long_polling_http_svc.get_msg","group_open_long_polling_http_noauth_svc.get_msg"];var 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,i=Object.freeze({__proto__:null,get ConvModifyPushType(){return o},ENUM_PLATFORM:t,IS_TOPIC_MESSAGE:2,NOT_NEED_CRC_SERVCMD:s});function r(e){var t;const s=[];return null===(t=null==e?void 0:e.GroupTips)||void 0===t||t.forEach((e=>{2===e.GroupInfo.MillionGroupFlag?s.push(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={}));const 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){var t;const s=[];return null===(t=null==e?void 0:e.C2cNotifyMsgArray)||void 0===t||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){var t;const s=[];return null===(t=null==e?void 0:e.GroupTips)||void 0===t||t.forEach((e=>{Array.isArray(e.MsgBody.GroupWithdrawInfoArray)?s.push(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){var t;const s=[];return null===(t=null==e?void 0:e.GroupTips)||void 0===t||t.forEach((e=>{const{GroupAtTips:{TopicId:t}}=e;t?s.push(n.TOPIC_AT_TIPS):s.push(n.GROUP_AT_TIPS)})),s}},{conditions:[{type:"hasKey",value:"RecentContactMod"}],subTypeParser:function(e){var t;const s=[];return null===(t=null==e?void 0:e.RecentContactMod)||void 0===t||t.forEach((e=>{switch(e.PushType){case 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}];var c;function u(e){var t;const s=Array.isArray(null===(t=null==e?void 0:e.body)||void 0===t?void 0:t.EventArray)?e.body.EventArray:[],o=[];return s.forEach((t=>{t.Flag=e.body.Flag;const s=a.find((e=>e.conditions.every((e=>{switch(e.type){case"event":return t.Event===e.value;case"hasKey":return Object.prototype.hasOwnProperty.call(t,e.value);default:return!1}}))));if(!s)return null;let n=[];"function"==typeof s.subTypeParser?n=s.subTypeParser(t):s.subType&&(n=s.subType),Array.isArray(n)?n.forEach((e=>{o.push({type:`${c.SERVER_PUSH_MESSAGE}:${e}`,data:t})})):o.push({type:`${c.SERVER_PUSH_MESSAGE}:${n}`,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={}));const l={[c.SERVER_PUSH_MESSAGE]:u,[c.SERVER_PUSH_MESSAGE_MULTIPLE]:u,[c.ERROR]:function(e){const{errorCode:t}=e;return[{type:`error:${t}`,data:e}]}};const d=new class{constructor(){this._outerEventEmitter=null,this._innerEventEmitter=null,this._outerEventEmitter=new e,this._innerEventEmitter=new e,this.InnerEventSubType=n}subscribeInnerEvent(e,t,s,o){var n,i;if(["string","number"].includes(typeof t)){const i=t,r=s;null===(n=this._innerEventEmitter)||void 0===n||n.on(`${e}:${i}`,r,o)}else{const o=t;null===(i=this._innerEventEmitter)||void 0===i||i.on(e,o,s)}}emitInnerEvent(e,t){var s,o;if(null===(s=this._innerEventEmitter)||void 0===s||s.emit(e,t),Object.keys(l).includes(e)){const s=null===(o=l[e])||void 0===o?void 0:o.call(l,t);null==s||s.forEach((e=>{var t;e&&(null===(t=this._innerEventEmitter)||void 0===t||t.emit(e.type,e.data))}))}}unSubscribeInnerEvent(e,t,s,o){var n,i;if(["string","number"].includes(typeof t)){const i=t,r=s;null===(n=this._innerEventEmitter)||void 0===n||n.off(`${e}:${i}`,r,o)}else{const o=t;null===(i=this._innerEventEmitter)||void 0===i||i.off(e,o,s)}}subscribeOuterEvent(e,t,s){var o;null===(o=this._outerEventEmitter)||void 0===o||o.on(e,t,s)}unSubscribeOuterEvent(e,t,s){var o;null===(o=this._outerEventEmitter)||void 0===o||o.off(e,t,s)}emitOuterEvent(e,t){var s;null===(s=this._outerEventEmitter)||void 0===s||s.emit(e,t)}getOuterEventEmitter(){return this._outerEventEmitter}rest(){this._outerEventEmitter=null,this._innerEventEmitter=null}};function p(e,t){var s={};for(var o in e)Object.prototype.hasOwnProperty.call(e,o)&&t.indexOf(o)<0&&(s[o]=e[o]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var n=0;for(o=Object.getOwnPropertySymbols(e);n<o.length;n++)t.indexOf(o[n])<0&&Object.prototype.propertyIsEnumerable.call(e,o[n])&&(s[o[n]]=e[o[n]])}return s}function h(e,t,s,o){return new(s||(s=Promise))((function(n,i){function r(e){try{c(o.next(e))}catch(e){i(e)}}function a(e){try{c(o.throw(e))}catch(e){i(e)}}function c(e){var t;e.done?n(e.value):(t=e.value,t instanceof s?t:new s((function(e){e(t)}))).then(r,a)}c((o=o.apply(e,t||[])).next())}))}"function"==typeof SuppressedError&&SuppressedError;const g=e=>void 0===e,_=e=>"string"==typeof e,m=e=>{var t;return null===(t=Object.prototype.toString.call(e).match(/^\[object (.*)\]$/))||void 0===t?void 0:t[1].toLowerCase()},v=e=>"function"==typeof Array.isArray?Array.isArray(e):"array"===m(e),f=e=>null!==e&&"object"==typeof e,I=e=>v(e)||f(e),S=e=>{if("string"!=typeof e)return!1;const t=e[0];return!/[^a-zA-Z0-9]/.test(t)},E=e=>{if("object"!=typeof e||null===e)return!1;const t=Object.getPrototypeOf(e);if(null===t)return!0;let s=t;for(;null!==Object.getPrototypeOf(s);)s=Object.getPrototypeOf(s);return t===s};function C(e=99999999){return Math.round(Math.random()*e)}const M=(e,t,s,o)=>{if(!I(e)||!I(t))return 0;let n=0;const i=Object.keys(t);let r;for(let a=0,c=i.length;a<c;a++)if(r=i[a],!(g(t[r])||s&&s.includes(r)))if(I(e[r])&&I(t[r]))n+=M(e[r],t[r],s,o);else{if(o&&o.includes(t[r]))continue;e[r]!==t[r]&&(e[r]=t[r],n+=1)}return n};function y(e){let t,s,o=e;e.length%8!=0&&(o="0".repeat(8-e.length%8)+e);let n="";for(let e=0,{length:i}=o;e<i;e+=8)t=parseInt(o.slice(e,e+4),2),s=parseInt(o.slice(e+4,e+8),2),n+=base16Map.get(t)+base16Map.get(s);return n}const 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),H=/iPhone/i.test(V)&&!K,W=/iPod/i.test(V),Y=H||K||W,z=function(){const e=V.match(/OS (\d+)_/i);return e&&e[1]?e[1]:null}(),J=/Android/i.test(V),Q=function(){const e=V.match(/Android (\d+)(?:\.(\d+))?(?:\.(\d+))*/i);if(!e)return null;const t=e[1]&&parseFloat(e[1]),s=e[2]&&parseFloat(e[2]);return t&&s?parseFloat(`${e[1]}.${e[2]}`):t||null}(),X=/Firefox/i.test(V),Z=/Edge/i.test(V),ee=!Z&&/Chrome/i.test(V),te=/MSIE/.test(V)||V.indexOf("Trident")>-1&&V.indexOf("rv:11.0")>-1,se=function(){const e=/MSIE\s(\d+)\.\d/.exec(V);let t=e&&parseFloat(e[1]);return!t&&/Trident\/7.0/i.test(V)&&/rv:11.0/.test(V)&&(t=11),t}(),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(){if("undefined"==typeof window||void 0===window.navigator)return!1;const{standalone:e}=window.navigator;return!(!Y||e||oe)}();function le(){let e="unknown";if(ie&&(e="mac"),ne&&(e="windows"),Y&&(e="ios"),J&&(e="android"),U)try{const{platform:t}=wx.getSystemInfoSync();void 0!==t&&(e=t)}catch(e){console.error(e)}return e}const de=2800,pe=2801,he=3e3,ge="application/x-www-form-urlencoded;charset=UTF-8";function _e(e){return h(this,arguments,void 0,(function*({method:e,url:t,data:s,timeout:o=he}){return new Promise(U?(n,i)=>{x.request({url:t,data:s,method:e,timeout:o,header:{"content-type":ge},success:e=>n(e.data),fail:()=>i(new Error(`{"message":"Network error","code":${de}}`))})}:(n,i)=>{const r=new XMLHttpRequest,a=setTimeout((()=>{r.abort(),i(new Error(`{"message":"Request timeout","code":${pe}}`))}),o);r.onreadystatechange=function(){if(4===r.readyState)if(clearTimeout(a),200===r.status||304===r.status)try{n(r.responseText?JSON.parse(r.responseText):null)}catch(e){n(r.responseText)}else i(new Error(`{"message":"Network error","code":${de}}`))},r.open(e,t,!0),r.setRequestHeader("Content-type",ge),r.send(s||null)})}))}function me(e){if(null==e)return!0;if("boolean"==typeof e)return!1;if("number"==typeof e)return 0===e;if("string"==typeof e)return 0===e.length;if("function"==typeof e)return 0===e.length;if(Array.isArray(e))return 0===e.length;if(e instanceof Error)return""===e.message;if(E(e)){for(const t in e)if(Object.prototype.hasOwnProperty.call(e,t))return!1;return!0}return("[object Map]"===Object.prototype.toString.call(e)||"[object Set]"===Object.prototype.toString.call(e)||"[object File]"===Object.prototype.toString.call(e))&&0===e.size}function ve(e){if(null===e||"object"!=typeof e)return e;if(e instanceof Date)return new Date(e.getTime());if(e instanceof RegExp)return new RegExp(e.source,e.flags);if(e instanceof Map){const t=new Map;return e.forEach(((e,s)=>{t.set(ve(s),ve(e))})),t}if(e instanceof Set){const t=new Set;return e.forEach((e=>{t.add(ve(e))})),t}if(Array.isArray(e))return e.map((e=>ve(e)));const t=Object.getPrototypeOf(e),s=Object.create(t);return[...Object.getOwnPropertyNames(e),...Object.getOwnPropertySymbols(e)].forEach((t=>{const o=Object.getOwnPropertyDescriptor(e,t);o&&(o.get||o.set?Object.defineProperty(s,t,o):s[t]=ve(e[t]))})),s}function fe(){let e,t;return{promise:new Promise(((s,o)=>{e=s,t=o})),resolve:e,reject:t}}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:H,IS_IPOD:W,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:_e,isArray:v,isArrayOrObject:I,isEmpty:me,isFlutterWeb:ce,isH5:ae,isIOSWebView:ue,isNumber:e=>null!==e&&("number"==typeof e&&!Number.isNaN(e-0)||"object"==typeof e&&e.constructor===Number),isObject:f,isPlainObject:E,isString:_,isUndefined:g,isValidRequestKey:S,platform:j,randomInt:C,randomString:function(){const e="0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";let t="";for(let s=32;s>0;--s)t+=e[Math.floor(62*Math.random())];return t}});class Se{constructor(){this._socket=null}connectSocket(e){return this._socket=new WebSocket(e),this._socket}send(e){var t,s;try{null===(t=this._socket)||void 0===t||t.send(e)}catch(e){null===(s=this._onSendFail)||void 0===s||s.call(this,e)}}bindSocketHandlers(e){const{onOpen:t,onMessage:s,onClose:o,onError:n,onSendFail:i}=e;this._socket&&(this._socket.binaryType="arraybuffer",this._socket.onopen=t,this._socket.onmessage=s,this._socket.onclose=o,this._socket.onerror=n,this._onSendFail=i)}unbindSocketHandlers(){this._socket&&(this._socket.onopen=null,this._socket.onmessage=null,this._socket.onclose=null,this._socket.onerror=null)}disconnect(){this._socket&&(this._socket.close(),this._socket=null)}}class Ee{connectSocket(e){return this._socket=wx.connectSocket({url:e,header:{"content-type":"application/json"},complete:()=>{}}),this._socket}send(e){var t;null===(t=this._socket)||void 0===t||t.send({data:e,fail:this._onSendFail})}bindSocketHandlers(e){const{onOpen:t,onMessage:s,onClose:o,onError:n,onSendFail:i}=e;this._socket.onClose(o),this._socket.onOpen(t),this._socket.onMessage(s),this._socket.onError(n),this._onSendFail=i}unbindSocketHandlers(){this._socket&&(this._socket.onClose((()=>{})),this._socket.onOpen((()=>{})),this._socket.onMessage((()=>{})),this._socket.onError((()=>{})))}disconnect(){this._socket&&(this._socket.close(),this._socket=null)}}const Ce="CONNECT",Me="SEND",ye="DISCONNECT",Te="OPEN",Ae="MESSAGE",Oe="CLOSE",De="ERROR",Re="SEND_FAIL";class Le{constructor(){this._worker=null,this._blobUrl=null}connectSocket(e){const t=new Blob(["\n let _socket = null;\n\n self.onmessage = (event) => {\n const { type, url, data } = event.data;\n\n switch (type) {\n case 'CONNECT':\n connectSocket(url);\n break;\n case 'SEND':\n send(data);\n break;\n case 'DISCONNECT':\n disconnect();\n break;\n }\n };\n\n function connectSocket(url) {\n _socket = new WebSocket(url);\n _socket.binaryType = 'arraybuffer';\n bindSocketHandlers();\n return _socket;\n }\n\n function send(packet) {\n try {\n _socket?.send(packet);\n } catch (error) {\n self.postMessage({\n type: 'SEND_FAIL', \n error: {\n message: error.message,\n name: error.name,\n },\n });\n }\n }\n\n function bindSocketHandlers() {\n if (_socket) {\n _socket.onopen = (event) => {\n self.postMessage({\n type: 'OPEN',\n data: {\n type: event.type,\n timeStamp: event.timeStamp,\n },\n });\n };\n\n _socket.onmessage = (event) => {\n self.postMessage({ \n type: 'MESSAGE',\n data: event.data,\n });\n };\n\n _socket.onclose = (event) => {\n self.postMessage({ \n type: 'CLOSE', \n data: { \n code: event.code,\n reason: event.reason,\n timeStamp: event.timeStamp,\n },\n });\n };\n\n _socket.onerror = (error) => {\n self.postMessage({\n type: 'ERROR',\n data: {\n message: error.message,\n name: error.name\n },\n });\n };\n }\n }\n\n function unbindSocketHandlers() {\n if (_socket) {\n _socket.onopen = null;\n _socket.onmessage = null;\n _socket.onclose = null;\n _socket.onerror = null;\n }\n }\n\n function disconnect() {\n if (_socket) {\n _socket.close();\n _socket = null;\n }\n }\n"],{type:"application/javascript"});this._worker=new Worker(URL.createObjectURL(t)),this._worker.postMessage({type:Ce,url:e})}send(e){var t,s;try{null===(t=this._worker)||void 0===t||t.postMessage({type:Me,data:e})}catch(e){null===(s=this._onSendFail)||void 0===s||s.call(this,e)}}bindSocketHandlers(e){const{onOpen:t,onMessage:s,onClose:o,onError:n,onSendFail:i}=e;if(this._worker){const e={[Te]:t,[Ae]:s,[Oe]:o,[De]:n,[Re]:i};this._onSendFail=i,this._worker.onmessage=t=>{var s;const{type:o}=(null==t?void 0:t.data)||{};"function"==typeof e[o]&&(null===(s=e[o])||void 0===s||s.call(e,null==t?void 0:t.data))}}}unbindSocketHandlers(){this._worker&&(this._worker.onmessage=null)}disconnect(){this._worker&&(this._worker.postMessage({type:ye}),this._worker.terminate(),this._worker=null),this._blobUrl&&(URL.revokeObjectURL(this._blobUrl),this._blobUrl=null)}}var Ne,be=new class{constructor(){this._store=new Map}get(e){return this._store.get(e)}getStorage(e){if(U){if(N){return my.getStorageSync({key:e}).data}return x.getStorageSync(e)}return this._canUseLocalStorage()?localStorage.getItem(e):{}}set(e,t){const s=this._store.get(e)||{};t instanceof Map?this._store.set(e,t):this._store.set(e,Object.assign(Object.assign({},s),t))}setStorage(e,t){U?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(){const e=be.get("cloudConfig")||{};return(g(e.isWorkerEnabled)||"1"===e.isWorkerEnabled)&&re}}const we="CHINA",Pe="OVERSEA",Ue="SINGAPORE",ke="KOREA",Fe="GERMANY",$e="IND",qe="JPN",xe="USA",Ve="INDONESIA",Be={TEST:{CHINA:{DEFAULT:"wss://wss-dev.tim.qq.com"},OVERSEA:{DEFAULT:"wss://wss-dev.tim.qq.com"},SINGAPORE:{DEFAULT:"wss://wsssgp-dev.im.qcloud.com"},KOREA:{DEFAULT:"wss://wsskr-dev.im.qcloud.com"},GERMANY:{DEFAULT:"wss://wssger-dev.im.qcloud.com"},IND:{DEFAULT:"wss://wssind-dev.im.qcloud.com"},JPN:{DEFAULT:"wss://wssjpn-dev.im.qcloud.com"},USA:{DEFAULT:"wss://wssusa-dev.im.qcloud.com"},INDONESIA:{DEFAULT:"wss://wssidn-dev.im.qcloud.com"}},PRODUCTION:{CHINA:{INITIAL:"wss://*w4c.my-imcloud.com",DEFAULT:"wss://wss.im.qcloud.com",IPV6:"wss://wssv6.im.qcloud.com",BACKUP:"wss://wss.tim.qq.com",STAT:"https://events.im.qcloud.com",ANYCAST:"wss://162.14.13.203"},OVERSEA:{INITIAL:"wss://*w4c.my-imcloud.com",DEFAULT:"wss://wss.im.qcloud.com",IPV6:"wss://wssv6.im.qcloud.com",BACKUP:"wss://wss.my-imcloud.com",STAT:"https://api.my-imcloud.com"},SINGAPORE:{INITIAL:"wss://*w4s.my-imcloud.com",DEFAULT:"wss://wsssgp.im.qcloud.com",IPV6:"wss://wsssgpv6.im.qcloud.com",BACKUP:"wss://wsssgp.my-imcloud.com",STAT:"https://apisgp.my-imcloud.com",ANYCAST:"wss://162.14.19.159"},KOREA:{INITIAL:"wss://*w4k.my-imcloud.com",DEFAULT:"wss://wsskr.im.qcloud.com",IPV6:"wss://wsskrv6.im.qcloud.com",BACKUP:"wss://wsskr.my-imcloud.com",STAT:"https://apikr.my-imcloud.com",ANYCAST:"wss://162.14.13.104"},GERMANY:{INITIAL:"wss://*w4g.my-imcloud.com",DEFAULT:"wss://wssger.im.qcloud.com",IPV6:"wss://wssgerv6.im.qcloud.com",BACKUP:"wss://wssger.my-imcloud.com",STAT:"https://apiger.my-imcloud.com",ANYCAST:"wss://162.14.3.17"},IND:{INITIAL:"wss://*w4i.my-imcloud.com",DEFAULT:"wss://wssind.my-imcloud.com",IPV6:"wss://wssindv6.im.qcloud.com",BACKUP:"wss://wssind.im.qcloud.com",STAT:"https://apiind.my-imcloud.com",ANYCAST:"wss://162.14.19.46"},JPN:{INITIAL:"wss://*w4j.my-imcloud.com",DEFAULT:"wss://wssjpn.im.qcloud.com",IPV6:"wss://wssjpnv6.im.qcloud.com",BACKUP:"wss://wssjpn.my-imcloud.com",STAT:"https://apijpn.my-imcloud.com",ANYCAST:"wss://162.14.13.254"},USA:{INITIAL:"wss://*w4u.my-imcloud.com",DEFAULT:"wss://wssusa.im.qcloud.com",IPV6:"wss://wssusav6.im.qcloud.com",BACKUP:"wss://wssusa.my-imcloud.com",STAT:"https://apiusa.my-imcloud.com",ANYCAST:"wss://162.14.10.42"},INDONESIA:{INITIAL:"wss://*w4y.my-imcloud.com",DEFAULT:"wss://wssidn.im.qcloud.com",IPV6:"wss://wssidnv6.im.qcloud.com",BACKUP:"wss://wssidn.my-imcloud.com",STAT:"https://apiidn.my-imcloud.com",ANYCAST:"wss://43.129.34.169"}}},je={[Ue]:[[2e7,3e7],[172e7,173e7]],[ke]:[[3e7,4e7],[173e7,174e7]],[Fe]:[[4e7,5e7],[174e7,175e7]],[$e]:[[5e7,6e7],[175e7,176e7]],[qe]:[[6e7,7e7],[176e7,177e7]],[xe]:[[7e7,8e7],[177e7,178e7]],[Ve]:[[8e7,9e7],[178e7,179e7]]};function Ke(e){var t;if(null===(t=be.get("instance"))||void 0===t?void 0:t.oversea)return Pe;for(const t of Object.keys(je))for(const[s,o]of je[t])if(e>=s&&e<o)return t;return we}var He,We="1.4.2";!function(e){e.INITIAL="INITIAL",e.DEFAULT="DEFAULT",e.BACKUP="BACKUP",e.ANYCAST="ANYCAST",e.IPV6="IPV6"}(He||(He={}));let Ye=He.INITIAL;function ze(){const e=Math.random();return 0===e?ze():e}function Je(e,t){const{isBinary:s=!1}=t||{},o=be.get("instance"),{sdkAppId:n,instanceId:i}=o,r=ze(),a=le(),c=function(){const e=le();let t=-1;"ios"===e?t=z||-1:"android"===e&&(t=Q||-1);return t}(),u=(l={sdkappid:n,instanceid:i,random:r,platform:j,host:a,version:c,sdkversion:We},Object.keys(l).map((e=>`${e}=${l[e]}`)).join("&"));var l;return s?`${e}/binfo?${u}&compress=gzip`:`${e}/info?${u}`}var Qe=new class{constructor(){this._timeOffsetWithServer=0}getServerTimeMs(){return Date.now()+this._timeOffsetWithServer}getServerTimeSeconds(){return Math.floor(this.getServerTimeMs()/1e3)}getTimeOffsetWithServer(){return this._timeOffsetWithServer}calculateTimeOffsetWithServer(e,t){const s=Date.now(),o=s-e;this._timeOffsetWithServer=t+o-s}};const Xe=16;var Ze=new class{constructor(){this._tasks=[],this._timer=null,this._taskMap=new Map}_addTaskToScheduler(e){const{id:t}=e;this.removeTask(t),this._tasks.push(e),this._taskMap.set(t,e),this._sort(),this._scheduleNextTask()}_createTask(e){const{id:t,callback:s,context:o,isOnce:n=!1,intervalMs:i=Xe}=e,r=Math.max(i,Xe);return{id:t,nextExecuteTime:Date.now()+r,intervalMs:i,callback:s,context:o,isOnce:n}}addTask(e){const t=this._createTask(e);this._addTaskToScheduler(t)}addOnceTask(e){const t=this._createTask(Object.assign(Object.assign({},e),{isOnce:!0}));this._addTaskToScheduler(t)}removeTask(e){const t=this._tasks.findIndex((t=>t.id===e));t>-1&&(this._tasks.splice(t,1),this._taskMap.delete(e),this._scheduleNextTask())}updateTaskInterval(e,t){const s=this._taskMap.get(e);s&&(s.intervalMs=t,s.nextExecuteTime=Date.now()+t,this._sort(),this._scheduleNextTask())}clearAllTasks(){this._tasks=[],this._taskMap.clear(),this._timer&&(clearTimeout(this._timer),this._timer=null)}dispose(){this.clearAllTasks()}_sort(){this._tasks.sort(((e,t)=>e.nextExecuteTime-t.nextExecuteTime))}_scheduleNextTask(){this._timer&&(clearTimeout(this._timer),this._timer=null);const e=this._tasks[0];if(e){const t=Math.max(0,e.nextExecuteTime-Date.now());this._timer=setTimeout((()=>this._execute()),t)}}_execute(){const e=Date.now();for(;this._tasks.length&&this._tasks[0].nextExecuteTime<=e;){const t=this._tasks[0];try{t.context?t.callback.call(t.context):t.callback(),t.isOnce?this.removeTask(t.id):(t.nextExecuteTime=e+t.intervalMs,this._sort())}catch(e){console.warn(`Task ${t.id} execution failed:`,e),t.isOnce&&this.removeTask(t.id)}}this._scheduleNextTask()}};function et(e){const t=[];for(let s=0;s<e.length;s+=1){const o=e.charCodeAt(s);if(o>=55296&&o<=56319){const n=e.charCodeAt(++s)-56320+(o-55296<<10)+65536;t.push(240|n>>18,128|n>>12&63,128|n>>6&63,128|63&n)}else o<=127?t.push(o):o<=2047?t.push(192|o>>6,128|63&o):t.push(224|o>>12,128|o>>6&63,128|63&o)}return new Uint8Array(t)}function st(e){const t=Array.isArray(e)?[]:Object.create(null);for(const s in e)Object.prototype.hasOwnProperty.call(e,s)&&S(s)&&null!=e[s]&&(null===e[s]||"object"!=typeof e[s]?t[s]=e[s]:t[s]=st(e[s]));return t}function ot(e,t){if(s.includes(e))return 0;const o=et(JSON.stringify(t));let n=4294967295;const{length:i}=o;for(let e=0;e<i;e++){n^=o[e];for(let e=0;e<8;e++)1&~n?n>>>=1:n=n>>>1^3988292384}return(4294967295^n)>>>0}function nt(e){const{servcmd:t,data:s}=e,o=function(e){const t=be.get("login")||{},s=be.get("instance")||{};return{servcmd:e,ver:"v4",platform:j,websdkappid:537048168,websdkversion:"1.7.3",a2:t.a2Key||void 0,tinyid:t.tinyID||void 0,status_instid:t.statusInstanceId||0,sdkappid:s.sdkAppId,contenttype:"json",reqtime:Math.floor(Date.now()/1e3),identifier:t.a2Key?void 0:t.userId,usersig:t.a2Key?void 0:t.userSig,sdkability:75689843,sdkability_ext:y(""),cappid:t.cappid||0,tjgID:"",seq:at(),cs:0}}(t),n=st(s);return o.cs=ot(t,n),{head:o,body:n}}function it(e){const{servcmd:t,data:s}=e,o=function(e){const t=be.get("login")||{},s=be.get("instance")||{};return{servcmd:e,ver:"v4",platform:j,websdkappid:537048168,websdkversion:"1.7.3",sdkappid:s.sdkAppId,contenttype:"",reqtime:Math.floor(Date.now()/1e3),identifier:"",usersig:"",status_instid:t.statusInstanceId||0,sdkability:75689843,sdkability_ext:y(""),cappid:t.cappid||0,seq:at(),cs:0}}(t),n=st(s);return o.cs=ot(t,n),{head:o,body:n}}let rt=C();function at(){return rt=rt<2415919103?rt+1:C(),rt}function ct(){const e=be.get("login")||{},t=be.get("instance")||{};return{sdk_type:30,sdk_app_id:t.sdkAppId,sdk_version:"1.4.2",tiny_id:Number(e.tinyID),user_id:e.userId,platform:j,instance_id:t.instanceId,trace_id:(new Date).getTime()}}var ut,lt=Object.freeze({__proto__:null,generateCosSpecifiedData:function(e){const{servcmd:t,data:s}=e,o=function(e){const t=be.get("login")||{},s=be.get("instance")||{};return{servcmd:e,ver:"v4",platform:j,websdkappid:537048168,websdkversion:"1.7.3",sdkappid:s.sdkAppId,contenttype:"json",reqtime:Math.floor(Date.now()/1e3),identifier:t.userId,usersig:t.userSig,status_instid:t.statusInstanceId||0,sdkability:75689843,sdkability_ext:y(""),cappid:t.cappid||0,seq:at(),cs:0}}(t),n=st(s);return o.cs=ot(t,n),{head:o,body:n}},generateProtocolData:nt,generateSSOLogProtocolData:it,generateSequence:at,getCommonHead:ct,taskScheduler:Ze,timeManager:Qe});!function(e){e[e.info=4]="info",e[e.warning=5]="warning",e[e.error=6]="error"}(ut||(ut={}));const dt={method:"extension",networkType:"network_type",eventType:"event_type",code:"error_code",message:"error_message",moreMessage:"more_message",duplicate:"duplicate",costTime:"cost_time",level:"level",uiPlatform:"ui_platform",timestamp:"timestamp"};class pt{constructor(e){this.level=ut.info,this._canSendLog=!0,this._logCreatedAt=Qe.getServerTimeMs(),this.timestamp=0,this.networkType=8,this.code=0,this.moreMessage="",this.method="",this.message="",this.costTime=0,this.duplicate=!1,this.eventType=0,this.uiPlatform=void 0;const{method:t,eventType:s=0,uiPlatform:o,message:n}=e||{};this.eventType=s,this.method=t,this.uiPlatform=o,this.message=n||""}setMoreMessage(e){this.moreMessage=`${this.moreMessage} ${e}`}updateLogCreatedAtByTimeOffset(){this._logCreatedAt+=Qe.getTimeOffsetWithServer()}end(e=!1){if(!this._canSendLog)return;const t=Qe.getServerTimeMs();0===this.costTime&&(this.costTime=t-this._logCreatedAt),this.setMoreMessage(`startts:${this._logCreatedAt} endts:${t}`),e?(this._canSendLog=!1,this.timestamp=Qe.getServerTimeMs(),this._ssoLogModule.pushToLogQueue(this._convertSSOLogDataKeyToServe())):setTimeout((()=>{this._canSendLog=!1,this.timestamp=Qe.getServerTimeMs(),this._ssoLogModule.pushToLogQueue(this._convertSSOLogDataKeyToServe())}),0)}setError(e){var t;if(!(e instanceof Error))return console.warn("SSOLogData.setError value not instanceof Error, please check!"),this;if(!this._canSendLog)return this;return(null===(t=be.get("netWorkMonitor"))||void 0===t?void 0:t.isNetworkOnline)&&(e.errorCode&&(this.code=e.errorCode),e.errorMessage&&this.setMoreMessage(e.errorMessage)),this.level=ut.error,this}setLogInfo(e){return Object.keys(e).forEach((t=>{Object.keys(dt).includes(t)&&(this[t]=e[t])})),this}setSSOLogModule(e){this._ssoLogModule=e}_convertSSOLogDataKeyToServe(){const e={};return Object.keys(this).forEach((t=>{const s=t;dt[s]&&(e[dt[s]]=this[s])})),e}}var ht;!function(e){e.RECONNECTED="reconnected",e.CLOUD_CONFIG_UPDATE="cloud_config_update",e.SOCKET_DISCONNECTED="socket_disconnected"}(ht||(ht={}));var gt=ht;const _t=20,mt=6e4,vt=[4,5,6],ft=[],It=[],St="report-logger";var Et=new class{constructor(){this._sdkAppIdBlackList=[],this._tinyIdWhiteList=[],this._reportLevel=[4,5,6],this._minThreshold=_t,this._maxThreshold=100,this._waitingTime=mt,this._lastReportAt=Date.now(),this._ssoLogMap=new Map,d.subscribeInnerEvent(gt.CLOUD_CONFIG_UPDATE,this._handleCloudConfigUpdate,this),Ze.addTask({id:St,intervalMs:1e3,callback:this._checkAndReportIfDue,context:this}),this._logQueue=[],this._savePlatFormInfo()}_handleCloudConfigUpdate(e){const{evt_rpt_threshold:t=_t,evt_rpt_waiting:s=mt,evt_rpt_level:o=vt,evt_rpt_sdkappid_bl:n=ft,evt_rpt_tinyid_wl:i=It}=e||{};this._sdkAppIdBlackList=n,this._waitingTime=s,this._minThreshold=t,this._reportLevel=o,this._tinyIdWhiteList=i}createSSOLogData(e){const t=new pt(e);return t.setSSOLogModule(this),this._ssoLogMap.set(e.method,t),t}getSSOLogData(e){return this._ssoLogMap.get(e)||{}}pushToLogQueue(e){e&&(this._logQueue.push(e),this._shouldUploadImmediately()&&this.uploadSSOLogData())}_shouldUploadImmediately(){return this._logQueue.length>=this._minThreshold}_isReportDue(){return Date.now()>=this._lastReportAt+this._waitingTime}_checkAndReportIfDue(){this._isReportDue()&&this._logQueue.length>0&&this.uploadSSOLogData()}uploadSSOLogData(){return h(this,void 0,void 0,(function*(){if(0===this._logQueue.length)return;const e=this._logQueue.slice(),t=this._filterLogs(e);if(this._logQueue=[],0===t.length)return void(this._lastReportAt=Date.now());const s={Header:ct(),Event:t};me(s.Header.user_id)||(yield function(e){const t="imopenstat.tim_web_report_v2",s=it({servcmd:t,data:e}),o=`${s.head.seq}${t}`;xt.sendPacket(s,{requestId:o})}(s)),this._lastReportAt=Date.now()}))}_savePlatFormInfo(){var e,t;if(A){const s=null===(t=null===(e=wx.getAccountInfoSync)||void 0===e?void 0:e.call(wx))||void 0===t?void 0:t.miniProgram;if(s){const{appId:e,envVersion:t}=s;be.set("instance",{appId:e,envVersion:t})}}else q&&be.set("instance",{href:window.location.href})}_filterLogs(e){const{tinyID:t}=be.get("login")||{},{sdkAppId:s}=be.get("instance")||{};return this._sdkAppIdBlackList.includes(s)&&!this._tinyIdWhiteList.includes(t)?[]:e.filter((e=>this._reportLevel.includes(e.level)))}reset(){console.log("SSO_LOG_MODULE.reset"),Ze.removeTask(St),d.unSubscribeInnerEvent(gt.CLOUD_CONFIG_UPDATE,this._handleCloudConfigUpdate,this),this._lastReportAt=0,this.uploadSSOLogData(),this._sdkAppIdBlackList=[],this._tinyIdWhiteList=[],this._minThreshold=_t,this._maxThreshold=100,this._waitingTime=mt,this._logQueue=[]}};const Ct=15e3,Mt="Channel",yt="channel_schedule_task",Tt="channel_reconnect_task",At="connected",Ot="connecting",Dt="disconnected",Rt=1e3,Lt="network_status_change",Nt="activity_status_change",bt="send_fail",Gt="reconnect_failed",wt="socket_error",Pt="socket_close";function Ut(e){return Ut="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},Ut(e)}function kt(e){throw new Error('Could not dynamically require "'+e+'". Please configure the dynamicRequireTargets or/and ignoreDynamicRequires option of @rollup/plugin-commonjs appropriately for this require call to work.')}var Ft,$t={exports:{}};var qt=(Ft||(Ft=1,$t.exports=function e(t,s,o){function n(r,a){if(!s[r]){if(!t[r]){if(!a&&kt)return kt(r);if(i)return i(r,!0);var c=new Error("Cannot find module '"+r+"'");throw c.code="MODULE_NOT_FOUND",c}var u=s[r]={exports:{}};t[r][0].call(u.exports,(function(e){return n(t[r][1][e]||e)}),u,u.exports,e,t,s,o)}return s[r].exports}for(var i=kt,r=0;r<o.length;r++)n(o[r]);return n}({1:[function(e,t,s){var o="undefined"!=typeof Uint8Array&&"undefined"!=typeof Uint16Array&&"undefined"!=typeof Int32Array;s.assign=function(e){for(var t,s,o=Array.prototype.slice.call(arguments,1);o.length;){var n=o.shift();if(n){if("object"!=Ut(n))throw new TypeError(n+"must be non-object");for(var i in n)t=n,s=i,Object.prototype.hasOwnProperty.call(t,s)&&(e[i]=n[i])}}return e},s.shrinkBuf=function(e,t){return e.length===t?e:e.subarray?e.subarray(0,t):(e.length=t,e)};var n={arraySet:function(e,t,s,o,n){if(t.subarray&&e.subarray)e.set(t.subarray(s,s+o),n);else for(var i=0;i<o;i++)e[n+i]=t[s+i]},flattenChunks:function(e){var t,s,o,n,i,r;for(t=o=0,s=e.length;t<s;t++)o+=e[t].length;for(r=new Uint8Array(o),t=n=0,s=e.length;t<s;t++)i=e[t],r.set(i,n),n+=i.length;return r}},i={arraySet:function(e,t,s,o,n){for(var i=0;i<o;i++)e[n+i]=t[s+i]},flattenChunks:function(e){return[].concat.apply([],e)}};s.setTyped=function(e){e?(s.Buf8=Uint8Array,s.Buf16=Uint16Array,s.Buf32=Int32Array,s.assign(s,n)):(s.Buf8=Array,s.Buf16=Array,s.Buf32=Array,s.assign(s,i))},s.setTyped(o)},{}],2:[function(e,t,s){var o=e("./common"),n=!0,i=!0;try{String.fromCharCode.apply(null,[0])}catch(e){n=!1}try{String.fromCharCode.apply(null,new Uint8Array(1))}catch(e){i=!1}for(var r=new o.Buf8(256),a=0;a<256;a++)r[a]=252<=a?6:248<=a?5:240<=a?4:224<=a?3:192<=a?2:1;function c(e,t){if(t<65534&&(e.subarray&&i||!e.subarray&&n))return String.fromCharCode.apply(null,o.shrinkBuf(e,t));for(var s="",r=0;r<t;r++)s+=String.fromCharCode(e[r]);return s}r[254]=r[254]=1,s.string2buf=function(e){var t,s,n,i,r,a=e.length,c=0;for(i=0;i<a;i++)55296==(64512&(s=e.charCodeAt(i)))&&i+1<a&&56320==(64512&(n=e.charCodeAt(i+1)))&&(s=65536+(s-55296<<10)+(n-56320),i++),c+=s<128?1:s<2048?2:s<65536?3:4;for(t=new o.Buf8(c),i=r=0;r<c;i++)55296==(64512&(s=e.charCodeAt(i)))&&i+1<a&&56320==(64512&(n=e.charCodeAt(i+1)))&&(s=65536+(s-55296<<10)+(n-56320),i++),s<128?t[r++]=s:(s<2048?t[r++]=192|s>>>6:(s<65536?t[r++]=224|s>>>12:(t[r++]=240|s>>>18,t[r++]=128|s>>>12&63),t[r++]=128|s>>>6&63),t[r++]=128|63&s);return t},s.buf2binstring=function(e){return c(e,e.length)},s.binstring2buf=function(e){for(var t=new o.Buf8(e.length),s=0,n=t.length;s<n;s++)t[s]=e.charCodeAt(s);return t},s.buf2string=function(e,t){var s,o,n,i,a=t||e.length,u=new Array(2*a);for(s=o=0;s<a;)if((n=e[s++])<128)u[o++]=n;else if(4<(i=r[n]))u[o++]=65533,s+=i-1;else{for(n&=2===i?31:3===i?15:7;1<i&&s<a;)n=n<<6|63&e[s++],i--;1<i?u[o++]=65533:n<65536?u[o++]=n:(n-=65536,u[o++]=55296|n>>10&1023,u[o++]=56320|1023&n)}return c(u,o)},s.utf8border=function(e,t){var s;for((t=t||e.length)>e.length&&(t=e.length),s=t-1;0<=s&&128==(192&e[s]);)s--;return s<0||0===s?t:s+r[e[s]]>t?s:t}},{"./common":1}],3:[function(e,t,s){t.exports=function(e,t,s,o){for(var n=65535&e,i=e>>>16&65535,r=0;0!==s;){for(s-=r=2e3<s?2e3:s;i=i+(n=n+t[o++]|0)|0,--r;);n%=65521,i%=65521}return n|i<<16}},{}],4:[function(e,t,s){t.exports={Z_NO_FLUSH:0,Z_PARTIAL_FLUSH:1,Z_SYNC_FLUSH:2,Z_FULL_FLUSH:3,Z_FINISH:4,Z_BLOCK:5,Z_TREES:6,Z_OK:0,Z_STREAM_END:1,Z_NEED_DICT:2,Z_ERRNO:-1,Z_STREAM_ERROR:-2,Z_DATA_ERROR:-3,Z_BUF_ERROR:-5,Z_NO_COMPRESSION:0,Z_BEST_SPEED:1,Z_BEST_COMPRESSION:9,Z_DEFAULT_COMPRESSION:-1,Z_FILTERED:1,Z_HUFFMAN_ONLY:2,Z_RLE:3,Z_FIXED:4,Z_DEFAULT_STRATEGY:0,Z_BINARY:0,Z_TEXT:1,Z_UNKNOWN:2,Z_DEFLATED:8}},{}],5:[function(e,t,s){var o=function(){for(var e,t=[],s=0;s<256;s++){e=s;for(var o=0;o<8;o++)e=1&e?3988292384^e>>>1:e>>>1;t[s]=e}return t}();t.exports=function(e,t,s,n){var i=o,r=n+s;e^=-1;for(var a=n;a<r;a++)e=e>>>8^i[255&(e^t[a])];return~e}},{}],6:[function(e,t,s){t.exports=function(){this.text=0,this.time=0,this.xflags=0,this.os=0,this.extra=null,this.extra_len=0,this.name="",this.comment="",this.hcrc=0,this.done=!1}},{}],7:[function(e,t,s){t.exports=function(e,t){var s,o,n,i,r,a,c,u,l,d,p,h,g,_,m,v,f,I,S,E,C,M,y,T,A;s=e.state,o=e.next_in,T=e.input,n=o+(e.avail_in-5),i=e.next_out,A=e.output,r=i-(t-e.avail_out),a=i+(e.avail_out-257),c=s.dmax,u=s.wsize,l=s.whave,d=s.wnext,p=s.window,h=s.hold,g=s.bits,_=s.lencode,m=s.distcode,v=(1<<s.lenbits)-1,f=(1<<s.distbits)-1;e:do{g<15&&(h+=T[o++]<<g,g+=8,h+=T[o++]<<g,g+=8),I=_[h&v];t:for(;;){if(h>>>=S=I>>>24,g-=S,0==(S=I>>>16&255))A[i++]=65535&I;else{if(!(16&S)){if(!(64&S)){I=_[(65535&I)+(h&(1<<S)-1)];continue t}if(32&S){s.mode=12;break e}e.msg="invalid literal/length code",s.mode=30;break e}E=65535&I,(S&=15)&&(g<S&&(h+=T[o++]<<g,g+=8),E+=h&(1<<S)-1,h>>>=S,g-=S),g<15&&(h+=T[o++]<<g,g+=8,h+=T[o++]<<g,g+=8),I=m[h&f];s:for(;;){if(h>>>=S=I>>>24,g-=S,!(16&(S=I>>>16&255))){if(!(64&S)){I=m[(65535&I)+(h&(1<<S)-1)];continue s}e.msg="invalid distance code",s.mode=30;break e}if(C=65535&I,g<(S&=15)&&(h+=T[o++]<<g,(g+=8)<S&&(h+=T[o++]<<g,g+=8)),c<(C+=h&(1<<S)-1)){e.msg="invalid distance too far back",s.mode=30;break e}if(h>>>=S,g-=S,(S=i-r)<C){if(l<(S=C-S)&&s.sane){e.msg="invalid distance too far back",s.mode=30;break e}if(y=p,(M=0)===d){if(M+=u-S,S<E){for(E-=S;A[i++]=p[M++],--S;);M=i-C,y=A}}else if(d<S){if(M+=u+d-S,(S-=d)<E){for(E-=S;A[i++]=p[M++],--S;);if(M=0,d<E){for(E-=S=d;A[i++]=p[M++],--S;);M=i-C,y=A}}}else if(M+=d-S,S<E){for(E-=S;A[i++]=p[M++],--S;);M=i-C,y=A}for(;2<E;)A[i++]=y[M++],A[i++]=y[M++],A[i++]=y[M++],E-=3;E&&(A[i++]=y[M++],1<E&&(A[i++]=y[M++]))}else{for(M=i-C;A[i++]=A[M++],A[i++]=A[M++],A[i++]=A[M++],2<(E-=3););E&&(A[i++]=A[M++],1<E&&(A[i++]=A[M++]))}break}}break}}while(o<n&&i<a);o-=E=g>>3,h&=(1<<(g-=E<<3))-1,e.next_in=o,e.next_out=i,e.avail_in=o<n?n-o+5:5-(o-n),e.avail_out=i<a?a-i+257:257-(i-a),s.hold=h,s.bits=g}},{}],8:[function(e,t,s){var o=e("../utils/common"),n=e("./adler32"),i=e("./crc32"),r=e("./inffast"),a=e("./inftrees"),c=1,u=2,l=0,d=-2,p=1,h=852,g=592;function _(e){return(e>>>24&255)+(e>>>8&65280)+((65280&e)<<8)+((255&e)<<24)}function m(){this.mode=0,this.last=!1,this.wrap=0,this.havedict=!1,this.flags=0,this.dmax=0,this.check=0,this.total=0,this.head=null,this.wbits=0,this.wsize=0,this.whave=0,this.wnext=0,this.window=null,this.hold=0,this.bits=0,this.length=0,this.offset=0,this.extra=0,this.lencode=null,this.distcode=null,this.lenbits=0,this.distbits=0,this.ncode=0,this.nlen=0,this.ndist=0,this.have=0,this.next=null,this.lens=new o.Buf16(320),this.work=new o.Buf16(288),this.lendyn=null,this.distdyn=null,this.sane=0,this.back=0,this.was=0}function v(e){var t;return e&&e.state?(t=e.state,e.total_in=e.total_out=t.total=0,e.msg="",t.wrap&&(e.adler=1&t.wrap),t.mode=p,t.last=0,t.havedict=0,t.dmax=32768,t.head=null,t.hold=0,t.bits=0,t.lencode=t.lendyn=new o.Buf32(h),t.distcode=t.distdyn=new o.Buf32(g),t.sane=1,t.back=-1,l):d}function f(e){var t;return e&&e.state?((t=e.state).wsize=0,t.whave=0,t.wnext=0,v(e)):d}function I(e,t){var s,o;return e&&e.state?(o=e.state,t<0?(s=0,t=-t):(s=1+(t>>4),t<48&&(t&=15)),t&&(t<8||15<t)?d:(null!==o.window&&o.wbits!==t&&(o.window=null),o.wrap=s,o.wbits=t,f(e))):d}function S(e,t){var s,o;return e?(o=new m,(e.state=o).window=null,(s=I(e,t))!==l&&(e.state=null),s):d}var E,C,M=!0;function y(e){if(M){var t;for(E=new o.Buf32(512),C=new o.Buf32(32),t=0;t<144;)e.lens[t++]=8;for(;t<256;)e.lens[t++]=9;for(;t<280;)e.lens[t++]=7;for(;t<288;)e.lens[t++]=8;for(a(c,e.lens,0,288,E,0,e.work,{bits:9}),t=0;t<32;)e.lens[t++]=5;a(u,e.lens,0,32,C,0,e.work,{bits:5}),M=!1}e.lencode=E,e.lenbits=9,e.distcode=C,e.distbits=5}function T(e,t,s,n){var i,r=e.state;return null===r.window&&(r.wsize=1<<r.wbits,r.wnext=0,r.whave=0,r.window=new o.Buf8(r.wsize)),n>=r.wsize?(o.arraySet(r.window,t,s-r.wsize,r.wsize,0),r.wnext=0,r.whave=r.wsize):(n<(i=r.wsize-r.wnext)&&(i=n),o.arraySet(r.window,t,s-n,i,r.wnext),(n-=i)?(o.arraySet(r.window,t,s-n,n,0),r.wnext=n,r.whave=r.wsize):(r.wnext+=i,r.wnext===r.wsize&&(r.wnext=0),r.whave<r.wsize&&(r.whave+=i))),0}s.inflateReset=f,s.inflateReset2=I,s.inflateResetKeep=v,s.inflateInit=function(e){return S(e,15)},s.inflateInit2=S,s.inflate=function(e,t){var s,h,g,m,v,f,I,S,E,C,M,A,O,D,R,L,N,b,G,w,P,U,k,F,$=0,q=new o.Buf8(4),x=[16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15];if(!e||!e.state||!e.output||!e.input&&0!==e.avail_in)return d;12===(s=e.state).mode&&(s.mode=13),v=e.next_out,g=e.output,I=e.avail_out,m=e.next_in,h=e.input,f=e.avail_in,S=s.hold,E=s.bits,C=f,M=I,U=l;e:for(;;)switch(s.mode){case p:if(0===s.wrap){s.mode=13;break}for(;E<16;){if(0===f)break e;f--,S+=h[m++]<<E,E+=8}if(2&s.wrap&&35615===S){q[s.check=0]=255&S,q[1]=S>>>8&255,s.check=i(s.check,q,2,0),E=S=0,s.mode=2;break}if(s.flags=0,s.head&&(s.head.done=!1),!(1&s.wrap)||(((255&S)<<8)+(S>>8))%31){e.msg="incorrect header check",s.mode=30;break}if(8!=(15&S)){e.msg="unknown compression method",s.mode=30;break}if(E-=4,P=8+(15&(S>>>=4)),0===s.wbits)s.wbits=P;else if(P>s.wbits){e.msg="invalid window size",s.mode=30;break}s.dmax=1<<P,e.adler=s.check=1,s.mode=512&S?10:12,E=S=0;break;case 2:for(;E<16;){if(0===f)break e;f--,S+=h[m++]<<E,E+=8}if(s.flags=S,8!=(255&s.flags)){e.msg="unknown compression method",s.mode=30;break}if(57344&s.flags){e.msg="unknown header flags set",s.mode=30;break}s.head&&(s.head.text=S>>8&1),512&s.flags&&(q[0]=255&S,q[1]=S>>>8&255,s.check=i(s.check,q,2,0)),E=S=0,s.mode=3;case 3:for(;E<32;){if(0===f)break e;f--,S+=h[m++]<<E,E+=8}s.head&&(s.head.time=S),512&s.flags&&(q[0]=255&S,q[1]=S>>>8&255,q[2]=S>>>16&255,q[3]=S>>>24&255,s.check=i(s.check,q,4,0)),E=S=0,s.mode=4;case 4:for(;E<16;){if(0===f)break e;f--,S+=h[m++]<<E,E+=8}s.head&&(s.head.xflags=255&S,s.head.os=S>>8),512&s.flags&&(q[0]=255&S,q[1]=S>>>8&255,s.check=i(s.check,q,2,0)),E=S=0,s.mode=5;case 5:if(1024&s.flags){for(;E<16;){if(0===f)break e;f--,S+=h[m++]<<E,E+=8}s.length=S,s.head&&(s.head.extra_len=S),512&s.flags&&(q[0]=255&S,q[1]=S>>>8&255,s.check=i(s.check,q,2,0)),E=S=0}else s.head&&(s.head.extra=null);s.mode=6;case 6:if(1024&s.flags&&(f<(A=s.length)&&(A=f),A&&(s.head&&(P=s.head.extra_len-s.length,s.head.extra||(s.head.extra=new Array(s.head.extra_len)),o.arraySet(s.head.extra,h,m,A,P)),512&s.flags&&(s.check=i(s.check,h,A,m)),f-=A,m+=A,s.length-=A),s.length))break e;s.length=0,s.mode=7;case 7:if(2048&s.flags){if(0===f)break e;for(A=0;P=h[m+A++],s.head&&P&&s.length<65536&&(s.head.name+=String.fromCharCode(P)),P&&A<f;);if(512&s.flags&&(s.check=i(s.check,h,A,m)),f-=A,m+=A,P)break e}else s.head&&(s.head.name=null);s.length=0,s.mode=8;case 8:if(4096&s.flags){if(0===f)break e;for(A=0;P=h[m+A++],s.head&&P&&s.length<65536&&(s.head.comment+=String.fromCharCode(P)),P&&A<f;);if(512&s.flags&&(s.check=i(s.check,h,A,m)),f-=A,m+=A,P)break e}else s.head&&(s.head.comment=null);s.mode=9;case 9:if(512&s.flags){for(;E<16;){if(0===f)break e;f--,S+=h[m++]<<E,E+=8}if(S!==(65535&s.check)){e.msg="header crc mismatch",s.mode=30;break}E=S=0}s.head&&(s.head.hcrc=s.flags>>9&1,s.head.done=!0),e.adler=s.check=0,s.mode=12;break;case 10:for(;E<32;){if(0===f)break e;f--,S+=h[m++]<<E,E+=8}e.adler=s.check=_(S),E=S=0,s.mode=11;case 11:if(0===s.havedict)return e.next_out=v,e.avail_out=I,e.next_in=m,e.avail_in=f,s.hold=S,s.bits=E,2;e.adler=s.check=1,s.mode=12;case 12:if(5===t||6===t)break e;case 13:if(s.last){S>>>=7&E,E-=7&E,s.mode=27;break}for(;E<3;){if(0===f)break e;f--,S+=h[m++]<<E,E+=8}switch(s.last=1&S,E-=1,3&(S>>>=1)){case 0:s.mode=14;break;case 1:if(y(s),s.mode=20,6!==t)break;S>>>=2,E-=2;break e;case 2:s.mode=17;break;case 3:e.msg="invalid block type",s.mode=30}S>>>=2,E-=2;break;case 14:for(S>>>=7&E,E-=7&E;E<32;){if(0===f)break e;f--,S+=h[m++]<<E,E+=8}if((65535&S)!=(S>>>16^65535)){e.msg="invalid stored block lengths",s.mode=30;break}if(s.length=65535&S,E=S=0,s.mode=15,6===t)break e;case 15:s.mode=16;case 16:if(A=s.length){if(f<A&&(A=f),I<A&&(A=I),0===A)break e;o.arraySet(g,h,m,A,v),f-=A,m+=A,I-=A,v+=A,s.length-=A;break}s.mode=12;break;case 17:for(;E<14;){if(0===f)break e;f--,S+=h[m++]<<E,E+=8}if(s.nlen=257+(31&S),S>>>=5,E-=5,s.ndist=1+(31&S),S>>>=5,E-=5,s.ncode=4+(15&S),S>>>=4,E-=4,286<s.nlen||30<s.ndist){e.msg="too many length or distance symbols",s.mode=30;break}s.have=0,s.mode=18;case 18:for(;s.have<s.ncode;){for(;E<3;){if(0===f)break e;f--,S+=h[m++]<<E,E+=8}s.lens[x[s.have++]]=7&S,S>>>=3,E-=3}for(;s.have<19;)s.lens[x[s.have++]]=0;if(s.lencode=s.lendyn,s.lenbits=7,k={bits:s.lenbits},U=a(0,s.lens,0,19,s.lencode,0,s.work,k),s.lenbits=k.bits,U){e.msg="invalid code lengths set",s.mode=30;break}s.have=0,s.mode=19;case 19:for(;s.have<s.nlen+s.ndist;){for(;L=($=s.lencode[S&(1<<s.lenbits)-1])>>>16&255,N=65535&$,!((R=$>>>24)<=E);){if(0===f)break e;f--,S+=h[m++]<<E,E+=8}if(N<16)S>>>=R,E-=R,s.lens[s.have++]=N;else{if(16===N){for(F=R+2;E<F;){if(0===f)break e;f--,S+=h[m++]<<E,E+=8}if(S>>>=R,E-=R,0===s.have){e.msg="invalid bit length repeat",s.mode=30;break}P=s.lens[s.have-1],A=3+(3&S),S>>>=2,E-=2}else if(17===N){for(F=R+3;E<F;){if(0===f)break e;f--,S+=h[m++]<<E,E+=8}E-=R,P=0,A=3+(7&(S>>>=R)),S>>>=3,E-=3}else{for(F=R+7;E<F;){if(0===f)break e;f--,S+=h[m++]<<E,E+=8}E-=R,P=0,A=11+(127&(S>>>=R)),S>>>=7,E-=7}if(s.have+A>s.nlen+s.ndist){e.msg="invalid bit length repeat",s.mode=30;break}for(;A--;)s.lens[s.have++]=P}}if(30===s.mode)break;if(0===s.lens[256]){e.msg="invalid code -- missing end-of-block",s.mode=30;break}if(s.lenbits=9,k={bits:s.lenbits},U=a(c,s.lens,0,s.nlen,s.lencode,0,s.work,k),s.lenbits=k.bits,U){e.msg="invalid literal/lengths set",s.mode=30;break}if(s.distbits=6,s.distcode=s.distdyn,k={bits:s.distbits},U=a(u,s.lens,s.nlen,s.ndist,s.distcode,0,s.work,k),s.distbits=k.bits,U){e.msg="invalid distances set",s.mode=30;break}if(s.mode=20,6===t)break e;case 20:s.mode=21;case 21:if(6<=f&&258<=I){e.next_out=v,e.avail_out=I,e.next_in=m,e.avail_in=f,s.hold=S,s.bits=E,r(e,M),v=e.next_out,g=e.output,I=e.avail_out,m=e.next_in,h=e.input,f=e.avail_in,S=s.hold,E=s.bits,12===s.mode&&(s.back=-1);break}for(s.back=0;L=($=s.lencode[S&(1<<s.lenbits)-1])>>>16&255,N=65535&$,!((R=$>>>24)<=E);){if(0===f)break e;f--,S+=h[m++]<<E,E+=8}if(L&&!(240&L)){for(b=R,G=L,w=N;L=($=s.lencode[w+((S&(1<<b+G)-1)>>b)])>>>16&255,N=65535&$,!(b+(R=$>>>24)<=E);){if(0===f)break e;f--,S+=h[m++]<<E,E+=8}S>>>=b,E-=b,s.back+=b}if(S>>>=R,E-=R,s.back+=R,s.length=N,0===L){s.mode=26;break}if(32&L){s.back=-1,s.mode=12;break}if(64&L){e.msg="invalid literal/length code",s.mode=30;break}s.extra=15&L,s.mode=22;case 22:if(s.extra){for(F=s.extra;E<F;){if(0===f)break e;f--,S+=h[m++]<<E,E+=8}s.length+=S&(1<<s.extra)-1,S>>>=s.extra,E-=s.extra,s.back+=s.extra}s.was=s.length,s.mode=23;case 23:for(;L=($=s.distcode[S&(1<<s.distbits)-1])>>>16&255,N=65535&$,!((R=$>>>24)<=E);){if(0===f)break e;f--,S+=h[m++]<<E,E+=8}if(!(240&L)){for(b=R,G=L,w=N;L=($=s.distcode[w+((S&(1<<b+G)-1)>>b)])>>>16&255,N=65535&$,!(b+(R=$>>>24)<=E);){if(0===f)break e;f--,S+=h[m++]<<E,E+=8}S>>>=b,E-=b,s.back+=b}if(S>>>=R,E-=R,s.back+=R,64&L){e.msg="invalid distance code",s.mode=30;break}s.offset=N,s.extra=15&L,s.mode=24;case 24:if(s.extra){for(F=s.extra;E<F;){if(0===f)break e;f--,S+=h[m++]<<E,E+=8}s.offset+=S&(1<<s.extra)-1,S>>>=s.extra,E-=s.extra,s.back+=s.extra}if(s.offset>s.dmax){e.msg="invalid distance too far back",s.mode=30;break}s.mode=25;case 25:if(0===I)break e;if(A=M-I,s.offset>A){if((A=s.offset-A)>s.whave&&s.sane){e.msg="invalid distance too far back",s.mode=30;break}A>s.wnext?(A-=s.wnext,O=s.wsize-A):O=s.wnext-A,A>s.length&&(A=s.length),D=s.window}else D=g,O=v-s.offset,A=s.length;for(I<A&&(A=I),I-=A,s.length-=A;g[v++]=D[O++],--A;);0===s.length&&(s.mode=21);break;case 26:if(0===I)break e;g[v++]=s.length,I--,s.mode=21;break;case 27:if(s.wrap){for(;E<32;){if(0===f)break e;f--,S|=h[m++]<<E,E+=8}if(M-=I,e.total_out+=M,s.total+=M,M&&(e.adler=s.check=s.flags?i(s.check,g,M,v-M):n(s.check,g,M,v-M)),M=I,(s.flags?S:_(S))!==s.check){e.msg="incorrect data check",s.mode=30;break}E=S=0}s.mode=28;case 28:if(s.wrap&&s.flags){for(;E<32;){if(0===f)break e;f--,S+=h[m++]<<E,E+=8}if(S!==(4294967295&s.total)){e.msg="incorrect length check",s.mode=30;break}E=S=0}s.mode=29;case 29:U=1;break e;case 30:U=-3;break e;case 31:return-4;default:return d}return e.next_out=v,e.avail_out=I,e.next_in=m,e.avail_in=f,s.hold=S,s.bits=E,(s.wsize||M!==e.avail_out&&s.mode<30&&(s.mode<27||4!==t))&&T(e,e.output,e.next_out,M-e.avail_out)?(s.mode=31,-4):(C-=e.avail_in,M-=e.avail_out,e.total_in+=C,e.total_out+=M,s.total+=M,s.wrap&&M&&(e.adler=s.check=s.flags?i(s.check,g,M,e.next_out-M):n(s.check,g,M,e.next_out-M)),e.data_type=s.bits+(s.last?64:0)+(12===s.mode?128:0)+(20===s.mode||15===s.mode?256:0),(0===C&&0===M||4===t)&&U===l&&(U=-5),U)},s.inflateEnd=function(e){if(!e||!e.state)return d;var t=e.state;return t.window&&(t.window=null),e.state=null,l},s.inflateGetHeader=function(e,t){var s;return e&&e.state&&2&(s=e.state).wrap?((s.head=t).done=!1,l):d},s.inflateSetDictionary=function(e,t){var s,o=t.length;return e&&e.state?0!==(s=e.state).wrap&&11!==s.mode?d:11===s.mode&&n(1,t,o,0)!==s.check?-3:T(e,t,o,o)?(s.mode=31,-4):(s.havedict=1,l):d},s.inflateInfo="pako inflate (from Nodeca project)"},{"../utils/common":1,"./adler32":3,"./crc32":5,"./inffast":7,"./inftrees":9}],9:[function(e,t,s){var o=e("../utils/common"),n=[3,4,5,6,7,8,9,10,11,13,15,17,19,23,27,31,35,43,51,59,67,83,99,115,131,163,195,227,258,0,0],i=[16,16,16,16,16,16,16,16,17,17,17,17,18,18,18,18,19,19,19,19,20,20,20,20,21,21,21,21,16,72,78],r=[1,2,3,4,5,7,9,13,17,25,33,49,65,97,129,193,257,385,513,769,1025,1537,2049,3073,4097,6145,8193,12289,16385,24577,0,0],a=[16,16,16,16,17,17,18,18,19,19,20,20,21,21,22,22,23,23,24,24,25,25,26,26,27,27,28,28,29,29,64,64];t.exports=function(e,t,s,c,u,l,d,p){var h,g,_,m,v,f,I,S,E,C=p.bits,M=0,y=0,T=0,A=0,O=0,D=0,R=0,L=0,N=0,b=0,G=null,w=0,P=new o.Buf16(16),U=new o.Buf16(16),k=null,F=0;for(M=0;M<=15;M++)P[M]=0;for(y=0;y<c;y++)P[t[s+y]]++;for(O=C,A=15;1<=A&&0===P[A];A--);if(A<O&&(O=A),0===A)return u[l++]=20971520,u[l++]=20971520,p.bits=1,0;for(T=1;T<A&&0===P[T];T++);for(O<T&&(O=T),M=L=1;M<=15;M++)if(L<<=1,(L-=P[M])<0)return-1;if(0<L&&(0===e||1!==A))return-1;for(U[1]=0,M=1;M<15;M++)U[M+1]=U[M]+P[M];for(y=0;y<c;y++)0!==t[s+y]&&(d[U[t[s+y]]++]=y);if(0===e?(G=k=d,f=19):1===e?(G=n,w-=257,k=i,F-=257,f=256):(G=r,k=a,f=-1),M=T,v=l,R=y=b=0,_=-1,m=(N=1<<(D=O))-1,1===e&&852<N||2===e&&592<N)return 1;for(;;){for(I=M-R,d[y]<f?(S=0,E=d[y]):d[y]>f?(S=k[F+d[y]],E=G[w+d[y]]):(S=96,E=0),h=1<<M-R,T=g=1<<D;u[v+(b>>R)+(g-=h)]=I<<24|S<<16|E,0!==g;);for(h=1<<M-1;b&h;)h>>=1;if(0!==h?(b&=h-1,b+=h):b=0,y++,0==--P[M]){if(M===A)break;M=t[s+d[y]]}if(O<M&&(b&m)!==_){for(0===R&&(R=O),v+=T,L=1<<(D=M-R);D+R<A&&!((L-=P[D+R])<=0);)D++,L<<=1;if(N+=1<<D,1===e&&852<N||2===e&&592<N)return 1;u[_=b&m]=O<<24|D<<16|v-l}}return 0!==b&&(u[v+b]=M-R<<24|64<<16),p.bits=O,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 o=e("./zlib/inflate"),n=e("./utils/common"),i=e("./utils/strings"),r=e("./zlib/constants"),a=e("./zlib/messages"),c=e("./zlib/zstream"),u=e("./zlib/gzheader"),l=Object.prototype.toString;function d(e){if(!(this instanceof d))return new d(e);this.options=n.assign({chunkSize:16384,windowBits:0,to:""},e||{});var t=this.options;t.raw&&0<=t.windowBits&&t.windowBits<16&&(t.windowBits=-t.windowBits,0===t.windowBits&&(t.windowBits=-15)),!(0<=t.windowBits&&t.windowBits<16)||e&&e.windowBits||(t.windowBits+=32),15<t.windowBits&&t.windowBits<48&&!(15&t.windowBits)&&(t.windowBits|=15),this.err=0,this.msg="",this.ended=!1,this.chunks=[],this.strm=new c,this.strm.avail_out=0;var s=o.inflateInit2(this.strm,t.windowBits);if(s!==r.Z_OK)throw new Error(a[s]);if(this.header=new u,o.inflateGetHeader(this.strm,this.header),t.dictionary&&("string"==typeof t.dictionary?t.dictionary=i.string2buf(t.dictionary):"[object ArrayBuffer]"===l.call(t.dictionary)&&(t.dictionary=new Uint8Array(t.dictionary)),t.raw&&(s=o.inflateSetDictionary(this.strm,t.dictionary))!==r.Z_OK))throw new Error(a[s])}function p(e,t){var s=new d(t);if(s.push(e,!0),s.err)throw s.msg||a[s.err];return s.result}d.prototype.push=function(e,t){var s,a,c,u,d,p=this.strm,h=this.options.chunkSize,g=this.options.dictionary,_=!1;if(this.ended)return!1;a=t===~~t?t:!0===t?r.Z_FINISH:r.Z_NO_FLUSH,"string"==typeof e?p.input=i.binstring2buf(e):"[object ArrayBuffer]"===l.call(e)?p.input=new Uint8Array(e):p.input=e,p.next_in=0,p.avail_in=p.input.length;do{if(0===p.avail_out&&(p.output=new n.Buf8(h),p.next_out=0,p.avail_out=h),(s=o.inflate(p,r.Z_NO_FLUSH))===r.Z_NEED_DICT&&g&&(s=o.inflateSetDictionary(this.strm,g)),s===r.Z_BUF_ERROR&&!0===_&&(s=r.Z_OK,_=!1),s!==r.Z_STREAM_END&&s!==r.Z_OK)return this.onEnd(s),!(this.ended=!0);p.next_out&&(0!==p.avail_out&&s!==r.Z_STREAM_END&&(0!==p.avail_in||a!==r.Z_FINISH&&a!==r.Z_SYNC_FLUSH)||("string"===this.options.to?(c=i.utf8border(p.output,p.next_out),u=p.next_out-c,d=i.buf2string(p.output,c),p.next_out=u,p.avail_out=h-u,u&&n.arraySet(p.output,p.output,c,u,0),this.onData(d)):this.onData(n.shrinkBuf(p.output,p.next_out)))),0===p.avail_in&&0===p.avail_out&&(_=!0)}while((0<p.avail_in||0===p.avail_out)&&s!==r.Z_STREAM_END);return s===r.Z_STREAM_END&&(a=r.Z_FINISH),a===r.Z_FINISH?(s=o.inflateEnd(this.strm),this.onEnd(s),this.ended=!0,s===r.Z_OK):a!==r.Z_SYNC_FLUSH||(this.onEnd(r.Z_OK),!(p.avail_out=0))},d.prototype.onData=function(e){this.chunks.push(e)},d.prototype.onEnd=function(e){e===r.Z_OK&&("string"===this.options.to?this.result=this.chunks.join(""):this.result=n.flattenChunks(this.chunks)),this.chunks=[],this.err=e,this.msg=this.strm.msg},s.Inflate=d,s.inflate=p,s.inflateRaw=function(e,t){return(t=t||{}).raw=!0,p(e,t)},s.ungzip=p},{"./utils/common":1,"./utils/strings":2,"./zlib/constants":4,"./zlib/gzheader":6,"./zlib/inflate":8,"./zlib/messages":10,"./zlib/zstream":11}]},{},[])("/lib/inflate.js")),$t.exports);var xt=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=Rt,this._currentConnectState=At,this._beforeSendInterceptors=[]}init(){Ze.addTask({id:yt,intervalMs:1e3,callback:this._executeScheduledTaskIfReady,context:this}),this._updateIsBinarySupported(),this._url=function(e){const t=be.get("instance"),{sdkAppId:s,testEnv:o}=t,n=Ke(s);return Je(o?Be.TEST[n].DEFAULT:Be.PRODUCTION[n].INITIAL.replace("*",`${s}`),{isBinary:e})}(this._isBinarySupported),d.subscribeInnerEvent("networkStatusChange",this._handleNetworkStatusChange,this),d.subscribeInnerEvent("activityStatusChange",this._handleActivityStatusChange,this),this.connect()}sendPacket(e,t){var s;const{requestId:o,timeout:n=Ct,canResend:i=!0}=t||{};if(me(e))return console.warn(`${Mt}.sendPacket: packet is empty `,e),null;this._executeBeforeSendInterceptors(e),this._currentConnectState===Dt&&this._handleConnectStateChange({state:Dt,shouldEmitEvent:!0,shouldAttemptReconnect:!0,reason:bt});const r=JSON.stringify(e);let a=null;if(o){const{resolve:e,reject:t,promise:s}=fe();a=s,this._pendingRequests.set(o,{resolve:e,reject:t,timestamp:Date.now(),uplinkData:r,timeout:n,canResend:i})}const c=this._isBinarySupported?et(r).buffer:r;return null===(s=this._socketAdapter)||void 0===s||s.send(c),a}connect(){var e;this._socketAdapter=new Ge(this._url),this._connectionEstablishedTime=0,this._addEventListeners(),this._connectionStartTime=Date.now();const t=null===(e=this._socketAdapter)||void 0===e?void 0:e.getId(),s=`${Mt}.connect isWorkerEnabled: false socketID:${t} url:${this._url}`;this._connectionId=t,this._ssoLog({method:"connect",message:s}),console.log(s)}disconnect(){var e,t;const s=null===(e=this._socketAdapter)||void 0===e?void 0:e.getId(),o=`${Mt}.disconnect socketID:${s}`;this._ssoLog({method:"disconnect",message:o}),console.log(o),this._removeEventListeners(),null===(t=this._socketAdapter)||void 0===t||t.disconnect()}getSocketAdapter(){return this._socketAdapter}dispose(){console.log(`${Mt}.dispose`),Ze.removeTask(yt),Ze.removeTask(Tt),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=Rt,this._url=""}registerBeforeSendInterceptor(e,t){this._beforeSendInterceptors.push(e.bind(t))}_executeBeforeSendInterceptors(e){for(const t of this._beforeSendInterceptors){const{servcmd:s=""}=null==e?void 0:e.head;t(s.includes(".")?s.split(".").pop():"")}}_shouldSkipReconnect(){const e=this._currentConnectState===Ot&&this._isReconnecting;return!this._socketAdapter||e}reconnect(){return h(this,void 0,void 0,(function*(){const e=`${Mt}.reconnect isReconnecting: ${this._isReconnecting} currentConnectState: ${this._currentConnectState}`;if(this._ssoLog({method:"reconnect",message:e}),console.log(e),!this._shouldSkipReconnect()){this._url=function(e){const t=be.get("instance"),{sdkAppId:s,testEnv:o}=t,n=Ke(s);if(o)return Je(Be.TEST[n].DEFAULT,{isBinary:e});const i=Be.PRODUCTION[n],r=q&&i.ANYCAST;return Je({[He.INITIAL]:()=>(Ye=He.DEFAULT,i.DEFAULT),[He.DEFAULT]:()=>(Ye=He.IPV6,i.IPV6),[He.IPV6]:()=>(Ye=He.BACKUP,i.BACKUP),[He.BACKUP]:()=>(Ye=r?He.ANYCAST:He.DEFAULT,r?i.ANYCAST:i.DEFAULT),[He.ANYCAST]:()=>(Ye=He.DEFAULT,i.ANYCAST="",i.DEFAULT)}[Ye](),{isBinary:e})}(this._isBinarySupported);try{this._isReconnecting=!0,this.disconnect(),this.connect()}catch(e){this._isReconnecting=!1,this._handleConnectStateChange({state:Dt,shouldEmitEvent:!0,shouldAttemptReconnect:!0,reason:Gt}),console.warn(`${Mt}.reconnect failed: `,e)}}}))}_addEventListeners(){var e,t,s,o,n;null===(e=this._socketAdapter)||void 0===e||e.on("connect",this._onConnect,this),null===(t=this._socketAdapter)||void 0===t||t.on("message",this._onMessage,this),null===(s=this._socketAdapter)||void 0===s||s.on("close",this._onClose,this),null===(o=this._socketAdapter)||void 0===o||o.on("error",this._onError,this),null===(n=this._socketAdapter)||void 0===n||n.on("sendFail",this._onSendFail,this)}_removeEventListeners(){var e,t,s,o,n;null===(e=this._socketAdapter)||void 0===e||e.off("connect",this._onConnect,this),null===(t=this._socketAdapter)||void 0===t||t.off("message",this._onMessage,this),null===(s=this._socketAdapter)||void 0===s||s.off("close",this._onClose,this),null===(o=this._socketAdapter)||void 0===o||o.off("error",this._onError,this),null===(n=this._socketAdapter)||void 0===n||n.off("sendFail",this._onSendFail,this)}_onClose(e){const{socketId:t,event:s}=e||{},o=0!==this._connectionEstablishedTime?Date.now()-this._connectionEstablishedTime:0,n=`${Mt}.onClose closeSocketID: ${t} currentSocketID: ${this._connectionId} connectionDuration: ${o} code: ${null==s?void 0:s.code} reason: ${null==s?void 0:s.reason}`;this._ssoLog({method:"onClose",message:n}),console.warn(n),t===this._connectionId&&this._handleConnectStateChange({state:Dt,shouldEmitEvent:!0,shouldAttemptReconnect:!0,reason:Pt}),this._isReconnecting&&(this._isReconnecting=!1)}_onError(e){const{socketId:t,error:s}=e||{},o=`${Mt}.onError sourceSocketID: ${t} currentSocketID: ${this._connectionId} isReconnecting: ${this._isReconnecting} error: ${JSON.stringify(s)}`;this._ssoLog({method:"onError",message:o}),console.warn(o),t===this._connectionId&&this._handleConnectStateChange({state:Dt,shouldEmitEvent:!0,shouldAttemptReconnect:!0,reason:wt}),this._isReconnecting&&(this._isReconnecting=!1)}_onSendFail(e){const{socketId:t,error:s}=e||{},o=`${Mt}.onSendFail sendFailSocketId: ${t} currentSocketID: ${this._connectionId} isReconnecting: ${this._isReconnecting} error: ${s}`;this._ssoLog({method:"onSendFail",message:o}),console.warn(o),this._isReconnecting&&(this._isReconnecting=!1)}_onMessage(e){let t,s;this._updateHeartbeatTime();try{t=this._isBinarySupported?this._isCompressedData(e.data)?(e=>{const t=new Uint8Array(e).slice(4);let s;try{s=qt.inflate(t,{to:"string"})}catch(e){console.error("inflate error",e)}return s})(e.data):function(e){const t=new Uint8Array(e);let s="",o=0;const{length:n}=t;for(;o<n;){let e=t[o],i=0,r=0;if(e<=127?(i=0,r=255&e):e<=223?(i=1,r=31&e):e<=239?(i=2,r=15&e):e<=244&&(i=3,r=7&e),n-o-i>0)for(let s=0;s<i;s+=1)e=t[o+s+1],r=r<<6|63&e;else r=65533,i=n-o;s+=String.fromCodePoint(r),o+=i+1}return s}(e.data):e.data,s=JSON.parse(t)}catch(t){const s=e.data;return this._ssoLog({method:"jsonParseError",message:s}),void console.error(t)}if(!s||!s.head)return;const{seq:o,servcmd:n}=s.head,i=`${o}${n}`;this._pendingRequests.has(i)?this._handleRequestResponse(s):this._handlePushMessage(s)}_handleRequestResponse(e){const{seq:t,servcmd:s}=e.head,{int32_error_code:o,str_error_message:n,ErrorCode:i=o,ErrorInfo:r=n}=(null==e?void 0:e.body)||{},a=`${t}${s}`,{resolve:c,reject:u,timestamp:l,headSeq:p}=this._pendingRequests.get(a);if(this._pendingRequests.delete(a),i&&0!==i)return d.emitInnerEvent("error",{errorCode:i,errorInfo:r}),void u({errorCode:i,errorInfo:r});c(e.body)}_handlePushMessage(e){const{servcmd:t}=e.head,{NeedAck:s,SessionData:o}=e.body;1===s&&this._sendAck(o),d.emitInnerEvent(t,e)}_checkPendingRequestsAndResend(){var e;console.log(`${Mt}._checkPendingRequestsAndResend reConnectFlag:${this._isReconnecting} promiseMap.size:${this._pendingRequests.size}`),null===(e=this._pendingRequests)||void 0===e||e.forEach(((e,t)=>{var s;const{uplinkData:o,canResend:n,resolve:i,reject:r,timeout:a}=e;if(n){this._pendingRequests.set(t,{resolve:i,reject:r,timestamp:Date.now(),uplinkData:o,timeout:a,canResend:n});const e=this._isBinarySupported?et(o).buffer:o;null===(s=this._socketAdapter)||void 0===s||s.send(e)}else this._pendingRequests.delete(t)}))}_onConnect(e){const{socketId:t,event:s={}}=e||{};this._connectionId=t,this._connectionEstablishedTime=Date.now();const o=Date.now()-this._connectionStartTime,n=`${Mt}.onConnect cost:${o} ms. socketID:${t} res:${JSON.stringify(s)}`;if(this._ssoLog({method:"onConnect",message:n}),console.log(n),this._checkPendingRequestsAndResend(),this._sendHeartbeatIfReady(),this._isReconnecting){const e=`${Mt}.reconnect success`;this._ssoLog({method:"reconnectSuccess",message:e}),console.log(e),d.emitInnerEvent(gt.RECONNECTED),this._isReconnecting=!1}this._resetReconnectDelay(),this._handleConnectStateChange({state:At,shouldEmitEvent:!0,shouldAttemptReconnect:!1})}_sendAck(e){const t=nt({servcmd:"openim.ws_msg_push_ack",data:{SessionData:e}});this.sendPacket(t)}_executeScheduledTaskIfReady(){return h(this,void 0,void 0,(function*(){this._clearTimeoutRequest(),this._sendHeartbeatIfReady()}))}_canSendHeartbeat(){var e;return(null===(e=this._socketAdapter)||void 0===e?void 0:e.isConnected())&&Date.now()>=this._nextHeartbeatAt&&!this._isHeartbeatInProgress}_sendHeartbeat(){return h(this,void 0,void 0,(function*(){var e;const t=nt({servcmd:"heartbeat.alive",data:{}});try{const e=`${t.head.seq}${t.head.servcmd}`;yield this.sendPacket(t,{requestId:e,timeout:3e3})}catch(t){const s=null===(e=be.get("netWorkMonitor"))||void 0===e?void 0:e.isNetWorkOnline,o=`${Mt}.sendHeartbeat failed. isNetWorkOnline:${s} error: ${t}`;this._ssoLog({method:"sendHeartbeatError",message:o}),console.debug(o),this._handleConnectStateChange({state:Dt,shouldEmitEvent:!0,shouldAttemptReconnect:!0})}}))}_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){const t=`${Mt}.networkStatusChange ${JSON.stringify(e)}`;this._ssoLog({method:"networkStatusChange",message:t}),console.warn(t);const{isNetworkOnline:s,networkType:o}=e;s&&"none"!==o?this._handleConnectStateChange({state:At,shouldEmitEvent:!1,shouldAttemptReconnect:!0,reason:Lt}):this._handleConnectStateChange({state:Dt,shouldEmitEvent:!1,shouldAttemptReconnect:!0,reason:Lt})}isPrivateNetWork(){const e=be.get("instance")||{};return e.proxyServer&&!e.fileDownloadProxy}_handleConnectStateChange(e){const{state:t,shouldAttemptReconnect:s,shouldEmitEvent:o,reason:n}=e,i=`${Mt}._handleConnectStateChange currentConnectState: ${this._currentConnectState} shouldAttemptReconnect: ${s} shouldEmitEvent: ${o} reason: ${n}`;this._currentConnectState!==t&&(this._ssoLog({method:"handleConnectStateChange",message:i}),console.log(i),o&&(console.log(`${Mt}._handleConnectStateChange from ${this._currentConnectState} to ${t}`),d.emitOuterEvent("netStateChange",{name:"netStateChange",data:{state:t}}),this._currentConnectState=t,t===Dt&&d.emitInnerEvent(gt.SOCKET_DISCONNECTED)),s&&(this._resetReconnectDelay(),Ze.addTask({id:Tt,intervalMs:this._intendedDelay,callback:this._scheduleReconnectWithBackoff,context:this})))}_handleActivityStatusChange(e){var t,s;const o=null===(s=null===(t=this._socketAdapter)||void 0===t?void 0:t._ws)||void 0===s?void 0:s.readyState,n=`${Mt}.activityStatusChange ${JSON.stringify(e)} readyState: ${o}`;this._ssoLog({method:"activityStatusChange",message:n}),console.warn(n),3===o&&this._handleConnectStateChange({state:Dt,shouldEmitEvent:!0,shouldAttemptReconnect:!0,reason:Nt})}_resetReconnectDelay(){var e;console.log(`${Mt}._resetReconnectDelay`),Ze.removeTask(Tt);const t=null===(e=be.get("activityMonitor"))||void 0===e?void 0:e.isActive;this._intendedDelay=t?Rt:1e3}_scheduleReconnectWithBackoff(){var e;const t=null===(e=be.get("activityMonitor"))||void 0===e?void 0:e.isActive;this._intendedDelay=t?Math.min(5e3,Math.max(Rt,1.5*this._intendedDelay)):Math.min(3e5,Math.max(1e3,1.5*this._intendedDelay));const s=(new Date).toTimeString().slice(0,8),o=`${Mt}.scheduleReconnectWithBackoff timeStr: ${s} intendedDelay: ${this._intendedDelay}`;this._ssoLog({method:"scheduleReconnectWithBackoff",message:o}),console.log(o),this.reconnect(),Ze.updateTaskInterval(Tt,this._intendedDelay)}_ssoLog(e){const{method:t,message:s}=e;Et.createSSOLogData({method:t}).setLogInfo({message:s}).end()}_diagnose(){this.isPrivateNetWork()||(this._lastDiagnoseAt=Date.now(),function(e){h(this,void 0,void 0,(function*(){const t=e.split("/")[2];if(!t.startsWith("ws"))return;const s=`https://${t}/v3/netcheck/getconninfo?${e.slice(e.indexOf("info?")+5)}&reqtime=${Date.now()}`;try{yield _e({method:"GET",url:s,data:{}})}catch(e){console.warn("diagnoseBySSO failed. error:",e)}}))}(this._url),function(e){h(this,void 0,void 0,(function*(){const t=`https://boce-cdn.my-imcloud.com/v3/netcheck/getconninfo?${e.slice(e.indexOf("info?")+5)}&reqtime=${Date.now()}`;try{yield _e({method:"GET",url:t,data:{}})}catch(e){console.warn("diagnoseByCDN failed. error:",e)}}))}(this._url),this._beforeSendInterceptors=[])}_clearTimeoutRequest(){for(const[e,t]of this._pendingRequests.entries()){const{reject:s,timestamp:o,timeout:n}=t;Date.now()-o>=n&&(this._pendingRequests.delete(e),Date.now()-this._lastDiagnoseAt>=3e4&&this._diagnose(),s({errorCode:pe,errorInfo:"NETWORK_TIMEOUT",data:{requestId:e}}))}}_updateIsBinarySupported(){var e;if(null===(e=be.get("instance"))||void 0===e?void 0:e.devMode)return void(this._isBinarySupported=!1);const t=le();(N||A&&"windows"===t||G)&&(this._isBinarySupported=!1)}_isCompressedData(e){const t=new Uint8Array(e);return 67===t[0]&&79===t[1]&&77===t[2]&&80===t[3]}};const Vt={init:function(e){be.set("instance",e),xt.init()},destroy:function(){xt.dispose(),be.clear(),Ze.dispose()},notificationCenter:d,channel:xt,store:be,ssoLog:Et,utils:Ie,common:lt,constants:i};const Bt=e=>"function"==typeof e;function jt(e,t,s){const o=s||[];if(!e||!t)return!1;const n=Object.keys(e).filter((e=>!o.includes(e))),i=Object.keys(t).filter((e=>!o.includes(e)));return n.length===i.length&&n.every((o=>!!t.hasOwnProperty(o)&&("object"==typeof e[o]&&null!==e[o]?jt(e[o],t[o],s):e[o]===t[o])))}var Kt;!function(e){e.SDK_READY="sdkStateReady",e.SDK_NOT_READY="sdkStateNotReady",e.SDK_DESTROY="sdkDestroy",e.MESSAGE_RECEIVED="onMessageReceived",e.ROOM_CUSTOM_DATA_RECEIVED="onRoomCustomDataReceived",e.MESSAGE_MODIFIED="onMessageModified",e.MESSAGE_REVOKED="onMessageRevoked",e.MESSAGE_READ_BY_PEER="onMessageReadByPeer",e.MESSAGE_READ_RECEIPT_RECEIVED="onMessageReadReceiptReceived",e.MESSAGE_EXTENSIONS_UPDATED="onMessageExtensionsUpdated",e.MESSAGE_EXTENSIONS_DELETED="onMessageExtensionsDeleted",e.MESSAGE_REACTIONS_UPDATED="onMessageReactionsUpdated",e.CONVERSATION_LIST_UPDATED="onConversationListUpdated",e.TOTAL_UNREAD_MESSAGE_COUNT_UPDATED="onTotalUnreadMessageCountUpdated",e.CONVERSATION_GROUP_LIST_UPDATED="onConversationGroupListUpdated",e.CONVERSATION_IN_GROUP_UPDATED="onConversationInGroupUpdated",e.GROUP_LIST_UPDATED="onGroupListUpdated",e.GROUP_ATTRIBUTES_UPDATED="groupAttributesUpdated",e.GROUP_COUNTER_UPDATED="onGroupCounterUpdated",e.TOPIC_CREATED="onTopicCreated",e.TOPIC_DELETED="onTopicDeleted",e.TOPIC_UPDATED="onTopicUpdated",e.PROFILE_UPDATED="onProfileUpdated",e.USER_STATUS_UPDATED="onUserStatusUpdated",e.BLACKLIST_UPDATED="blacklistUpdated",e.FRIEND_LIST_UPDATED="onFriendListUpdated",e.FRIEND_GROUP_LIST_UPDATED="onFriendGroupListUpdated",e.FRIEND_APPLICATION_LIST_UPDATED="onFriendApplicationListUpdated",e.MY_FOLLOWERS_LIST_UPDATED="onMyFollowersListUpdated",e.MY_FOLLOWING_LIST_UPDATED="onMyFollowingListUpdated",e.MUTUAL_FOLLOWERS_LIST_UPDATED="onMutualFollowersListUpdated",e.KICKED_OUT="kickedOut",e.ERROR="error",e.NET_STATE_CHANGE="netStateChange",e.ALL_RECEIVE_MESSAGE_OPT_UPDATED="onAllReceiveMessageOptUpdated"}(Kt||(Kt={}));var Ht,Wt=Kt;!function(e){e.LOGOUT="logout",e.DESTROY="destroy",e.CLOUD_CONFIG_UPDATE="cloud_config_update",e.PROFILE_UPDATE="profile_updated",e.ERROR="error",e.RECONNECTED="reconnected",e.FORCE_OFFLINE="im_open_status.stat_forceoffline",e.COMMERCIAL_CONFIG_PUSH="im_sdk_config_mgr.push_imsdk_purchase_bitsv2",e.OVERLOAD_PUSH="OverLoadPush.notify2",e.NEW_MESSAGE="new_message",e.MESSAGE_PUSH="im_open_push.msg_push",e.MESSAGE_DELETED="message_deleted",e.MESSAGE_REVOKED="message_revoked",e.MESSAGE_MODIFIED="message_modified",e.SOCKET_DISCONNECTED="socket_disconnected",e.CONVERSATION_UPDATED="conversation_updated",e.TOPIC_MESSAGE_DELETED="topic_message_deleted",e.TOPIC_MESSAGE_REVOKED="topic_message_revoked",e.TOPIC_MESSAGE_MODIFIED="topic_message_modified",e.TOPIC_NEW_MESSAGE="topic_new_message",e.QUALITY_STAT="quality_stat",e.SYNC_CONVERSATION_LIST="sync_conversation_list"}(Ht||(Ht={}));var Yt,zt=Ht;!function(e){e.NEW_INVITATION_RECEIVED="newInvitationReceived",e.INVITEE_ACCEPTED="ts_invitee_accepted",e.INVITEE_REJECTED="ts_invitee_rejected",e.INVITATION_CANCELLED="ts_invitation_cancelled",e.INVITATION_TIMEOUT="ts_invitation_timeout",e.INVITATION_MODIFIED="ts_invitation_modified"}(Yt||(Yt={}));var Jt=Yt;const Qt=Object.assign({},{KICKED_OUT_MULT_ACCOUNT:"multipleAccount",KICKED_OUT_MULT_DEVICE:"multipleDevice",KICKED_OUT_USERSIG_EXPIRED:"userSigExpired",KICKED_OUT_REST_API:"REST_API_Kick"}),Xt={MSG_TEXT:"TIMTextElem",MSG_IMAGE:"TIMImageElem",MSG_AUDIO:"TIMSoundElem",MSG_FILE:"TIMFileElem",MSG_FACE:"TIMFaceElem",MSG_VIDEO:"TIMVideoFileElem",MSG_LOCATION:"TIMLocationElem",MSG_GRP_TIP:"TIMGroupTipElem",MSG_GRP_SYS_NOTICE:"TIMGroupSystemNoticeElem",MSG_CUSTOM:"TIMCustomElem",MSG_MERGER:"TIMRelayElem"};var Zt;!function(e){e.UNSENT="unSend",e.SUCCESS="success",e.FAIL="fail"}(Zt||(Zt={}));const es={modify:zt.MESSAGE_MODIFIED,delete:zt.MESSAGE_DELETED,revoke:zt.MESSAGE_REVOKED};var ts;!function(e){e[e.FORWARD=0]="FORWARD",e[e.BACKWARD=1]="BACKWARD"}(ts||(ts={}));const ss=Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},Xt),{MSG_PRIORITY_HIGH:"High",MSG_PRIORITY_NORMAL:"Normal",MSG_PRIORITY_LOW:"Low",MSG_PRIORITY_LOWEST:"Lowest"}),{RECEIVE_WITH_OFFLINE_PUSH_EXCEPT_AT:"AcceptNotNotifyExceptAt",NOT_RECEIVE_OFFLINE_PUSH_EXCEPT_AT:"AcceptNotNotifyExceptAt",NOT_RECEIVE_MSG_EXCEPT_AT:"NotReceiveMsgExceptAt",MSG_AT_ALL:"__kImSDK_MesssageAtALL__"}),{MSG_REMIND_ACPT_AND_NOTE:"AcceptAndNotify",MSG_REMIND_ACPT_NOT_NOTE:"AcceptNotNotify",MSG_REMIND_DISCARD:"Discard"}),{MessageStatus:Zt,Direction:ts}),os={[es.modify]:zt.TOPIC_MESSAGE_MODIFIED,[es.delete]:zt.TOPIC_MESSAGE_DELETED,[es.revoke]:zt.TOPIC_MESSAGE_REVOKED},ns={GENDER_UNKNOWN:"Gender_Type_Unknown",GENDER_FEMALE:"Gender_Type_Female",GENDER_MALE:"Gender_Type_Male",USER_STATUS_UNKNOWN:0,USER_STATUS_ONLINE:1,USER_STATUS_OFFLINE:2,USER_STATUS_UNLOGINED:3,USER_NOT_FOUND:"@TLS#NOT_FOUND"},is=Object.assign({},ns),rs={CONV_C2C:"C2C",CONV_GROUP:"GROUP",CONV_TOPIC:"TOPIC",CONV_SYSTEM:"@TIM#SYSTEM"},as=Object.assign(Object.assign(Object.assign(Object.assign({},rs),{CONV_AT_ME:1,CONV_AT_ALL:2,CONV_AT_ALL_AT_ME:3}),{CONV_MARK_TYPE_STAR:1,CONV_MARK_TYPE_UNREAD:2,CONV_MARK_TYPE_FOLD:4,CONV_MARK_TYPE_HIDE:8}),{READ_ALL_C2C_MSG:"readAllC2CMessage",READ_ALL_GROUP_MSG:"readAllGroupMessage",READ_ALL_MSG:"readAllMessage"}),cs=Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},{SNS_TYPE_NO_RELATION:"CheckResult_Type_NoRelation",SNS_TYPE_A_WITH_B:"CheckResult_Type_AWithB",SNS_TYPE_B_WITH_A:"CheckResult_Type_BWithA",SNS_TYPE_BOTH_WAY:"CheckResult_Type_BothWay"}),{ALLOW_TYPE_ALLOW_ANY:"AllowType_Type_AllowAny",ALLOW_TYPE_NEED_CONFIRM:"AllowType_Type_NeedConfirm",ALLOW_TYPE_DENY_ANY:"AllowType_Type_DenyAny"}),{SNS_ADD_TYPE_SINGLE:"Add_Type_Single",SNS_ADD_TYPE_BOTH:"Add_Type_Both"}),{SNS_DELETE_TYPE_SINGLE:"Delete_Type_Single",SNS_DELETE_TYPE_BOTH:"Delete_Type_Both"}),{SNS_APPLICATION_TYPE_BOTH:"Pendency_Type_Both",SNS_APPLICATION_SENT_TO_ME:"Pendency_Type_ComeIn",SNS_APPLICATION_SENT_BY_ME:"Pendency_Type_SendOut",SNS_APPLICATION_AGREE:"Response_Action_Agree",SNS_APPLICATION_AGREE_AND_ADD:"Response_Action_AgreeAndAdd"}),{SNS_CHECK_TYPE_BOTH:"CheckResult_Type_Both",SNS_CHECK_TYPE_SINGLE:"CheckResult_Type_Single"}),{FORBID_TYPE_NONE:"AdminForbid_Type_None",FORBID_TYPE_SEND_OUT:"AdminForbid_Type_SendOut"}),us={GRP_WORK:"Private",GRP_PUBLIC:"Public",GRP_MEETING:"ChatRoom",GRP_AVCHATROOM:"AVChatRoom",GRP_COMMUNITY:"Community",GRP_ROOM:"Room",GRP_LIVE:"Live"},ls={COMMUNITY:"@TGS#_",TOPIC:"@TOPIC#_"},ds={JOINED:1,QUITTED:2,KICKED:3,ADMIN_SET:4,ADMIN_CANCELED:5,GROUP_PROFILE_UPDATED:6,GROUP_MEMBER_PROFILE_UPDATED:7,TOPIC_PROFILE_UPDATED:8},ps=Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},us),{GRP_MBR_ROLE_OWNER:"Owner",GRP_MBR_ROLE_ADMIN:"Admin",GRP_MBR_ROLE_MEMBER:"Member",GRP_MBR_ROLE_CUSTOM:"Custom"}),{GRP_TIP_MBR_JOIN:1,GRP_TIP_MBR_QUIT:2,GRP_TIP_MBR_KICKED_OUT:3,GRP_TIP_MBR_SET_ADMIN:4,GRP_TIP_MBR_CANCELED_ADMIN:5,GRP_TIP_GRP_PROFILE_UPDATED:6,GRP_TIP_MBR_PROFILE_UPDATED:7,GRP_TIP_BAN_AVCHATROOM_MEMBER:10,GRP_TIP_UNBAN_AVCHATROOM_MEMBER:11}),{JOIN_OPTIONS_FREE_ACCESS:"FreeAccess",JOIN_OPTIONS_NEED_PERMISSION:"NeedPermission",JOIN_OPTIONS_DISABLE_APPLY:"DisableApply",JOIN_STATUS_SUCCESS:"JoinedSuccess",JOIN_STATUS_ALREADY_IN_GROUP:"AlreadyInGroup",JOIN_STATUS_WAIT_APPROVAL:"WaitAdminApproval"}),{INVITE_OPTIONS_DISABLE_INVITE:"DisableInvite",INVITE_OPTIONS_NEED_PERMISSION:"NeedPermission",INVITE_OPTIONS_FREE_ACCESS:"FreeAccess"}),{GRP_PROFILE_OWNER_ID:"ownerID",GRP_PROFILE_CREATE_TIME:"createTime",GRP_PROFILE_LAST_INFO_TIME:"lastInfoTime",GRP_PROFILE_MEMBER_NUM:"memberNum",GRP_PROFILE_MAX_MEMBER_NUM:"maxMemberNum",GRP_PROFILE_JOIN_OPTION:"joinOption",GRP_PROFILE_INVITE_OPTION:"inviteOption",GRP_PROFILE_INTRODUCTION:"introduction",GRP_PROFILE_NOTIFICATION:"notification",GRP_PROFILE_MUTE_ALL_MBRS:"muteAllMembers"}),{GROUP_ID_PREFIX:ls,GROUP_TIPS_OPERATION_TYPE:ds}),hs=Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},Qt),ss),is),as),cs),ps),{IOS_OFFLINE_PUSH_NO_SOUND:"push.no_sound",IOS_OFFLINE_PUSH_DEFAULT_SOUND:"default"}),{NET_STATE_CONNECTING:"connecting",NET_STATE_DISCONNECTED:"disconnected"}),gs={NO_SDKAPPID:2e3,NO_TINYID:2022,NO_A2KEY:2023,USER_NOT_LOGGED_IN:2024,REPEAT_LOGIN:2025,MSG_SEND_FAIL:2100,MSG_SEND_FAIL_NOT_IN_AV:2101,MSG_SEND_GRP_WITH_TOPIC_FAIL:2115,MSG_INSTANCE_REQUIRED:2105,MSG_INVALID_CONV_TYPE:2106,MSG_REVOKE_FAIL:2110,MSG_DELETE_FAIL:2111,MSG_UNREAD_ALL_FAIL:2112,READ_RECEIPT_MSG_LIST_EMPTY:2114,CANNOT_DELETE_GRP_SYSTEM_NOTICE:2116,NOT_MY_FRIEND:2700,NETWORK_ERROR:2800,NETWORK_TIMEOUT:2801,NO_NETWORK:2805,UNCAUGHT_ERROR:2903,INVALID_OPERATION:2905,SDK_IS_NOT_READY:2999,LOGGING_IN:3e3,LOGIN_FAILED:3001,KICKED_OUT_MULT_DEVICE:3002,KICKED_OUT_MULT_ACCOUNT:3003,KICKED_OUT_USERSIG_EXPIRED:3004,LOGGED_OUT:3005,KICKED_OUT_REST_API:3006,NO_USE:3122,OPTIONS_IS_EMPTY:3153,MSG_A2KEY_EXPIRED:20002,ACCOUNT_A2KEY_EXPIRED:70001,HELLO_ANSWER_KICKED_OUT:1002,OPEN_SERVICE_OVERLOAD_ERROR:60022},_s={BASIC:"1",STANDARD:"2",PROFESSIONAL:"3"},ms={SYNC_SERVER_INFO_AFTER_RE_ONLINE:"sync-server-info-after-re-online",SYNC_SERVER_INFO_AFTER_LOGIN:"sync-server-info-after-login",RECEIVE_C2C_NEW_MESSAGE:"receive-c2c-new-message",RECEIVE_GROUP_NEW_MESSAGE:"receive-group-new-message"},vs={USER_STATUS_UPDATE:"user-status-update",CONVERSATION_RECOVER:"conversation-recover",HISTORY_MESSAGE_RECOVER:"history-message-recover",BLACKLIST_RECOVER:"blacklist-recover",FRIEND_RECOVER:"friend-recover",GROUP_ATTRIBUTE_CACHE_CLEAR:"group-attribute-cache-clear",UNREAD_MESSAGE_RECOVER:"unread-message-recover",HANDLE_NEW_MESSAGE:"handle-new-message",HANDLE_CONVERSATION_PROFILE_UPDATED:"handle-conversation-profile-updated",COMMERCIAL_CONFIG_UPDATE:"commercial-config-update",UNREAD_MESSAGE_SYNC:"unread-message-sync",FRIEND_AND_BLACKLIST_SYNC:"friend-and-blacklist-sync",SIGNALING_MESSAGE_RECOVER:"signaling-message-recover",GROUP_LIST_SYNC:"group-list-sync",CONVERSATION_LIST_SYNC:"conversation-list-sync",USER_PROFILE_SYNC:"user-profile-sync",CONVERSATION_UPDATE_AFTER_UNREAD_SYNC_FINISHED:"conversation-update-after-unread-sync-finished",CONVERSATION_UPDATE_AFTER_GROUP_LIST_SYNC_FINISHED:"conversation-update-after-group-list-sync-finished",HANDLE_C2C_NEW_MESSAGE:"handle-c2c-new-message",HANDLE_GROUP_NEW_MESSAGE:"handle-group-new-message",CREATE_OR_UPDATE_CONVERSATION_BY_RECEIVE_NEW_MESSAGE:"create-or-update-conversation-by-receive-new-message",HANDLE_GROUP_TIPS_FROM_SYNC_UNREAD:"handle-group-tips-from-sync-unread",HANDLE_C2C_REVOKED_MESSAGE_FROM_SYNC_UNREAD:"handle-c2c-revoked-message-from-sync-unread",GROUP_REVOKED_NOTICE_RECOVER:"group-revoked-notice-recover",CLOUD_CONFIG_SYNC:"cloud-config-sync",UPDATE_GROUP_NEXT_SEQUENCE:"update-group-next-sequence",EMIT_C2C_MESSAGE_EVENT:"emit-c2c-message-event",EMIT_GROUP_MESSAGE_EVENT:"emit-group-message-event",CONVERSATION_GROUP_LIST_SYNC:"conversation-group-list-sync",CONVERSATION_GROUP_UPDATE:"conversation-group-update",UPDATE_TOPIC_AFTER_UNREAD_SYNC_FINISHED:"update-topic-after-unread-sync-finished",UPDATE_TOPIC_BY_RECEIVE_NEW_MESSAGE:"update-topic-by-received-new-message",TOPIC_REQUEST_INFO_RESET:"topic-request-info-reset",QUALITY_REPORT:"quality-report",GROUP_TIPS_RECOVER:"group-tips-recover"},fs={[ms.SYNC_SERVER_INFO_AFTER_RE_ONLINE]:[{stepId:vs.USER_STATUS_UPDATE},{stepId:vs.GROUP_ATTRIBUTE_CACHE_CLEAR},{stepId:vs.UNREAD_MESSAGE_SYNC},{stepId:vs.CONVERSATION_RECOVER},{stepId:vs.HISTORY_MESSAGE_RECOVER,dependency:vs.CONVERSATION_RECOVER},{stepId:vs.BLACKLIST_RECOVER},{stepId:vs.FRIEND_RECOVER},{stepId:vs.GROUP_REVOKED_NOTICE_RECOVER,dependency:vs.HISTORY_MESSAGE_RECOVER},{stepId:vs.GROUP_TIPS_RECOVER,dependency:vs.HISTORY_MESSAGE_RECOVER},{stepId:vs.TOPIC_REQUEST_INFO_RESET},{stepId:vs.HANDLE_C2C_REVOKED_MESSAGE_FROM_SYNC_UNREAD,dependency:vs.UNREAD_MESSAGE_SYNC},{stepId:vs.HANDLE_GROUP_TIPS_FROM_SYNC_UNREAD,dependency:vs.UNREAD_MESSAGE_SYNC},{stepId:vs.CONVERSATION_UPDATE_AFTER_UNREAD_SYNC_FINISHED,dependency:[vs.UNREAD_MESSAGE_SYNC,vs.CONVERSATION_RECOVER]},{stepId:vs.EMIT_C2C_MESSAGE_EVENT,dependency:[vs.UNREAD_MESSAGE_SYNC,vs.CONVERSATION_UPDATE_AFTER_UNREAD_SYNC_FINISHED],skipIfDependencyMissing:!1}],[ms.SYNC_SERVER_INFO_AFTER_LOGIN]:[{stepId:vs.COMMERCIAL_CONFIG_UPDATE},{stepId:vs.CLOUD_CONFIG_SYNC},{stepId:vs.USER_PROFILE_SYNC},{stepId:vs.UNREAD_MESSAGE_SYNC},{stepId:vs.FRIEND_AND_BLACKLIST_SYNC},{stepId:vs.GROUP_LIST_SYNC},{stepId:vs.CONVERSATION_LIST_SYNC},{stepId:vs.SIGNALING_MESSAGE_RECOVER,dependency:vs.UNREAD_MESSAGE_SYNC},{stepId:vs.UPDATE_TOPIC_AFTER_UNREAD_SYNC_FINISHED,dependency:[vs.UNREAD_MESSAGE_SYNC]},{stepId:vs.CONVERSATION_UPDATE_AFTER_UNREAD_SYNC_FINISHED,dependency:[vs.UNREAD_MESSAGE_SYNC,vs.CONVERSATION_LIST_SYNC]},{stepId:vs.CONVERSATION_UPDATE_AFTER_GROUP_LIST_SYNC_FINISHED,dependency:[vs.GROUP_LIST_SYNC,vs.CONVERSATION_LIST_SYNC]},{stepId:vs.CONVERSATION_GROUP_LIST_SYNC},{stepId:vs.CONVERSATION_GROUP_UPDATE,dependency:[vs.CONVERSATION_LIST_SYNC,vs.CONVERSATION_GROUP_LIST_SYNC]},{stepId:vs.QUALITY_REPORT}],[ms.RECEIVE_C2C_NEW_MESSAGE]:[{stepId:vs.HANDLE_C2C_NEW_MESSAGE},{stepId:vs.UNREAD_MESSAGE_SYNC},{stepId:vs.CREATE_OR_UPDATE_CONVERSATION_BY_RECEIVE_NEW_MESSAGE,dependency:vs.HANDLE_C2C_NEW_MESSAGE},{stepId:vs.EMIT_C2C_MESSAGE_EVENT,dependency:[vs.HANDLE_C2C_NEW_MESSAGE,vs.CREATE_OR_UPDATE_CONVERSATION_BY_RECEIVE_NEW_MESSAGE],skipIfDependencyMissing:!1},{stepId:vs.CONVERSATION_UPDATE_AFTER_UNREAD_SYNC_FINISHED,dependency:[vs.UNREAD_MESSAGE_SYNC]}],[ms.RECEIVE_GROUP_NEW_MESSAGE]:[{stepId:vs.HANDLE_GROUP_NEW_MESSAGE},{stepId:vs.CREATE_OR_UPDATE_CONVERSATION_BY_RECEIVE_NEW_MESSAGE,dependency:vs.HANDLE_GROUP_NEW_MESSAGE},{stepId:vs.UPDATE_GROUP_NEXT_SEQUENCE,dependency:vs.HANDLE_GROUP_NEW_MESSAGE},{stepId:vs.UPDATE_TOPIC_BY_RECEIVE_NEW_MESSAGE,dependency:vs.HANDLE_GROUP_NEW_MESSAGE},{stepId:vs.EMIT_GROUP_MESSAGE_EVENT,dependency:[vs.HANDLE_GROUP_NEW_MESSAGE,vs.CREATE_OR_UPDATE_CONVERSATION_BY_RECEIVE_NEW_MESSAGE],skipIfDependencyMissing:!1}]},Is={MESSAGE_SEND_SUCCESS_RATE:"messageSendSuccessRate"},Ss={TOTAL_COUNT:"sendMessageTotalCount",SUCCESS_COUNT:"sendMessageSuccessCount",FAILED_COUNT:"sendMessageFailedCount",SEND_COST:"sendMessageCost"};var Es=Object.freeze({__proto__:null,ERROR_CODE:gs,InnerEvent:zt,OuterConstant:hs,OuterEvent:Wt,QUALITY_METRICS:Is,SDK_EDITION:_s,SDK_INFO:{VERSION:"1.7.3",APPID:537048168},SEND_MESSAGE_STAT:Ss,SignalingEvent:Jt,WORKFLOW_DEFINITIONS:fs,WORKFLOW_NAME:ms,WORKFLOW_STEP:vs});var Cs,Ms,ys;!function(e){e[e.USER_INITIATED=0]="USER_INITIATED",e[e.KICKED_OUT=1]="KICKED_OUT"}(Cs||(Cs={})),function(e){e[e.multipleAccount=1]="multipleAccount",e[e.multipleDevice=2]="multipleDevice",e[e.restApi=3]="restApi"}(Ms||(Ms={})),function(e){e[e.multipleDevice=3002]="multipleDevice",e[e.multipleAccount=3003]="multipleAccount",e[e.usersigExpired=70001]="usersigExpired",e[e.restApi=20002]="restApi"}(ys||(ys={}));const Ts={[Ms.multipleAccount]:"multipleAccount",[Ms.multipleDevice]:"multipleDevice",[Ms.restApi]:"REST_API_Kick",[ys.multipleAccount]:"multipleAccount",[ys.multipleDevice]:"multipleDevice",[ys.restApi]:"REST_API_Kick",[ys.usersigExpired]:"userSigExpired"},As="login_online_presence_task",{ERROR:Os,DESTROY:Ds,FORCE_OFFLINE:Rs}=zt,{KICKED_OUT_MULT_ACCOUNT:Ls,KICKED_OUT_MULT_DEVICE:Ns,KICKED_OUT_REST_API:bs,ACCOUNT_A2KEY_EXPIRED:Gs,MSG_A2KEY_EXPIRED:ws}=gs;class Ps{init(){const{notificationCenter:e}=Vt;e.subscribeInnerEvent(Rs,this._handleForceOfflineFromServerPush,this),e.subscribeInnerEvent(Os,ws,this._handleForceOfflineFromResponse,this),e.subscribeInnerEvent(Os,Gs,this._handleForceOfflineFromResponse,this),e.subscribeInnerEvent(Os,Ls,this._handleForceOfflineFromResponse,this),e.subscribeInnerEvent(Os,Ns,this._handleForceOfflineFromResponse,this),e.subscribeInnerEvent(Os,bs,this._handleForceOfflineFromResponse,this),e.subscribeInnerEvent(Ds,this._dispose,this)}_handleForceOfflineFromServerPush(e){const{EventArray:t=[]}=(null==e?void 0:e.body)||{};this._extractKickedOutMessages(t).forEach((e=>{const{KickoutMsgNotify:{KickType:t,NewInstInfo:s}}=e;this._processKickedOutReasonInfo({kickedOutReasonCode:t,newInstanceInfo:s})}))}_extractKickedOutMessages(e){return e.reduce(((e,t)=>[...e,...t.C2cNotifyMsgArray||[]]),[]).filter((e=>{var t;return this._isKickedOut(null===(t=null==e?void 0:e.KickoutMsgNotify)||void 0===t?void 0:t.KickType)}))}_handleForceOfflineFromResponse(e){const{errorCode:t}=e;this._processKickedOutReasonInfo({kickedOutReasonCode:t})}_processKickedOutReasonInfo(e){return h(this,void 0,void 0,(function*(){const{kickedOutReasonCode:t}=e;try{this._logKickedOutEvent(e),yield Vt.login.loginAction.logout(Cs.KICKED_OUT)}catch(e){console.debug(e)}finally{Vt.notificationCenter.emitOuterEvent(Wt.KICKED_OUT,{data:{type:Ts[t]},name:Wt.KICKED_OUT}),[Ms.restApi,Gs,ws].includes(t)&&Vt.channel.reconnect()}}))}_logKickedOutEvent(e){const{kickedOutReasonCode:t,newInstanceInfo:s={}}=e,o=Vt.ssoLog.createSSOLogData({method:"kickedOut"}),n=`type:${Ts[t]} newInstanceInfo: ${JSON.stringify(s)}`;o.setLogInfo({message:n}).end(!0),console.warn(`loginModule.${n}`)}_isKickedOut(e){return[Ms.multipleAccount,Ms.multipleDevice,Ms.restApi].includes(e)}_dispose(){const{notificationCenter:e}=Vt;e.unSubscribeInnerEvent(Rs,this._handleForceOfflineFromServerPush,this),e.unSubscribeInnerEvent(Os,Gs,this._handleForceOfflineFromResponse,this),e.unSubscribeInnerEvent(Os,ws,this._handleForceOfflineFromResponse,this),e.unSubscribeInnerEvent(Os,Ls,this._handleForceOfflineFromResponse,this),e.unSubscribeInnerEvent(Os,Ns,this._handleForceOfflineFromResponse,this),e.unSubscribeInnerEvent(Os,bs,this._handleForceOfflineFromResponse,this),e.unSubscribeInnerEvent(Ds,this._dispose,this)}}function Us(){return h(this,void 0,void 0,(function*(){const e="im_open_status.wslogin",t=Vt.common.generateProtocolData({servcmd:e,data:{state:"Online",isWebUniapp:0,InstType:0,customInfo:""}}),s=`${t.head.seq}${e}`;try{const e=yield Vt.channel.sendPacket(t,{timeout:9e4,requestId:s});if(e){const{HelloInterval:t,InstId:s,TinyId:o,TimeStamp:n,CustomStatus:i,PurchaseBits:r,A2Key:a,RichMsgAuthKey:c,ErrorCode:u,ErrorInfo:l,ActionStatus:d}=e;return{helloInterval:t,instanceID:s,tinyID:o,timeStamp:n,customStatus:i,purchaseBits:r,a2Key:a,authKey:c,errorCode:u,errorInfo:l,actionStatus:d}}}catch(e){throw console.warn(e),e}}))}function ks(e){var t;try{const s=be.getStorage("errorMessage");if(!e||!s)return"";const o=(null===(t=JSON.parse(s))||void 0===t?void 0:t.errorMessage)||{},{isIntl:n=!1,code:i,replacement1:r="",replacement2:a=""}=e;if(!i)return"";const c=n?`${i}_en`:`${i}_cn`;let u=o[o[c]?c:i]||"";return u&&(r&&(u=u.replace("$replacement1",r)),a&&(u=u.replace("$replacement2",a))),u}catch(e){return console.warn("Error parsing stored error messages:",e),""}}class Fs extends Error{constructor(e){const{functionName:t="Unknown",code:s,message:o="",data:n=""}=e;let i=o;s&&!o&&(i=ks(e));const r=s?`${t} failed. error: {"message": ${i}, "code": ${s}}`:`${t} failed. error: {"message": ${i}}`;super(),this.code=s,this.errorCode=s,this.errorMessage=r,this.message=r,this.data=n}}function $s(e,t){var s;if(!e)return;if(!(!0===(null===(s=Vt.store.get("login"))||void 0===s?void 0:s.isLoggedIn)))throw new Fs({code:gs.USER_NOT_LOGGED_IN,functionName:t})}function qs(e,t,s){if(Array.isArray(e))for(let o=0;o<e.length;o++)xs.call(this,Object.assign(Object.assign({},e[o]),{value:t[o],name:s}));else for(const o in e)xs.call(this,Object.assign(Object.assign({},e[o]),{value:t[0][o],name:s,key:o}))}function xs({required:e,rules:t,range:s,value:o,allowEmpty:n,name:i,key:r,customValidator:a}){if(void 0===o){if(e){throw new Fs({functionName:i,message:`[${i}] Missing required params: "${r}"`})}return}let c="";if(!t.some((e=>{return e===(t=o,Object.prototype.toString.call(t).match(/^\[object (.*)\]$/)[1].toLowerCase());var t}))){for(let e=0;e<t.length;e++){let s=t[e];s=s.replace(s[0],s[0].toUpperCase()),c+=`${s}/`}c=c.substring(0,c.length-1);const e=`[${r}] must be type of ${c}, received type: ${function(e){return Reflect.apply(Object.prototype.toString,e,[]).replace(/^\[object\s(\w+)\]$/,"$1").toLowerCase()}(o)}.`;throw new Fs({functionName:i,message:e})}if(!1===n){if(Array.isArray(o)&&(0===o.length||"string"==typeof o[0]&&""===o[0].trim())){throw new Fs({functionName:i,message:`${r} can not be empty.`})}if("string"==typeof o&&""===o.trim()){throw new Fs({functionName:i,message:`${r} can not be empty.`})}}if(a&&"function"==typeof a){const e=a(o);if(!0!==e){throw new Fs({functionName:i,message:`[${r}] custom validation failed: ${e||"Invalid value"}`})}}}const Vs=[],Bs={},js={};function Ks(e,t){$s(Bs[e],e),qs(js[e],t,e),function(e){Vs.forEach((t=>{const{interceptor:s,context:o}=t;s.apply(o,[e])}))}(e)}function Hs(e,t){Vs.push({interceptor:e,context:t})}function Ws(e){const{params:t,auth:s}=e;t&&"object"==typeof t&&Object.assign(js,t),s&&"object"==typeof s&&Object.assign(Bs,s)}function Ys(e){return Vt.store.get("commercialConfig").get(e)}class zs{constructor(){this._handlers=new Map,this._activeWorkflows=new Map,this._stepStartTimes=new Map,this._logHandlers={start:(e,t)=>{const s=Date.now();t?(this._stepStartTimes.set(`${e}-${t}`,s),console.log(`[Workflow ${e}] Step ${t} started at ${new Date(s).toISOString()}`)):(this._workflowStartTimes.set(e,s),console.log(`[Workflow ${e}] started at ${new Date(s).toISOString()}`))},success:(e,t)=>{const s=Date.now();if(t){const o=this._stepStartTimes.get(`${e}-${t}`),n=o?s-o:0;this._stepStartTimes.delete(`${e}-${t}`),console.log(`[Workflow ${e}] Step ${t} completed successfully at ${new Date(s).toISOString()} (${n}ms)`)}else{const t=this._workflowStartTimes.get(e),o=t?s-t:0;this._workflowStartTimes.delete(e),console.log(`[Workflow ${e}] completed successfully at ${new Date(s).toISOString()} (${o}ms)`)}},error:(e,t,s)=>{const o=Date.now();if(t){const n=this._stepStartTimes.get(`${e}-${t}`),i=n?o-n:0;this._stepStartTimes.delete(`${e}-${t}`),console.error(`[Workflow ${e}] Step ${t} failed at ${new Date(o).toISOString()} (${i}ms)`,s)}else{const t=this._workflowStartTimes.get(e),n=t?o-t:0;this._workflowStartTimes.delete(e),console.error(`[Workflow ${e}] failed at ${new Date(o).toISOString()} (${n}ms)`,s)}}}}static getInstance(){return zs._instance||(zs._instance=new zs),zs._instance}static setInstance(e){zs._instance=e}init(){this._initializeWorkflows()}registerWorkflowStep(e,t,s,o){if(!this._handlers.has(e))return void console.debug(`Workflow '${e}' not defined in core`);if(!fs[e].find((e=>e.stepId===t)))return void console.debug(`Step '${t}' not defined in workflow '${e}'`);const n=this._handlers.get(e);n.has(t)||n.set(t,o?s.bind(o):s)}executeWorkflow(e,t){return h(this,void 0,void 0,(function*(){if(!this._validateWorkflow(e))return;console.log(`[Workflow ${e}] Started execution at ${(new Date).toISOString()}`);const s=fs[e],o={},n={cancelled:!1};this._activeWorkflows.set(e,{cancelToken:n});try{const i=new Map;s.forEach((e=>{i.set(e.stepId,e)}));const r={workflowName:e,pendingSteps:new Set(s.map((e=>e.stepId))),completedSteps:new Set,runningSteps:new Set,stepMap:i,stepResults:o,data:t,cancelToken:n};yield new Promise(((t,s)=>{const o=()=>{if(n.cancelled)return void t();this._getExecutableSteps({pendingSteps:r.pendingSteps,completedSteps:r.completedSteps,stepMap:r.stepMap,workflowName:e}).filter((e=>!r.runningSteps.has(e))).forEach((n=>{r.completedSteps.has(n)||r.runningSteps.has(n)||this._executeWorkflowStep(n,r,{onComplete:()=>{if(0===r.pendingSteps.size)return void t();0===this._getExecutableSteps({pendingSteps:r.pendingSteps,completedSteps:r.completedSteps,stepMap:r.stepMap,workflowName:e}).filter((e=>!r.runningSteps.has(e))).length&&0===r.runningSteps.size&&(console.log(`Workflow ${e} completed with some steps skipped due to dependency failures`),t())},onError:s,onStepComplete:o})}))};o()})),console.log(`[Workflow ${e}] Completed execution at ${(new Date).toISOString()}`)}catch(t){console.error(`[Workflow ${e}] Failed execution at ${(new Date).toISOString()}`,t)}finally{this._activeWorkflows.delete(e)}}))}_executeWorkflowStep(e,t,s){return h(this,void 0,void 0,(function*(){const{workflowName:o,runningSteps:n,stepMap:i,stepResults:r,data:a}=t;n.add(e),this._logWorkflowExecution(o,e,"start");try{const s=i.get(e);let n=null;(null==s?void 0:s.dependency)&&(_(s.dependency)?n=r[s.dependency]:Array.isArray(s.dependency)&&(n={},s.dependency.forEach((e=>{n[e]=r[e]}))));const c=this._handlers.get(o).get(e);if(c){const t=yield Promise.resolve(c({data:a,result:n}));r[e]=t,this._logWorkflowExecution(o,e,"success")}t.completedSteps.add(e)}catch(t){const n=`[Workflow].${o}.${e}`,{errorCode:i,errorInfo:r=`${n} failed`}=t||{},a=new Fs({functionName:n,code:i,message:r});Vt.ssoLog.createSSOLogData({method:"Workflow"}).setLogInfo({message:`workflowName: ${o}, stepId: ${e}`}).setError(a).end(),this._logWorkflowExecution(o,e,"error",t),s.onError(t)}finally{n.delete(e),t.pendingSteps.delete(e),s.onStepComplete(),s.onComplete()}}))}reset(){this._cancelAllWorkflows()}destroy(){this.reset(),this._handlers.clear()}_initializeWorkflows(){Object.keys(fs).forEach((e=>{this._handlers.has(e)||this._handlers.set(e,new Map)}))}_cancelWorkFlow(e){const t=this._activeWorkflows.get(e);if(!t)return;const{cancelToken:s}=t;s.cancelled=!0,this._activeWorkflows.delete(e)}_cancelAllWorkflows(){Object.keys(fs).forEach((e=>{this._cancelWorkFlow(e)}))}_validateWorkflow(e){if(!fs[e])return console.debug(`Workflow '${e}' not defined`),!1;return!!this._handlers.get(e)||(console.debug(`No handlers registered for workflow '${e}'`),!1)}_getExecutableSteps(e){const{pendingSteps:t,completedSteps:s,stepMap:o,workflowName:n}=e;return Array.from(t).filter((e=>{const t=o.get(e)||{},{dependency:i,skipIfDependencyMissing:r=!0}=t;if(!i)return!0;if(_(i))return this._isStepRegistered({workflowName:n,stepId:i})?s.has(i):!r;if(v(i)){if(i.filter((e=>!this._isStepRegistered({workflowName:n,stepId:e}))).length>0&&r)return!1;for(const e of i)if(!s.has(e))return!1;return!0}return!1}))}_isStepRegistered(e){var t;const{workflowName:s,stepId:o}=e;return null===(t=this._handlers.get(s))||void 0===t?void 0:t.has(o)}_logWorkflowExecution(e,t,s,o){this._logHandlers[s](e,t)}}const Js=new Map,Qs=({type:e,groupID:t})=>e===hs.GRP_COMMUNITY||`${t}`.startsWith(ls.COMMUNITY)&&!`${t}`.includes(ls.TOPIC),Xs=(e="")=>{const t=e.startsWith("GROUP")?e.replace("GROUP",""):e;return t.startsWith(ls.COMMUNITY)&&`${t}`.includes(ls.TOPIC)},Zs="openim",eo="million_group_open_http_svc";function to(e){return h(this,void 0,void 0,(function*(){const{servcmd:t,data:s}=function(e){const{data:t}=e;return so(t)||oo(t)}(e)?function(e){let{servcmd:t,data:s}=e;if(oo(s))return function(e){const{servcmd:t,data:s}=e;let{GroupId:o=""}=s;const n=o;return[o]=n.split(ls.TOPIC),{servcmd:no(t),data:Object.assign(Object.assign({},s),{GroupId:o,TopicId:n})}}(e);so(s)&&(t=no(t));return{servcmd:t,data:s}}(e):e,o=Vt.common.generateProtocolData({servcmd:t,data:s}),n=`${o.head.seq}${t}`;return Vt.channel.sendPacket(o,{requestId:n})}))}function so(e){const{Type:t,GroupId:s,GroupIdList:o=[]}=e,n=s||o[0]||"";return Qs({type:t,groupID:n})}function oo(e){const{GroupId:t=""}=e;return Xs(t)}function no(e){if(e.includes(Zs))return e;const t=e.split(".")[1];return`${eo}.${t}`}function io(){var e;return null===(e=Vt.store.get("login"))||void 0===e?void 0:e.userId}const ro=e=>v(e)||f(e),ao=(e,t,s,o)=>{if(!ro(e)||!ro(t))return 0;let n=0;const i=Object.keys(t);let r;for(let a=0,c=i.length;a<c;a++)if(r=i[a],!(g(t[r])||s&&s.includes(r)))if(ro(e[r])&&ro(t[r]))n+=ao(e[r],t[r],s,o);else{if(o&&o.includes(t[r]))continue;e[r]!==t[r]&&(e[r]=t[r],n+=1)}return n},co=(e,t)=>{if(g(t))return"";switch(e){case hs.MSG_TEXT:return t.text||"";case hs.MSG_IMAGE:return"[Image]";case hs.MSG_LOCATION:return"[Location]";case hs.MSG_AUDIO:return"[Voice]";case hs.MSG_VIDEO:return"[Video]";case hs.MSG_FILE:return"[File]";case hs.MSG_CUSTOM:return"[Custom Messages]";case hs.MSG_GRP_TIP:return"[Group Notification]";case hs.MSG_GRP_SYS_NOTICE:return"[Group System Message]";case hs.MSG_FACE:return"[Animated Sticker]";case hs.MSG_MERGER:return"[Chat Record]";default:return""}},uo=[{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}],lo="im_sdk_config_mgr.fetch_config",po="im_sdk_config_mgr.push_configv2",ho="cloud-config",go=2996;var _o=new class{constructor(){this._core=null,this._expirationTime=0,this._version=0,this._isFetching=!1,this._cmdFrequencyLimitMap=new Map,this._methodCallFrequencyMap=new Map}install(e){this._core=e;const{notificationCenter:t,InnerEvent:s,helper:o,constants:{WORKFLOW_NAME:n,WORKFLOW_STEP:i},channel:r}=e;t.subscribeInnerEvent(po,this._handlePushedConfig,this),o.registerWorkflowStep(n.SYNC_SERVER_INFO_AFTER_LOGIN,i.CLOUD_CONFIG_SYNC,this._handleLoginSuccess,this),t.subscribeInnerEvent(s.LOGOUT,this._reset,this),t.subscribeInnerEvent(s.DESTROY,this._dispose,this),o.registerExperimentalAPI("getServerConfig",this),this._updateCmdFreqLimitMap(uo),r.registerBeforeSendInterceptor(this.checkMethodCallOverLimit,this)}getServerConfig(e){var t;const s={code:0,data:""};return e?(s.data=(null===(t=this._core.store.get("cloudConfig"))||void 0===t?void 0:t[e])||"",s):s}checkMethodCallOverLimit(e){if(!this._cmdFrequencyLimitMap.has(e))return;if(!this._methodCallFrequencyMap.has(e))return void this._methodCallFrequencyMap.set(e,{startTime:Date.now(),methodCallCounter:1});const{count:t,interval:s}=this._cmdFrequencyLimitMap.get(e);let{startTime:o,methodCallCounter:n}=this._methodCallFrequencyMap.get(e);if(Date.now()-o>1e3*s)this._methodCallFrequencyMap.set(e,{startTime:Date.now(),methodCallCounter:1});else if(n+=1,this._methodCallFrequencyMap.set(e,{startTime:o,methodCallCounter:n}),n>t)throw new this._core.helper.ChatError({code:go,replacement1:e})}_fetchCloudConfig(){return h(this,void 0,void 0,(function*(){try{const{sdkAppId:e}=this._core.store.get("instance")||{},t=this._core.helper.generateProtocolData({servcmd:lo,data:{uint32_sdkappid:e,uint64_version:this._version}}),s=`${t.head.seq}${lo}`;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{if(this._canFetch()){const e=yield this._fetchCloudConfig();this._updateCloudConfig(e)}this._core.helper.taskScheduler.addTask({id:ho,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{const e=yield this._fetchCloudConfig();this._updateCloudConfig(e)}catch(e){console.warn(e)}}))}_updateCloudConfig(e){const t=this._parseCloudConfig(e);t&&(this._core.store.set("cloudConfig",t),this._parseCmdFreqLimit(),this._core.notificationCenter.emitInnerEvent(this._core.InnerEvent.CLOUD_CONFIG_UPDATE,t))}_canFetch(){const{isLoggedIn:e}=this._core.store.get("login")||{};return e&&!this._isFetching&&Date.now()>=this._expirationTime}_parseCloudConfig(e){const{int32_error_code:t,str_error_message:s,str_json_config:o,uint32_expired_time:n,uint32_sdkappid:i,uint64_version:r}=e;let a=null;if(0===t){if(this._version!==r)try{a=JSON.parse(o),this._version=r}catch(e){}this._expirationTime=Date.now()+1e3*n}else this._expirationTime=void 0===t?Date.now()+36e5:Date.now()+12e4;return a}_parseCmdFreqLimit(){var e;let t=null===(e=this.getServerConfig("cmd_frequency_limit"))||void 0===e?void 0:e.data;const{isEmpty:s}=this._core.utils;if(!s(t))try{t=JSON.parse(t),this._updateCmdFreqLimitMap(t)}catch(e){console.warn(e)}}_updateCmdFreqLimitMap(e){e.forEach((e=>{this._cmdFrequencyLimitMap.set(e.cmd,{interval:e.interval,count:e.count})}))}_reset(){this._core.helper.taskScheduler.removeTask(ho),this._core.store.clear("cloudConfig"),this._updateCmdFreqLimitMap(uo),this._methodCallFrequencyMap.clear(),this._expirationTime=0,this._version=0,this._isFetching=!1}_dispose(){const{notificationCenter:e,InnerEvent:t}=this._core;e.unSubscribeInnerEvent(po,this._handlePushedConfig,this),e.unSubscribeInnerEvent(t.LOGOUT,this._reset,this),e.unSubscribeInnerEvent(t.DESTROY,this._dispose,this),this._reset()}};class mo{constructor(e=0,t=0){this.high=e,this.low=t}equal(e){return null!==e&&(this.low===e.low&&this.high===e.high)}toString(){const e=Number(this.high).toString(16);let t=Number(this.low).toString(16);if(t.length<8){let e=8-t.length;for(;e;)t=`0${t}`,e--}return e+t}}const vo={SEARCH_GRP_SNS:new mo(0,Math.pow(2,1)).toString(),AV_HISTORY_MSG:new mo(0,Math.pow(2,2)).toString(),GRP_COMMUNITY:new mo(0,Math.pow(2,3)).toString(),MSG_TO_SPECIFIED_GRP_MBR:new mo(0,Math.pow(2,4)).toString(),AV_MBR_LIST:new mo(0,Math.pow(2,6)).toString(),USER_STATUS:new mo(0,Math.pow(2,7)).toString(),CONV_MARK:new mo(0,Math.pow(2,9)).toString(),CONV_GROUP:new mo(0,Math.pow(2,10)).toString(),AV_BAN_MBR:new mo(0,Math.pow(2,11)).toString(),MSG_EXT:new mo(0,Math.pow(2,13)).toString(),GRP_COUNTER:new mo(0,Math.pow(2,15)).toString(),PLUGIN_TRANSLATE:new mo(Math.pow(2,6)).toString(),PLUGIN_VOICE_TO_TEXT:new mo(Math.pow(2,7)).toString(),PLUGIN_CS:new mo(Math.pow(2,8)).toString(),PLUGIN_PUSH:new mo(Math.pow(2,9)).toString(),PLUGIN_BOT:new mo(Math.pow(2,10)).toString(),MSG_REACTION:new mo(Math.pow(2,16)).toString(),FOLLOW:new mo(Math.pow(2,20)).toString()},fo="CommercialConfig",Io="commercial-config";var So=new class{constructor(){this._core=null,this._expirationTime=0,this._isFetching=!1,this._featureMap=new Map,this._methodKeyMap=new Map,this._purchaseBits="0"}install(e){this._core=e;const{helper:t,notificationCenter:s,constants:{WORKFLOW_NAME:o,WORKFLOW_STEP:n,InnerEvent:i}}=e;s.subscribeInnerEvent(i.COMMERCIAL_CONFIG_PUSH,this._handlePushedConfig,this),s.subscribeInnerEvent(i.LOGOUT,this._handleLogout,this),s.subscribeInnerEvent(i.DESTROY,this._dispose,this),t.registerWorkflowStep(o.SYNC_SERVER_INFO_AFTER_LOGIN,n.COMMERCIAL_CONFIG_UPDATE,this._syncCommercialConfig,this),e.helper.registerExperimentalAPI("isCommercialAbilityEnabled",this),e.helper.registerExperimentalAPI("queryCommercialAbility",this)}isCommercialAbilityEnabled(e){return h(this,void 0,void 0,(function*(){const t=parseInt(e,10).toString(2),{length:s}=t;let o,n=!0;for(let e=s-1,i=0;e>=0;e--,i++)if("1"===t.charAt(e)&&(o=i<32?new mo(0,2**i).toString():new mo(2**(i-32),0).toString(),!this._featureMap.get(o))){n=!1;break}return console.log(`${fo}.isFeatureEnabled decimalNumber:${e} key:${o} ret:${n}`),{code:0,data:{enabled:n}}}))}queryCommercialAbility(){return this._purchaseBits}_fetchAndParseCommercialConfig(){return h(this,void 0,void 0,(function*(){var e;try{this._isFetching=!0;const t=this._core.helper.generateProtocolData({servcmd:"im_sdk_config_mgr.fetch_imsdk_purchase_bitsv2",data:{uint32_sdkappid:null===(e=this._core.store.get("instance"))||void 0===e?void 0:e.sdkAppId}}),s=yield this._core.channel.sendPacket(t);(null==s?void 0:s.body)&&(this._parseCommercialConfig(s.body),this._core.store.set("commercialConfig",this._methodKeyMap))}catch(e){console.warn("fetch commercial fail: ",e)}finally{this._isFetching=!1}}))}_syncCommercialConfig(e){return h(this,void 0,void 0,(function*(){const{purchaseBits:t}=(null==e?void 0:e.data)||{};t&&(this._parsePurchaseBits(t),this._core.store.set("commercialConfig",this._methodKeyMap)),this._canFetch()&&(yield this._fetchAndParseCommercialConfig()),this._core.helper.taskScheduler.addTask({id:Io,intervalMs:1e3,callback:this._fetchCommercialConfigIfReady,context:this})}))}_canFetch(){var e;const t=null===(e=this._core.store.get("login"))||void 0===e?void 0:e.isLoggedIn,s=Date.now()>=this._expirationTime;return t&&!this._isFetching&&s}_handlePushedConfig(e){(null==e?void 0:e.body)&&(this._parseCommercialConfig(e.body),this._core.store.set("commercialConfig",this._methodKeyMap))}_fetchCommercialConfigIfReady(){return h(this,void 0,void 0,(function*(){this._canFetch()&&(yield this._fetchAndParseCommercialConfig())}))}_parseCommercialConfig(e){if("object"!=typeof e)return;const{int32_error_code:t,str_error_message:s,str_purchase_bits:o,uint32_expired_time:n}=e;0===t?(this._parsePurchaseBits(o),this._expirationTime=Date.now()+1e3*n):void 0===t?(console.log(`${fo}._parseCommercialConfig failed. Invalid message format:`,e),this._expirationTime=Date.now()+36e5):(console.error(`${fo}._parseCommercialConfig errorCode:${t} errorMessage:${s}`),this._expirationTime=Date.now()+12e4)}_isValidPurchaseBits(e){return e&&"string"==typeof e&&e.length>=1&&e.length<=64&&/[01]{1,64}/.test(e)}_parsePurchaseBits(e){if(this._isValidPurchaseBits(e)){this._purchaseBits=e,this._featureMap.clear(),this._methodKeyMap.clear();let t=null;for(let s=e.length-1,o=0;s>=0;s--,o++)if(t=o<32?new mo(0,2**o).toString():new mo(2**(o-32),0).toString(),"1"===e[s]){this._featureMap.set(t,!0);const e=this._getKeyByValue(vo,t);e&&this._methodKeyMap.set(e,!0)}else{this._featureMap.set(t,!1);const e=this._getKeyByValue(vo,t);e&&this._methodKeyMap.set(e,!1)}}else console.warn(`${fo}.parsePurchaseBits invalid purchases:${e}`)}_getKeyByValue(e,t){const s=Object.entries(e).find((([e,s])=>s===t));return s?s[0]:void 0}_handleLogout(){this._reset()}_dispose(){this._reset(),this._core.notificationCenter.unSubscribeInnerEvent(this._core.InnerEvent.COMMERCIAL_CONFIG_PUSH,this._handlePushedConfig,this),this._core.notificationCenter.unSubscribeInnerEvent(this._core.InnerEvent.LOGOUT,this._reset,this),this._core.notificationCenter.unSubscribeInnerEvent(this._core.InnerEvent.DESTROY,this._dispose,this)}_reset(){this._core.helper.taskScheduler.removeTask(Io),this._core.store.set("commercialConfig",{}),this._expirationTime=0,this._isFetching=!1,this._featureMap.clear(),this._purchaseBits="0"}};var Eo=new class{constructor(){this._core=null,this._serverOverloadInfoMap=new Map}install(e){this._core=e;const{notificationCenter:t,InnerEvent:s,channel:o}=this._core;t.subscribeInnerEvent(s.OVERLOAD_PUSH,this._handleOverLoadPush,this),t.subscribeInnerEvent(s.LOGOUT,this._reset,this),t.subscribeInnerEvent(s.DESTROY,this._dispose,this),o.registerBeforeSendInterceptor(this.checkServerOverload,this)}checkServerOverload(e){if(!this._serverOverloadInfoMap.has(e))return;const{overloadStartTimestamp:t,delaySeconds:s}=this._serverOverloadInfoMap.get(e);if(Date.now()-t<=1e3*s)throw new this._core.helper.ChatError({functionName:e,message:"service is busy, please try again later"});this._serverOverloadInfoMap.delete(e)}_handleOverLoadPush(e){const{OverLoadServCmd:t,DelaySecs:s}=e;this._serverOverloadInfoMap.set(t,{overloadStartTimestamp:Date.now(),delaySeconds:s})}_reset(){this._serverOverloadInfoMap.clear()}_dispose(){this._reset();const{notificationCenter:e,InnerEvent:t}=this._core;e.unSubscribeInnerEvent(t.OVERLOAD_PUSH,this._handleOverLoadPush,this),e.unSubscribeInnerEvent(t.LOGOUT,this._reset,this),e.unSubscribeInnerEvent(t.DESTROY,this._dispose,this)}};var Co=new class{constructor(){this.name="ConfigCenter"}install(e){_o.install(e),So.install(e),Eo.install(e)}};var Mo=new class{constructor(){this.name="ErrorMessage",this._core=null}install(e){return h(this,void 0,void 0,(function*(){if(this._core=e,this._canFetch()){const e=yield this._fetchErrorMessage();if(!e)return;const t=this._parseResponse(e);this._saveErrorMessage(t)}}))}_canFetch(){const e=this._core.store.getStorage("errorMessage");return!e||this._isExpired(e)}_saveErrorMessage(e){this._core.store.setStorage("errorMessage",{errorMessage:e,errorMessageSavedTime:(new Date).getTime()})}_fetchErrorMessage(){return 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){if(!e)return!0;const{errorMessageSavedTime:t}=e;return t&&(new Date).getTime()-t>=6048e5}_parseResponse(e){if("string"==typeof e){const t=e.split(";\n"),s={},o=new RegExp(/'/g);for(let e=0;e<t.length;e++){const n=t[e].indexOf(":"),i=t[e].slice(0,n);let r=t[e].slice(n+1);if(!i.startsWith("//")){if(""===r)continue;r=r.replace(o,""),s[i]=r}}return s}}};function yo(e,t){return h(this,void 0,void 0,(function*(){const{cookie:s,syncFlag:o,syncTriggerEvent:n}=e,i="openim.getmsg",r=t.helper.generateProtocolData({servcmd:i,data:{Cookie:s,SyncFlag:o,IsOnlineSync:n,NeedAbstract:1,NeedSignaling:1,NeedCachedMsg:1}}),a=`${r.head.seq}${i}`;try{const e=yield t.channel.sendPacket(r,{requestId:a});if(!e)return null;const{C2CPairUnreadCount:s,C2CRemainingUnreadCount:o,EventArray:n}=e,{unreadMessageList:i,revokedMessageList:c}=function(e,t){const s=[],o=[];return null==e||e.forEach((e=>{var n,i,r;const a=function(e,t){const{From_Account:s,From_AccountHeadurl:o,From_AccountNick:n,IsNeedReadReceipt:i,MsgBody:r,MsgClientTime:a,MsgRandom:c,MsgSeq:u,MsgTimeStamp:l,SendMsgControl:d,SupportMessageExtension:p,To_Account:h,TinyId:g,MsgCheckResult:_,CloudCustomData:m,IsPeerRead:v,MsgFlagBits:f,MsgVersion:I,EventArray:S}=e;return{from:s,avatar:o,nick:n,needReadReceipt:1===i,readReceiptSentByPeer:v,clientTime:a,messageFlagBits:f,random:c,sequence:u,time:l,messageControlInfo:d,isSupportExtension:p,to:h,tinyID:g,checkResult:_,cloudCustomData:m,messageVersion:I,eventArray:S,elements:t.message.messageHelper.parseServerPushMessageElement(r)}}(e,t);if(null===(r=null===(i=null===(n=null==e?void 0:e.EventArray)||void 0===n?void 0:n[0])||void 0===i?void 0:i.hasOwnProperty)||void 0===r?void 0:r.call(i,"C2cNotifyMsgArray"))o.push(...function(e){var t;const s=[];return null===(t=e.EventArray)||void 0===t||t.forEach((e=>{var t,o;const{C2cNotifyMsgArray:n}=e,i=null===(o=null===(t=null==n?void 0:n[0])||void 0===t?void 0:t.WithdrawC2cMsgNotify)||void 0===o?void 0:o.C2cWithdrawInfoArray;Array.isArray(i)&&s.push(...i)})),s}(e));else{const e=t.message.messageFactory.createMessage(Object.assign(Object.assign({},a),{conversationType:"C2C",flow:"in"})),{elements:o}=a;e.setElement(o),s.push(e)}})),{unreadMessageList:s,revokedMessageList:o}}(e.MsgList,t);return{syncFlag:null==e?void 0:e.SyncFlag,unreadMessageList:i,revokedMessageList:c,unreadCountList:s,overflowUnreadCountList:o,cookie:null==e?void 0:e.Cookie,groupTipList:n}}catch(e){console.warn(e)}}))}var To,Ao;!function(e){e[e.START_SYNC=0]="START_SYNC",e[e.SYNCING=1]="SYNCING",e[e.SYNC_COMPLETE=2]="SYNC_COMPLETE"}(To||(To={})),function(e){e[e.LOGIN_SUCCESS=0]="LOGIN_SUCCESS",e[e.NEW_MESSAGE_RECEIVED=1]="NEW_MESSAGE_RECEIVED"}(Ao||(Ao={}));var Oo=new class{constructor(){this.name="UnreadMessageSynchronizer",this._unreadDBMessageMap=new Map,this._cookie=""}install(e){this._core=e;const{constants:t}=e;e.helper.registerWorkflowStep(t.WORKFLOW_NAME.SYNC_SERVER_INFO_AFTER_RE_ONLINE,t.WORKFLOW_STEP.UNREAD_MESSAGE_SYNC,this._syncUnreadDBMessageAfterReOnline,this),e.helper.registerWorkflowStep(t.WORKFLOW_NAME.RECEIVE_C2C_NEW_MESSAGE,t.WORKFLOW_STEP.UNREAD_MESSAGE_SYNC,this._syncUnreadDBMessageAfterNewMessageReceived,this),e.helper.registerWorkflowStep(t.WORKFLOW_NAME.SYNC_SERVER_INFO_AFTER_LOGIN,t.WORKFLOW_STEP.UNREAD_MESSAGE_SYNC,this._syncUnreadDBMessageAfterLogin,this),e.notificationCenter.subscribeInnerEvent(e.InnerEvent.LOGOUT,this._reset,this),e.notificationCenter.subscribeInnerEvent(e.InnerEvent.DESTROY,this._dispose,this)}_syncUnreadMessage(e){return h(this,void 0,void 0,(function*(){const{isAfterReOnline:t=!1,isAfterNewMessageReceived:s=!1,isAfterLogin:o=!1}=e||{};let n=To.START_SYNC;const i=[],r=[],a=[],c=[];for(;this._canContinueSync({cookie:this._cookie,syncFlag:n});){const e=yield this._fetchUnreadDBMessage({cookie:this._cookie,syncFlag:n,syncTriggerEvent:s?Ao.NEW_MESSAGE_RECEIVED:Ao.LOGIN_SUCCESS});if(!e)break;const{unreadMessageList:o=[],revokedMessageList:u=[],overflowUnreadCountList:l,unreadCountList:d,groupTipList:p}=e;if(this._cookie=(null==e?void 0:e.cookie)||"",n=null==e?void 0:e.syncFlag,this._parseAndSaveUnreadMessageList(o),a.push(...u),this._updateConversationUnreadOptions({unreadCountList:d,overflowUnreadCountList:l,conversationUpdateFieldList:i}),Array.isArray(p)&&r.push(...p),t){const{messages:e}=this._handleNewMessageList(o);c.push(...e)}}return t?{conversationUpdateFieldList:i,revokedMessageList:a,unreadMessageMap:this._unreadDBMessageMap,groupTipList:r,messages:c}:{conversationUpdateFieldList:i,isInstantMessage:!o,isUnreadC2CMessage:!0,revokedMessageList:a,unreadMessageMap:this._unreadDBMessageMap,groupTipList:r}}))}_syncUnreadDBMessageAfterLogin(){return h(this,void 0,void 0,(function*(){return this._cookie="",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){const{unreadCountList:t,overflowUnreadCountList:s,conversationUpdateFieldList:o}=e,{constants:{OuterConstant:{CONV_C2C:n,CONV_SYSTEM:i}}}=this._core;null==t||t.forEach((e=>{const{From_Account:t,UnreadCount:s}=e;if(t!==i){const e=o.find((({conversationID:e})=>e===`${n}${t}`));e?e.unreadCount=s:o.push({conversationID:`${n}${t}`,unreadCount:s,type:n})}})),null==s||s.forEach((e=>{const{From_Account:t,LastMsgTime:s}=e;if(t!==i){o.find((({conversationID:e})=>e===`${n}${t}`))||o.push({conversationID:`${n}${t}`,type:n,lastMsgTime:s})}}))}_syncUnreadDBMessageAfterReOnline(){return h(this,void 0,void 0,(function*(){return this._syncUnreadMessage({isAfterReOnline:!0})}))}_updateMessageProfile(e){var t;const{messageDataHandler:s}=this._core.message||{},o=null===(t=this._core.store.get("login"))||void 0===t?void 0:t.userId,{from:n,nick:i,avatar:r,conversationID:a=""}=e;if(n!==o){const t=s.getLatestMsgSentByPeer(a);if(t){const{nick:o,avatar:n}=t;i&&r?i===o&&r===n||s.updateNickAndAvatarOfSentMessage({conversationID:a,latestNick:i,latestAvatar:r,isSentByMe:!1}):(e.nick=o,e.avatar=n)}}else{const e=s.getLatestMsgSentByMe(a);!e||i===e.nick&&r===e.avatar||s.updateNickAndAvatarOfSentMessage({conversationID:a,latestNick:i,latestAvatar:r,isSentByMe:!0})}}_handleNewMessageList(e){const{messageDataHandler:t}=this._core.message||{},s=new Map,o=[];return e.forEach((e=>{this._updateMessageProfile(e);let n=1===e.isModified;if(t.isMessageSentByCurrentInstance(e)?e.isModified=n:n=!1,e.isOnlineMessage())e._onlineOnlyFlag=!0,t.isMessageSentByCurrentInstance(e)||o.push(e);else if(!t.isInMessageList(e)){if(t.storeConversationMessage(e)){const{conversationID:t,conversationType:o,conversationSubType:n,flow:i,_isExcludedFromUnreadCount:r,_isExcludedFromLastMessage:a}=e,c=a?"":e;s.has(t)?(s.get(t).lastMessage=c,"in"===i&&(r||s.get(t).unreadCount++)):s.set(t,{conversationID:t,type:o,subType:n,unreadCount:r||"in"!==i?0:1,lastMessage:c})}t.isMessageSentByCurrentInstance(e)&&!n||o.push(e)}})),{messages:o,conversationOptions:s}}_fetchUnreadDBMessage(e){return h(this,void 0,void 0,(function*(){try{const t="unread-message-synchronizer._fetchUnreadDBMessage";console.log(`${t} options:`,e);const s=yield yo(e,this._core);if(!s)return null;const{syncFlag:o,unreadMessageList:n,revokedMessageList:i,cookie:r,unreadCountList:a,overflowUnreadCountList:c,groupTipList:u}=s;return this._parseAndSaveUnreadMessageList(n),{syncFlag:o,cookie:r,unreadMessageList:n,revokedMessageList:i,unreadCountList:a,overflowUnreadCountList:c,groupTipList:u}}catch(e){console.log(e)}}))}_canContinueSync({cookie:e,syncFlag:t}){var s;return t===To.START_SYNC||t===To.SYNCING&&!(null===(s=this._core)||void 0===s?void 0:s.helper.isEmpty(e))}_parseAndSaveUnreadMessageList(e){e.forEach((e=>{const{ID:t}=e;this._unreadDBMessageMap.set(t,e)}))}_reset(){this._cookie="",this._unreadDBMessageMap.clear()}_dispose(){var e,t;null===(e=this._core)||void 0===e||e.notificationCenter.unSubscribeInnerEvent(this._core.InnerEvent.LOGOUT,this._reset,this),null===(t=this._core)||void 0===t||t.notificationCenter.unSubscribeInnerEvent(this._core.InnerEvent.DESTROY,this._dispose,this),this._reset()}};var Do=new class{init(e){var t;this._core=e,this._visibilityChangeHandler=this._handleVisibilityChange.bind(this),e.notificationCenter.subscribeInnerEvent(e.InnerEvent.DESTROY,this._dispose,this),document.addEventListener("visibilitychange",this._visibilityChangeHandler),null===(t=this._core)||void 0===t||t.store.set("activityMonitor",{isActive:!0})}_handleVisibilityChange(){var e,t;const s="visible"===document.visibilityState;null===(e=this._core)||void 0===e||e.store.set("activityMonitor",{isActive:s}),null===(t=this._core)||void 0===t||t.notificationCenter.emitInnerEvent("activityStatusChange",{isActive:s})}_reset(){var e;null===(e=this._core)||void 0===e||e.store.clear("activityMonitor")}_dispose(){document.removeEventListener("visibilitychange",this._visibilityChangeHandler);const{notificationCenter:e,InnerEvent:t}=this._core;e.unSubscribeInnerEvent(t.DESTROY,this._dispose,this),this._reset()}};var Ro=new class{init(e){var t;this._core=e,this._bindAppActivityEvent(),e.notificationCenter.subscribeInnerEvent(e.InnerEvent.DESTROY,this._dispose,this),null===(t=this._core)||void 0===t||t.store.set("activityMonitor",{isActive:!0})}_bindAppActivityEvent(){var e;const{MINI_APP_NAMESPACE:t}=(null===(e=this._core)||void 0===e?void 0:e.utils)||{};t.onAppShow((()=>{var e,t;null===(e=this._core)||void 0===e||e.store.set("activityMonitor",{isActive:!0}),null===(t=this._core)||void 0===t||t.notificationCenter.emitInnerEvent("activityStatusChange",{isActive:!0})})),t.onAppHide((()=>{var e,t;null===(e=this._core)||void 0===e||e.store.set("activityMonitor",{isActive:!1}),null===(t=this._core)||void 0===t||t.notificationCenter.emitInnerEvent("activityStatusChange",{isActive:!1})}))}_reset(){var e;null===(e=this._core)||void 0===e||e.store.clear("activityMonitor")}_dispose(){const{notificationCenter:e,InnerEvent:t}=this._core;e.unSubscribeInnerEvent(t.DESTROY,this._dispose,this),this._reset()}};var Lo=new class{init(e){const{IN_WX_MINI_APP:t,IN_WX_MINI_PLUGIN:s}=e.helper;s||(t?Ro.init(e):Do.init(e))}};const No="none",bo="online";var Go=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,s;const{isConnected:o,networkType:n}=e;null===(t=this._core)||void 0===t||t.store.set("netWorkMonitor",{isNetworkOnline:o,networkType:n}),null===(s=this._core)||void 0===s||s.notificationCenter.emitInnerEvent("networkStatusChange",{isNetworkOnline:o,networkType:n})}_onOnline(){this._onNetworkStatusChange({isConnected:!0,networkType:bo})}_onOffline(){this._onNetworkStatusChange({isConnected:!1,networkType:No})}_reset(){var e;this._deactivateNetworkMonitoring(),null===(e=this._core)||void 0===e||e.store.clear("netWorkMonitor")}_dispose(){var e,t;null===(e=this._core)||void 0===e||e.notificationCenter.unSubscribeInnerEvent(null===(t=this._core)||void 0===t?void 0:t.InnerEvent.DESTROY,this._dispose,this),this._reset()}};var wo=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,s;const{isConnected:o,networkType:n}=e;null===(t=this._core)||void 0===t||t.store.set("netWorkMonitor",{isNetworkOnline:o,networkType:n}),null===(s=this._core)||void 0===s||s.notificationCenter.emitInnerEvent("networkStatusChange",{isNetworkOnline:o,networkType:n})}_reset(){var e;this._deactivateNetworkMonitoring(),null===(e=this._core)||void 0===e||e.store.clear("netWorkMonitor")}_dispose(){var e,t;null===(e=this._core)||void 0===e||e.notificationCenter.unSubscribeInnerEvent(null===(t=this._core)||void 0===t?void 0:t.InnerEvent.DESTROY,this._dispose,this),this._reset()}};var Po=new class{init(e){const{IN_WX_MINI_APP:t}=e.helper;t?wo.init(e):Go.init(e)}};var Uo=new class{constructor(){this.name="SystemStateMonitor"}install(e){Lo.init(e),Po.init(e)}};const ko=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.*"]),Fo="tui_room_svr.*";var $o=new class{constructor(){this.name="BusinessCommandTransfer",this._transferredCommands=ko}install(e){this._core=e;const{notificationCenter:t,InnerEvent:s,helper:o}=e;t.subscribeInnerEvent(s.CLOUD_CONFIG_UPDATE,this._onCloudConfigUpdate,this),t.subscribeInnerEvent(s.LOGOUT,this._reset,this),t.subscribeInnerEvent(s.DESTROY,this._dispose,this),t.subscribeInnerEvent("im_open_push.msg_push",t.InnerEventSubType.BUSINESS_COMMAND,this._onServerPushBusinessCommand,this),o.registerExperimentalAPI("sendTRTCCustomData",this,"transferBusinessCommand"),o.registerExperimentalAPI("sendRoomCustomData",this,"transferBusinessCommand")}transferBusinessCommand(e){return h(this,void 0,void 0,(function*(){const t="transferBusinessCommand";try{const{serviceCommand:s=Fo}=e||{};if(!this._isValidTransferredCommand(s))throw new this._core.helper.ChatError({code:2995,functionName:t});const o=yield function(e,t){return h(this,void 0,void 0,(function*(){const{helper:s,channel:o}=t,{serviceCommand:n=Fo,data:i}=e||{};let r={};try{r="string"==typeof i?JSON.parse(i):i}catch(e){console.warn(e)}const a=s.generateProtocolData({servcmd:n,data:r}),c=`${a.head.seq}${n}`;return o.sendPacket(a,{requestId:c})}))}(e,this._core);return{code:0,data:o||{}}}catch(e){throw console.warn(e),new this._core.helper.ChatError({code:null==e?void 0:e.errorCode,message:null==e?void 0:e.errorInfo,data:{},functionName:t})}}))}_onCloudConfigUpdate(e={}){try{if("string"!=typeof e.rtc_cmd)return;const t=JSON.parse(e.rtc_cmd);Array.isArray(t)&&(this._transferredCommands=new Set([...this._transferredCommands,...t]))}catch(e){console.log(e)}}_isValidTransferredCommand(e=""){const t=`${null==e?void 0:e.split(".")[0]}.*`;return this._transferredCommands.has(t)}_onServerPushBusinessCommand(e){const{OuterEvent:t,notificationCenter:s}=this._core,{MsgContent:o}=e||{},{ROOM_CUSTOM_DATA_RECEIVED:n}=t;s.emitOuterEvent(n,{name:n,data:o})}_reset(){this._transferredCommands=ko}_dispose(){const{notificationCenter:e,InnerEvent:t}=this._core;this._reset(),e.unSubscribeInnerEvent(t.CLOUD_CONFIG_UPDATE,this._onCloudConfigUpdate,this),e.unSubscribeInnerEvent(t.LOGOUT,this._reset,this),e.unSubscribeInnerEvent(t.DESTROY,this._dispose,this),e.unSubscribeInnerEvent("im_open_push.msg_push",e.InnerEventSubType.BUSINESS_COMMAND,this._onServerPushBusinessCommand,this)}};const qo=1,xo=2,Vo=3,Bo=4,jo=5,Ko="TIMCustomElem",Ho="C2C",Wo="GROUP",Yo="invite",zo="accept",Jo="cancel",Qo="reject",Xo="modifyInvitation",Zo="signaling",en=8010,tn="signaling-timeout";function sn(e){return e.filter((e=>{if(e.type===Ko){const{cloudCustomData:t="",payload:{data:s=""}={}}=e,o=t.match(/"type":"tsignaling"/),n=s.match(/inviteID/),i=s.match(/actionType/);return o||n&&i}return!1}))}function on(e){const{data:t}=e.payload;try{return JSON.parse(t)}catch(e){return console.error(e),null}}function nn(e,t){return e.toString(16).padStart(t,"0")}function rn(e){if(e<0||e>53)throw new Error("Number of digits must be between 0 and 53");if(e<=30)return Math.floor(Math.random()*(1<<e));const t=e-30;return Math.floor(Math.random()*(1<<t))*(1<<30)+Math.floor(Math.random()*(1<<30))}var an=new class{constructor(){this._onlineSignalingMap=new Map,this._isSignalingListening=!1}init(e){this._core=e,e.notificationCenter.subscribeInnerEvent(e.InnerEvent.DESTROY,this._dispose,this),e.notificationCenter.subscribeInnerEvent(e.InnerEvent.LOGOUT,this._reset,this)}getOnlineSignalingMap(){return this._onlineSignalingMap}hasSignaling(e){return this._onlineSignalingMap.has(e)}getSignaling(e){return this._onlineSignalingMap.get(e)}saveSignaling(e,t){return this._onlineSignalingMap.set(e,t)}removeSignaling(e){return this._onlineSignalingMap.delete(e)}isInvitationValid(e){const t=`${Zo}.isInvitationValid`,{inviteID:s,groupID:o,inviter:n}=e,i=n===this._core.common.getCurrentUserID();if(!this._onlineSignalingMap.has(s))return!1;const{inviteeList:r}=this._onlineSignalingMap.get(s);if(console.log(`${t} inviteID:${s} inviteeList:${r} groupID:${o}`),o){if(i)return r.length>0;const e=this._core.common.getCurrentUserID();return r.includes(e)}return!0}updateSignaling(e){const t=`${Zo}.updateSignaling`,{inviteID:s,inviter:o,inviteeList:n,groupID:i}=e;if(console.log(`${t} inviteID:${s} inviter:${o} groupID:${i}`),i&&this.hasSignaling(s)){const e=n[0],{inviteeList:o}=this._onlineSignalingMap.get(s);o.includes(e)&&(o.splice(o.indexOf(e),1),console.log(`${t} remove ${e}. localInviteeList.length:${o.length}`)),0===o.length&&this.removeSignaling(s)}else this.removeSignaling(s)}setSignalingListenStatus(e){this._isSignalingListening=e}getSignalingListenStatus(){return this._isSignalingListening}_dispose(){var e,t;this._reset(),null===(e=this._core)||void 0===e||e.notificationCenter.unSubscribeInnerEvent(this._core.InnerEvent.DESTROY,this._dispose,this),null===(t=this._core)||void 0===t||t.notificationCenter.unSubscribeInnerEvent(this._core.InnerEvent.LOGOUT,this._reset,this),this._isSignalingListening=!1}_reset(){this._onlineSignalingMap.clear()}};var cn=new class{init(e){this._core=e}createInviteSignaling(e){const t=this._generateInviteID(),s=this._createInviteSignalingData(Object.assign(Object.assign({},e),{inviteID:t})),{groupID:o,inviteeList:n}=s,i=o||n[0];return{signaling:this._createSignaling(s,i),signalingData:s,signalingExtensionOptions:this._createSignalingExtensionOptions(e)}}createAcceptSignaling(e){const t=this._createAcceptSignalingData(e),{groupID:s,inviter:o}=t,n=s||o;return{signaling:this._createSignaling(t,n),signalingData:t,signalingExtensionOptions:this._createSignalingExtensionOptions(e)}}createCancelSignaling(e){const t=this._createCancelSignalingData(e),{groupID:s,inviteeList:o}=t,n=s||o[0];return{signaling:this._createSignaling(t,n),signalingData:t,signalingExtensionOptions:this._createSignalingExtensionOptions(e)}}createRejectSignaling(e){const t=this._createRejectSignalingData(e),{groupID:s,inviter:o}=t,n=s||o;return{signaling:this._createSignaling(t,n),signalingData:t,signalingExtensionOptions:this._createSignalingExtensionOptions(e)}}createTimeoutSignaling(e){const{isInviter:t=!1}=e,s=this._createTimeoutSignalingData(e),{groupID:o,inviteeList:n,inviter:i}=s,r=o||(t?n[0]:i);return{signaling:this._createSignaling(s,r),signalingData:s,signalingExtensionOptions:this._createSignalingExtensionOptions(s)}}_createSignalingExtensionOptions(e){var t,s;const{data:o="",onlineUserOnly:n,inviteID:i="",offlinePushInfo:r,actionType:a}=e,c=(null===(s=null===(t=an.getSignaling(i))||void 0===t?void 0:t.signaling)||void 0===s?void 0:s._onlineOnlyFlag)||!1;return{onlineUserOnly:n||c,offlinePushInfo:r,messageControlInfo:this._createMessageControlInfo(o,a)}}_createMessageControlInfo(e,t){const s=t===jo&&!!e.match(/excludeTimeoutSignalingFromHistoryMessage/),o=!!e.match(/excludeFromHistoryMessage/)||!!e.match(/excludeOriginalSignalingFromHistoryMessage/);return{excludedFromContentModeration:!0,excludedFromUnreadCount:s||o,excludedFromLastMessage:s||o}}_createInviteSignalingData(e){const t=`${Zo}._createInviteSignalingData`,{userID:s,timeout:o=0,groupID:n="",inviteeList:i=[]}=e,r=this._core.common.getCurrentUserID(),a=Object.assign(Object.assign({},this._generateBaseSignalData(e)),{actionType:qo,inviter:r,inviteeList:n?i:[s],timeout:o});return console.log(`${t} signalingData:`,a),a}_createAcceptSignalingData(e){const t=`${Zo}._createAcceptSignalingData`,{inviteID:s}=e,o=this._core.common.getCurrentUserID(),{inviter:n,groupID:i}=an.getSignaling(s),r=Object.assign(Object.assign({},this._generateBaseSignalData(e)),{actionType:Vo,groupID:i,inviter:n,inviteeList:[o]});return console.log(`${t} signalingData:`,r),r}_createCancelSignalingData(e){const t=`${Zo}._createCancelSignalingData`,{inviteID:s}=e,o=this._core.common.getCurrentUserID(),{inviteeList:n,groupID:i}=an.getSignaling(s),r=Object.assign(Object.assign({},this._generateBaseSignalData(e)),{actionType:xo,groupID:i,inviter:o,inviteeList:n});return console.log(`${t} signalingData:`,r),r}_createRejectSignalingData(e){const t=`${Zo}._createRejectSignalingData`,{inviteID:s}=e,o=this._core.common.getCurrentUserID(),{inviter:n,groupID:i}=an.getSignaling(s),r=Object.assign(Object.assign({},this._generateBaseSignalData(e)),{actionType:Bo,groupID:i,inviter:n,inviteeList:[o]});return console.log(`${t} signalingData:`,r),r}_createTimeoutSignalingData(e){const t=`${Zo}._createTimeoutSignalingData`,{isInviter:s=!1,inviteID:o}=e,{inviteeList:n,inviter:i}=an.getSignaling(o),r=this._core.common.getCurrentUserID(),a=Object.assign(Object.assign({},this._generateBaseSignalData(e)),{actionType:jo,inviter:i,inviteeList:s?n:[r]});return console.log(`${t} signalingData:`,a),a}_createSignaling(e,t){var s,o,n;const{groupID:i=""}=e,r={to:t,conversationType:i?Wo:Ho,priority:"High",payload:{data:JSON.stringify(e)}};return null===(n=null===(o=null===(s=this._core)||void 0===s?void 0:s.message)||void 0===o?void 0:o.messageFactory)||void 0===n?void 0:n.createCustomMessage(r)}_generateInviteID(){return[nn(rn(32),8),nn(rn(16),4),nn(16384|rn(12),4),nn(32768|rn(14),4),nn(rn(48),12)].join("-")}_generateBaseSignalData(e){const{data:t="",inviteID:s="",groupID:o=""}=e;return{businessID:1,timeout:0,data:t,inviteID:s,groupID:o}}};var un=new class{constructor(){this._isProcessingSignaling=!1}init(e){this._core=e,e.helper.registerApi({apiName:"invite",context:this}),e.helper.registerApi({apiName:"accept",context:this}),e.helper.registerApi({apiName:"cancel",context:this}),e.helper.registerApi({apiName:"reject",context:this}),e.helper.registerApi({apiName:"modifyInvitation",context:this}),e.helper.registerApi({apiName:"getSignalingInfo",context:this}),e.helper.registerApi({apiName:"addSignalingListener",context:this}),e.helper.registerApi({apiName:"removeSignalingListener",context:this}),e.notificationCenter.subscribeInnerEvent(e.InnerEvent.DESTROY,this._dispose,this),e.notificationCenter.subscribeInnerEvent(e.InnerEvent.LOGOUT,this._reset,this)}invite(e){return h(this,void 0,void 0,(function*(){var t;console.log(`${Zo}.invite params:${JSON.stringify(e)}`);try{this._validateBeforeInvite(e);const{signaling:s,signalingData:o,signalingExtensionOptions:n}=cn.createInviteSignaling(e),i=yield this._sendSignaling(s,n);if(0===(null==i?void 0:i.code)){const{inviteID:e,timeout:n}=o;return an.saveSignaling(e,Object.assign(Object.assign({},o),{signaling:s})),n>0&&(null===(t=this._core)||void 0===t||t.helper.taskScheduler.addOnceTask({id:`${tn}-${e}`,intervalMs:1e3*(n+5),callback:this.handleInvitationExpiryTimer.bind(this,e)})),Object.assign(Object.assign({},i),{inviteID:e})}return i}catch(e){throw console.error(`${Zo}.invite error:${e}`),e}}))}accept(e){return h(this,void 0,void 0,(function*(){console.log(`${Zo}.accept params:${JSON.stringify(e)}`);try{const{inviteID:t}=e;this._validateBeforeAccept(t),this._isProcessingSignaling=!0;const{signaling:s,signalingData:o,signalingExtensionOptions:n}=cn.createAcceptSignaling(e),i=yield this._sendSignaling(s,n);return 0===(null==i?void 0:i.code)?(an.updateSignaling(o),Object.assign(Object.assign({},i),{inviteID:t})):i}catch(e){throw console.error(`${Zo}.accept error:${e}`),e}finally{this._isProcessingSignaling=!1}}))}cancel(e){return h(this,void 0,void 0,(function*(){console.log(`${Zo}.cancel params:${JSON.stringify(e)}`);try{const{inviteID:t}=e;this._validateBeforeCancel(t),this._isProcessingSignaling=!0;const{signaling:s,signalingExtensionOptions:o}=cn.createCancelSignaling(e),n=yield this._sendSignaling(s,o);return 0===(null==n?void 0:n.code)?(an.removeSignaling(t),Object.assign(Object.assign({},n),{inviteID:t})):n}catch(e){throw console.error(`${Zo}.cancel error:${e}`),e}finally{this._isProcessingSignaling=!1}}))}reject(e){return h(this,void 0,void 0,(function*(){console.log(`${Zo}.reject params:${JSON.stringify(e)}`);try{const{inviteID:t}=e;this._validateBeforeReject(t),this._isProcessingSignaling=!0;const{signaling:s,signalingExtensionOptions:o}=cn.createRejectSignaling(e),n=yield this._sendSignaling(s,o);return 0===(null==n?void 0:n.code)?(an.removeSignaling(t),Object.assign(Object.assign({},n),{inviteID:t})):n}catch(e){throw console.error(`${Zo}.reject error:${e}`),e}finally{this._isProcessingSignaling=!1}}))}modifyInvitation(e){return h(this,void 0,void 0,(function*(){var t,s;console.log(`${Zo}.modifyInvitation params:${JSON.stringify(e)}`);const{inviteID:o,data:n}=e;let i="";try{this._validateBeforeModifyInvitation(o);const e=an.getSignaling(o),{signaling:r}=e,a=p(e,["signaling"]);i=r.payload.data,a.data=n,r.payload.data=JSON.stringify(a);const c=yield null===(s=null===(t=this._core)||void 0===t?void 0:t.message.messageAction)||void 0===s?void 0:s.modifyMessage(r);return an.hasSignaling(o)&&an.saveSignaling(o,Object.assign(Object.assign({},a),{signaling:r})),c}catch(e){if(i){const{signaling:e}=an.getSignaling(o);e.payload.data=i}throw e}}))}getSignalingInfo(e){if(0===sn([e]).length)return;const t=on(e),s={businessID:t.businessID||1,inviteID:t.inviteID,groupID:t.groupID||"",inviter:t.inviter||"",inviteeList:t.inviteeList||[],data:t.data||"",actionType:t.actionType||qo,timeout:t.timeout||0};return console.log(`${Zo} getSignalingInfo `,s),s}addSignalingListener(e,t,s){var o,n;e===(null===(o=this._core)||void 0===o?void 0:o.SignalingEvent.NEW_INVITATION_RECEIVED)&&an.setSignalingListenStatus(!0),null===(n=this._core)||void 0===n||n.notificationCenter.subscribeOuterEvent(e,t,s)}removeSignalingListener(e,t,s){var o,n;e===(null===(o=this._core)||void 0===o?void 0:o.SignalingEvent.NEW_INVITATION_RECEIVED)&&an.setSignalingListenStatus(!1),null===(n=this._core)||void 0===n||n.notificationCenter.unSubscribeOuterEvent(e,t,s)}handleInvitationExpiryTimer(e){const t=an.getOnlineSignalingMap(),s=this._core.common.getCurrentUserID();if(!t.has(e))return;const o=t.get(e).inviter===s;this._sendTimeoutNotice({inviteID:e,isInviter:o})}_sendSignaling(e,t){return h(this,void 0,void 0,(function*(){var s,o,n;return null===(n=null===(o=null===(s=this._core)||void 0===s?void 0:s.message)||void 0===o?void 0:o.messageSender)||void 0===n?void 0:n.sendMessage(e,t)}))}_sendTimeoutNotice(e){return h(this,void 0,void 0,(function*(){var t,s,o;console.log(`${Zo}._sendTimeoutNotice params:${JSON.stringify(e)}`);const{isInviter:n,inviteID:i}=e,{signaling:r,signalingData:a,signalingExtensionOptions:c}=cn.createTimeoutSignaling(e),u=yield this._sendSignaling(r,c);if(0===(null==u?void 0:u.code)){const{data:e,groupID:c,inviteeList:u,inviter:l}=a;null===(t=this._core)||void 0===t||t.notificationCenter.emitOuterEvent(null===(s=this._core)||void 0===s?void 0:s.SignalingEvent.INVITATION_TIMEOUT,{name:null===(o=this._core)||void 0===o?void 0:o.SignalingEvent.INVITATION_TIMEOUT,data:{data:e,groupID:c,inviteID:i,inviteeList:u,inviter:l,isSelfTimeout:!0,message:r}}),n?an.removeSignaling(i):an.updateSignaling(a)}}))}_validateInviteId(e,t){if(!an.hasSignaling(t))throw new this._core.helper.ChatError({functionName:e,code:en})}_validateProcessStatus(e){if(this._isProcessingSignaling)throw new this._core.helper.ChatError({functionName:e,message:"processing other signaling operations"})}_validateBeforeInvite(e){const t=Yo,{userID:s}=e,o=this._core.common.getCurrentUserID();if(s===o)throw new this._core.helper.ChatError({functionName:t,message:`cannot invite yourself, currentUserId:${o}, inviteeId:${s}`})}_validateBeforeAccept(e){const t=zo;this._validateInviteId(t,e),this._validateProcessStatus(t);const s=this._core.common.getCurrentUserID(),{inviteeList:o}=an.getSignaling(e);if(!o.includes(s)){const o=`userID:${s} not in inviteeList. inviteID:${e}`;throw new this._core.helper.ChatError({functionName:t,message:o})}}_validateBeforeCancel(e){const t=Jo;this._validateInviteId(t,e),this._validateProcessStatus(t);const s=this._core.common.getCurrentUserID(),{inviter:o}=an.getSignaling(e);if(o!==s){const e=`unmatched inviter:${o} and my userID:${s}`;throw new this._core.helper.ChatError({functionName:t,message:e})}}_validateBeforeReject(e){const t=Qo;this._validateInviteId(t,e),this._validateProcessStatus(t);const s=this._core.common.getCurrentUserID(),{inviteeList:o}=an.getSignaling(e);if(!o.includes(s)){const o=`userID:${s} not in inviteeList. inviteID:${e}`;throw new this._core.helper.ChatError({functionName:t,message:o})}}_validateBeforeModifyInvitation(e){const t=Xo;this._validateInviteId(t,e)}_dispose(){var e,t;this._reset(),null===(e=this._core)||void 0===e||e.notificationCenter.unSubscribeInnerEvent(this._core.InnerEvent.DESTROY,this._dispose,this),null===(t=this._core)||void 0===t||t.notificationCenter.unSubscribeInnerEvent(this._core.InnerEvent.LOGOUT,this._reset,this)}_reset(){this._isProcessingSignaling=!1}};var ln=new class{constructor(){this._actionProcessor=new Map([[qo,this._onNewInvitationReceived.bind(this)],[Bo,this._onInviteeRejected.bind(this)],[Vo,this._onInviteeAccepted.bind(this)],[xo,this._onInvitationCancelled.bind(this)],[jo,this._onInvitationTimeout.bind(this)]])}init(e){this._core=e,e.notificationCenter.subscribeOuterEvent(e.OuterEvent.MESSAGE_RECEIVED,this._handleMessageReceived,this),e.notificationCenter.subscribeOuterEvent(e.OuterEvent.MESSAGE_MODIFIED,this._handleMessageModified,this),e.notificationCenter.subscribeInnerEvent(e.InnerEvent.DESTROY,this._dispose,this)}handleActionSignaling(e){e.forEach((e=>{const t=on(e);if(t){const s=this._actionProcessor.get(t.actionType);null==s||s(t,e)}}))}_handleMessageReceived(e){if(!an.getSignalingListenStatus())return;const t=sn(e.data);0!==t.length&&this.handleActionSignaling(t)}_handleMessageModified(e){if(!an.getSignalingListenStatus())return;const t=sn(e.data);t.length>0&&t.forEach((e=>{const t=on(e);t&&this._onInvitationModified(t,e)}))}_onNewInvitationReceived(e,t){var s,o;const n=`${Zo}._onNewInvitationReceived`,{inviteID:i,inviteeList:r,groupID:a}=e,c=this._core.common.getCurrentUserID();console.log(`${n} signalingData:${JSON.stringify(e)}}`);if(a&&!r.includes(c))return;let{timeout:u}=e;const l=Date.now()/1e3-t.time;u>0&&l>0&&u>l&&(u-=l);const d=an.getSignaling(i);d!==e&&(d||an.saveSignaling(i,Object.assign(Object.assign({},e),{signaling:t})),u>0&&(null===(s=this._core)||void 0===s||s.helper.taskScheduler.addOnceTask({id:`${tn}-${i}`,intervalMs:1e3*u,callback:un.handleInvitationExpiryTimer.bind(un,i)})),this._emitEvent({name:null===(o=this._core)||void 0===o?void 0:o.SignalingEvent.NEW_INVITATION_RECEIVED,data:Object.assign(Object.assign({},this._generateBaseEmitData(e)),{inviteeList:r})}))}_onInviteeRejected(e){var t;const s=`${Zo}._onInviteeRejected`,{inviteID:o,inviter:n,groupID:i,inviteeList:r}=e,a=an.hasSignaling(o);console.log(`${s} inviteID:${o} hasInviteID:${a} inviter:${n} groupID:${i}`),a&&(an.updateSignaling(e),this._emitEvent({name:null===(t=this._core)||void 0===t?void 0:t.SignalingEvent.INVITEE_REJECTED,data:Object.assign(Object.assign({},this._generateBaseEmitData(e)),{invitee:r[0]})}))}_onInviteeAccepted(e){var t;const s=`${Zo}._onInviteeAccepted`,{inviteID:o,inviter:n,groupID:i,inviteeList:r}=e,a=an.hasSignaling(o);console.log(`${s} inviteID:${o} hasInviteID:${a} inviter:${n} groupID:${i}`),a&&(an.updateSignaling(e),this._emitEvent({name:null===(t=this._core)||void 0===t?void 0:t.SignalingEvent.INVITEE_ACCEPTED,data:Object.assign(Object.assign({},this._generateBaseEmitData(e)),{invitee:r[0]})}))}_onInvitationCancelled(e){var t;const s=`${Zo}._onInvitationCancelled`,{inviteID:o,inviter:n,groupID:i}=e,r=an.hasSignaling(o);console.log(`${s} inviteID:${o} hasInviteID:${r} inviter:${n} groupID:${i}`),r&&(an.removeSignaling(o),this._emitEvent({name:null===(t=this._core)||void 0===t?void 0:t.SignalingEvent.INVITATION_CANCELLED,data:this._generateBaseEmitData(e)}))}_onInvitationTimeout(e){var t;const s=`${Zo}._onInvitationTimeout`,{inviteID:o,inviteeList:n}=e,i=an.hasSignaling(o);console.log(`${s} inviteID:${o} hasInviteID:${i} data:${e.data}`),i&&(an.updateSignaling(e),this._emitEvent({name:null===(t=this._core)||void 0===t?void 0:t.SignalingEvent.INVITATION_TIMEOUT,data:Object.assign(Object.assign({},this._generateBaseEmitData(e)),{inviteeList:n,isSelfTimeout:!1})}))}_onInvitationModified(e,t){var s;const o=`${Zo}._onInvitationModified`,{inviteID:n,data:i}=e,r=an.hasSignaling(n);console.log(`${o} inviteID:${n} data:${i}`),r&&(an.saveSignaling(n,Object.assign(Object.assign({},e),{signaling:t})),this._emitEvent({name:null===(s=this._core)||void 0===s?void 0:s.SignalingEvent.INVITATION_MODIFIED,data:{inviteID:n,data:i}}))}_emitEvent(e){var t;null===(t=this._core)||void 0===t||t.notificationCenter.emitOuterEvent(e.name,e)}_generateBaseEmitData(e){const{inviteID:t,inviter:s,groupID:o,data:n}=e;return{inviteID:t,inviter:s,groupID:o,data:n||""}}_dispose(){var e,t,s;null===(e=this._core)||void 0===e||e.notificationCenter.unSubscribeOuterEvent(this._core.OuterEvent.MESSAGE_RECEIVED,this._handleMessageReceived,this),null===(t=this._core)||void 0===t||t.notificationCenter.unSubscribeOuterEvent(this._core.OuterEvent.MESSAGE_MODIFIED,this._handleMessageModified,this),null===(s=this._core)||void 0===s||s.notificationCenter.unSubscribeOuterEvent(this._core.InnerEvent.DESTROY,this._dispose,this)}};var dn=new class{constructor(){this._offlineSignalingMap=new Map}init(e){this._core=e;const{notificationCenter:t,helper:s,constants:{InnerEvent:o,WORKFLOW_STEP:n,WORKFLOW_NAME:i}}=e;t.subscribeInnerEvent(o.DESTROY,this._dispose,this),t.subscribeInnerEvent(o.LOGOUT,this._reset,this),s.registerWorkflowStep(i.SYNC_SERVER_INFO_AFTER_LOGIN,n.SIGNALING_MESSAGE_RECOVER,this._handleC2COfflineMessage,this)}_handleC2COfflineMessage(e){const{result:{unreadMessageMap:t}={}}=e||{};if(!(0!==(null==t?void 0:t.size)&&an.getSignalingListenStatus()))return;const s=sn([...t.values()]);if(0!==s.length&&(s.forEach((e=>{this._handleC2CActionType(e)})),this._offlineSignalingMap.size>0)){const e=this._sortOfflineSignalingByTime();ln.handleActionSignaling(e)}}_handleC2CActionType(e){const t=on(e);if(!t)return;const{actionType:s}=t;s===qo?this._saveValidOfflineInvite(t,e):this._removeOfflineInvite(t)}_saveValidOfflineInvite(e,t){const{inviteID:s,inviteeList:o=[],timeout:n=0}=e,i=this._core.common.getCurrentUserID();if(!o.includes(i))return;const r=Date.now()/1e3-t.time;n>0&&r>n&&0!==n||this._offlineSignalingMap.set(s,Object.assign(Object.assign({},e),{signalingList:[t]}))}_removeOfflineInvite(e){const{inviteID:t=""}=e;this._offlineSignalingMap.has(t)&&this._offlineSignalingMap.delete(t)}_sortOfflineSignalingByTime(){let e=[];return this._offlineSignalingMap.forEach((t=>{e=[...e,...t.signalingList]})),e.sort(((e,t)=>e.time-t.time))}_dispose(){var e,t;this._reset(),null===(e=this._core)||void 0===e||e.notificationCenter.unSubscribeInnerEvent(this._core.InnerEvent.LOGOUT,this._reset,this),null===(t=this._core)||void 0===t||t.notificationCenter.unSubscribeInnerEvent(this._core.InnerEvent.DESTROY,this._dispose,this)}_reset(){this._offlineSignalingMap.clear()}};const pn={invite:{userID:{required:!0,rules:["string"],allowEmpty:!1},data:{required:!1,rules:["string"],allowEmpty:!0},timeout:{required:!1,rules:["number"],allowEmpty:!1},onlineUserOnly:{required:!1,rules:["boolean"],allowEmpty:!1},offlinePushInfo:{required:!1,rules:["object"],allowEmpty:!1}},cancel:{inviteID:{required:!0,rules:["string"],allowEmpty:!1},data:{required:!1,rules:["string"],allowEmpty:!0}},accept:{inviteID:{required:!0,rules:["string"],allowEmpty:!1},data:{required:!1,rules:["string"],allowEmpty:!0}},reject:{inviteID:{required:!0,rules:["string"],allowEmpty:!1},data:{required:!1,rules:["string"],allowEmpty:!0}},modifyInvitation:{inviteID:{required:!0,rules:["string"],allowEmpty:!1},data:{required:!1,rules:["string"],allowEmpty:!0}}},hn={invite:!0,cancel:!0,accept:!0,reject:!0,modifyInvitation:!0};var gn=new class{constructor(){this.name="Signaling"}install(e){un.init(e),ln.init(e),cn.init(e),an.init(e),dn.init(e),e.helper.registerValidateConfig({auth:hn,params:pn})}};const _n=new class{init(e){this.core=e}};var mn,vn;!function(e){e.MSG_TEXT="TIMTextElem",e.MSG_CUSTOM="TIMCustomElem",e.MSG_LOCATION="TIMLocationElem",e.MSG_FACE="TIMFaceElem"}(mn||(mn={})),function(e){e[e.FORWARD=0]="FORWARD",e[e.BACKWARD=1]="BACKWARD"}(vn||(vn={}));const fn="MSG_REACTION",In="MSG_EXT",Sn=0,En=1,Cn={ZH_CN:"zh (cmn-Hans-CN)",EN_US:"en-US",YUE_HK:"yue-Hant-HK",JA_JP:"ja-JP",ZH_PY:"zh-PY"},Mn="16k_zh",yn="16k_en",Tn="16k_yue",An="16k_ja",On="16k_zh-PY",Dn={[Cn.ZH_CN]:Mn,[Cn.EN_US]:yn,[Cn.YUE_HK]:Tn,[Cn.JA_JP]:An,[Cn.ZH_PY]:On},Rn=/\.(wav|pcm|ogg-opus|speex|silk|mp3|m4a|aac|amr)/,Ln={READ:0,UNREAD:1},Nn=1,bn=2,Gn=3,wn=1,Pn=2;const Un=2116,kn=2500,Fn="C2C",$n="GROUP",qn=20;function xn(e){return h(this,void 0,void 0,(function*(){var t;const{appStore:s}=_n.core,{messageList:o,conversationID:n}=e,i=s.conversationStore.getConversationMap();let r=null===(t=i.get(n))||void 0===t?void 0:t.peerReadTime;if(!r){const e=n.replace(Fn,""),t=yield function(e){return h(this,void 0,void 0,(function*(){const t={To_Account:e};return _n.core.common.buildAndSendPacket({servcmd:"openim.get_peer_read_time",data:t})}))}([e]);if(t){const{ReadTime:e}=t;r=null==e?void 0:e[0],i.has(n)&&(i.get(n).peerReadTime=r)}}o.forEach((e=>{e.time<=r&&!e.isPeerRead&&"out"===e.flow&&(e.isPeerRead=!0)}))}))}function Vn(e){return h(this,void 0,void 0,(function*(){var t;const{message:s,user:o,appStore:n,constants:{OuterConstant:i}}=_n.core,r=n.conversationStore.getConversationMap();if(r.has(e)){const s=null===(t=r.get(e))||void 0===t?void 0:t.userProfile;if(s&&e.startsWith(i.CONV_C2C)){const{avatar:t,nick:o}=s;_n.core.message.messageDataHandler.updateNickAndAvatarOfSentMessage({conversationID:e,latestAvatar:t,latestNick:o,isSentByMe:!1})}}const{data:a}=(yield o.userProfile.getMyProfile())||{};if(a){const{avatar:t,nick:o}=a;s.messageDataHandler.updateNickAndAvatarOfSentMessage({conversationID:e,latestAvatar:t,latestNick:o,isSentByMe:!0})}}))}function Bn(e){let t;const{message:s}=_n.core,{conversationID:o,messageID:n}=e;if(t=s.messageDataHandler.getLocalMessageList(o).find((e=>e.ID===n)),!t){t=s.messageDataHandler.getSparseMessageList(o).find((e=>e.ID===n))}return t}function jn(e){return e.map((e=>{const{from:t,to:s,cloudCustomData:o,avatar:n,nick:i,ID:r,clientSequence:a,clientTime:c,messageRandom:u,messageSequence:l,time:d}=e;return{ClientSeq:a,CloudCustomData:o,From_Account:t,From_AccountHeadurl:n,From_AccountNick:i,Id:r,MsgBody:JSON.parse(JSON.stringify(e.transformElementsToServerFormat())),MsgClientTime:c,MsgRandom:u,Random:u,MsgSeq:l,MsgTimeStamp:d,ReceiverId:s,SenderId:t,To_Account:s}}))}function Kn(e){var t;const{From_Account:s,From_AccountHeadurl:o,From_AccountNick:n,GroupId:i,MsgClientTime:r,ClientSeq:a,To_Account:c,MsgTimeStamp:u,TinyId:l,MsgRandom:d,MsgSeq:p}=e;return{from:s,avatar:o,nick:n,clientTime:r,time:u,tinyID:l,random:d,sequence:p,to:c,groupID:i,clientSequence:a,_elements:null===(t=e.MsgBody)||void 0===t?void 0:t.map((e=>{const{MsgType:t}=e;return _n.core.message.messageFactory.getElementClass(t).parseServerPushElement(e)}))}}var Hn=new class{constructor(){this._reactionsMap=new Map}init(e){this._core=e;const{helper:t,notificationCenter:s,InnerEvent:{MESSAGE_PUSH:o},InnerEventSubType:{MESSAGE_REACTION_UPDATED:n,MESSAGE_REACTION_UPDATED_SYNC:i}}=e;t.registerApi({apiName:"addMessageReaction",context:this}),t.registerApi({apiName:"removeMessageReaction",context:this}),t.registerApi({apiName:"getMessageReactions",context:this}),t.registerApi({apiName:"getAllUserListOfMessageReaction",context:this}),s.subscribeInnerEvent(o,n,this._handleReactionUpdated,this),s.subscribeInnerEvent(o,i,this._handleReactionSync,this)}addMessageReaction(e,t){return h(this,void 0,void 0,(function*(){const{OuterConstant:s,ssoLog:o,helper:n}=this._core;this._validateMessageReactionBusinessCapability();const i=o.createSSOLogData({method:"addMessageReaction"}),{conversationID:r,ID:a,conversationType:c,from:u,to:l,clientSequence:d,random:p,time:g,sequence:_}=e;try{return this._recordMessageReactedByMe(a,t),c===s.CONV_C2C?yield function(e,t){return h(this,void 0,void 0,(function*(){var s;const{from:o,to:n,clientSequence:i,random:r,time:a,reactionID:c}=e,u={From_Account:o,To_Account:n,MsgKey:`${i}_${r}_${a}`,Reaction:c,Add_Account:[null===(s=t.store.get("login"))||void 0===s?void 0:s.userId]};return _n.core.common.buildAndSendPacket({servcmd:"openim_msg_ext_http_svc.reaction_add",data:u})}))}({from:u,to:l,clientSequence:d,random:p,time:g,reactionID:t},this._core):c===s.CONV_GROUP&&(yield function(e,t){return h(this,void 0,void 0,(function*(){var s;const{to:o,reactionID:n,sequence:i}=e,r={GroupId:o,MsgSeq:i,Reaction:n,Add_Account:[null===(s=t.store.get("login"))||void 0===s?void 0:s.userId]};return _n.core.common.buildAndSendPacket({servcmd:"openim_msg_ext_http_svc.group_reaction_add",data:r})}))}({to:l,reactionID:t,sequence:_},this._core)),i.setLogInfo({message:`conversationID:${r} messageID:${a} reactionID:${t}`}).end(),{code:0}}catch(e){this._removeMyReactionRecord(a,t);const{errorCode:s}=e||{},o=new n.ChatError({functionName:"addMessageReaction",code:s});i.setError(o).end(),console.error("addMessageReaction error: ",e)}}))}removeMessageReaction(e,t){return h(this,void 0,void 0,(function*(){const{OuterConstant:s,ssoLog:o,helper:n}=this._core;this._validateMessageReactionBusinessCapability();const i=o.createSSOLogData({method:"removeMessageReaction"});try{const{conversationID:o,ID:n,conversationType:r,from:a,to:c,clientSequence:u,random:l,time:d,sequence:p}=e;return this._removeMyReactionRecord(n,t),r===s.CONV_C2C?yield function(e,t){return h(this,void 0,void 0,(function*(){var s;const{from:o,to:n,clientSequence:i,random:r,time:a,reactionID:c}=e,u={From_Account:o,To_Account:n,MsgKey:`${i}_${r}_${a}`,Reaction:c,Del_Account:[null===(s=t.store.get("login"))||void 0===s?void 0:s.userId]};return _n.core.common.buildAndSendPacket({servcmd:"openim_msg_ext_http_svc.reaction_del",data:u})}))}({from:a,to:c,clientSequence:u,random:l,time:d,reactionID:t},this._core):r===s.CONV_GROUP&&(yield function(e,t){return h(this,void 0,void 0,(function*(){var s;const{to:o,reactionID:n,sequence:i}=e,r={GroupId:o,MsgSeq:i,Reaction:n,Del_Account:[null===(s=t.store.get("login"))||void 0===s?void 0:s.userId]};return _n.core.common.buildAndSendPacket({servcmd:"openim_msg_ext_http_svc.group_reaction_del",data:r},t)}))}({to:c,reactionID:t,sequence:p},this._core)),i.setLogInfo({message:`conversationID:${o} messageID:${n} reactionID:${t}`}).end(),{code:0}}catch(e){const{errorCode:t}=e||{},s=new n.ChatError({functionName:"removeMessageReaction",code:t});i.setError(s).end(),console.error("removeMessageReaction error: ",e)}}))}getAllUserListOfMessageReaction(e){return h(this,void 0,void 0,(function*(){this._validateMessageReactionBusinessCapability();const{message:t,reactionID:s,nextSeq:o=0}=e,n=e.count>100?100:e.count,{conversationID:i}=t,{ssoLog:r,helper:a,constants:c}=this._core;try{let e=null;if(e=i.startsWith(c.OuterConstant.CONV_C2C)?yield function(e){return h(this,void 0,void 0,(function*(){const{message:t,nextSeq:s,reactionID:o,count:n}=e,{from:i,to:r,clientSequence:a,random:c,time:u}=t,l={Reaction:o,NextSeq:s,Count:n,From_Account:i,To_Account:r,MsgKey:`${a}_${c}_${u}`};return _n.core.common.buildAndSendPacket({servcmd:"openim_msg_ext_http_svc.reaction_iterate",data:l})}))}({message:t,reactionID:s,nextSeq:o,count:n}):yield function(e){return h(this,void 0,void 0,(function*(){const{message:t,nextSeq:s,reactionID:o,count:n}=e,{sequence:i,to:r}=t,a={Reaction:o,NextSeq:s,GroupId:r,Count:n,MsgSeq:i};return _n.core.common.buildAndSendPacket({servcmd:"openim_msg_ext_http_svc.group_reaction_iterate",data:a})}))}({message:t,reactionID:s,nextSeq:o,count:n}),e){const{Reaction_Account:t,NextSeq:s}=e,n=yield this._getUserProfileList(t);return{code:0,data:{nextSeq:s,isCompleted:0===o,userList:n}}}}catch(e){const{errorCode:t}=e||{},s=new a.ChatError({functionName:"getAllUserListOfMessageReaction",code:t});r.createSSOLogData({method:"removeMessageReaction"}).setError(s).end(),console.error("getAllUserListOfMessageReaction error: ",e)}}))}getMessageReactions(e){return h(this,void 0,void 0,(function*(){const{constants:t}=this._core;this._validateMessageReactionBusinessCapability();const{messageList:s,maxUserCountPerReaction:o=10}=e,n=s[0];let i=null;const r=new Map,{from:a,to:c,conversationType:u}=n,l=this._generateMessageKeyList(s,r);u===t.OuterConstant.CONV_C2C?i=yield function(e){return h(this,void 0,void 0,(function*(){const{from:t,to:s,messageKeyList:o,maxUserCountPerReaction:n}=e,i={From_Account:t,To_Account:s,MsgKeyList:o,Count:n};return _n.core.common.buildAndSendPacket({servcmd:"openim_msg_ext_http_svc.reaction_multi_stat",data:i})}))}({from:a,to:c,messageKeyList:l,maxUserCountPerReaction:o}):u===t.OuterConstant.CONV_GROUP&&(i=yield function(e){return h(this,void 0,void 0,(function*(){const{groupId:t,messageSequenceList:s,maxUserCountPerReaction:o}=e,n={GroupId:t,MsgSeqList:s,Count:o};return _n.core.common.buildAndSendPacket({servcmd:"openim_msg_ext_http_svc.group_reaction_multi_stat",data:n})}))}({groupId:c,messageSequenceList:l,maxUserCountPerReaction:o}));const{Results:d=[]}=i||{},p=this._extractUserIDsFromReactionResults(d),g=yield this._getUserProfileMap(p);return{code:0,data:{resultList:d.map((e=>{const{ReactionList:t,MsgSeq:s,MsgKey:o}=e;return{messageID:this._generateMessageID({messageSequence:s,messageKey:o,messageIDMap:r}),reactionList:t.map((e=>{const{Reaction:t,Count:s,Reaction_Account:o,ReactedByMe:n}=e;return{reactionID:t,totalUserCount:s,partialUserList:this._generatePartialUserInfo({userIDList:o,userProfileMap:g}),reactedByMyself:1===n}}))}}))}}}))}dispose(){this._reactionsMap.clear()}_extractUserIDsFromReactionResults(e){const t=[];return null==e||e.forEach((e=>{const{ReactionList:s=[]}=e;s.forEach((e=>{e.Reaction_Account&&t.push(...e.Reaction_Account)}))})),t}_getUserProfileList(e){return h(this,void 0,void 0,(function*(){var t;try{const s=yield null===(t=this._core.user.userProfile)||void 0===t?void 0:t.getUserProfile({userIDList:e});return s?s.data:[]}catch(e){return[]}}))}_getUserProfileMap(e){return h(this,void 0,void 0,(function*(){const t=new Map;return(yield this._getUserProfileList(e)).forEach((e=>{const{nick:s,avatar:o,userID:n}=e;t.set(n,{nick:s,avatar:o,userID:n})})),t}))}_recordMessageReactedByMe(e,t){const s=`${e}-${t}`;this._reactionsMap.has(s)?this._reactionsMap.get(s).reactedByMe=!0:this._reactionsMap.set(s,{reactedByMe:!0})}_removeMyReactionRecord(e,t){const s=`${e}-${t}`;this._reactionsMap.has(s)&&(this._reactionsMap.get(s).reactedByMe=!1)}_recordMessageReactionInfo(e){const{messageID:t,reactionID:s,reactionInfo:o}=e,n=`${t}-${s}`,i=this._reactionsMap.get(n)||{};this._reactionsMap.set(n,Object.assign(Object.assign({},i),o))}_validateMessageReactionBusinessCapability(){const{helper:e,constants:t}=this._core;if(!e.checkBusinessCapabilityBits(fn))throw new e.ChatError({functionName:"addMessageReaction",code:t.ERROR_CODE.NO_USE,replacement1:"addMessageReaction"})}_handleReactionUpdated(e){const{MsgReactionNotifyList:t}=e,{notificationCenter:s,constants:o}=this._core;t.forEach((e=>h(this,void 0,void 0,(function*(){const{C2CMsgInfo:t,GroupMsgInfo:n,MsgReactionSummary:i}=e,{TinyId:r,MsgClientTime:a,MsgRandom:c}=Object.assign(Object.assign({},t),n),u=`${r}-${a}-${c}`,l=this._extractUserIDsFromReactionResults([{ReactionList:i}]),d=yield this._getUserProfileMap(l),p=i.map((e=>{var t;const{Reaction:s,Reaction_Account:o}=e,n=this._generatePartialUserInfo({userIDList:o,userProfileMap:d}),i=o?e.Count:0,r=(null===(t=this._reactionsMap.get(`${u}-${s}`))||void 0===t?void 0:t.reactedByMe)||!1;return this._recordMessageReactionInfo({messageID:u,reactionID:s,reactionInfo:{reactionID:s,totalUserCount:i,partialUserList:n}}),{reactionID:s,totalUserCount:i,partialUserList:n,reactedByMyself:r}}));s.emitOuterEvent(o.OuterEvent.MESSAGE_REACTIONS_UPDATED,{name:o.OuterEvent.MESSAGE_REACTIONS_UPDATED,data:{messageID:u,reactionList:p}})}))))}_handleReactionSync(e){var t;const{notificationCenter:s,constants:o}=this._core,{C2CMsgInfo:n={},GroupMsgInfo:i={},Reaction:r,OperateType:a}=e.MsgReactionNotify,{TinyId:c="",MsgClientTime:u=0,MsgRandom:l=0}=Object.assign(Object.assign({},n),i),d=`${c}-${u}-${l}`,p=`${d}-${r}`;if(1===a?this._recordMessageReactedByMe(d,r):this._removeMyReactionRecord(d,r),null===(t=this._reactionsMap.get(p))||void 0===t?void 0:t.reactionID){const e=this._reactionsMap.get(p);e.reactedByMyself=1===a,s.emitOuterEvent(o.OuterEvent.MESSAGE_REACTIONS_UPDATED,{name:o.OuterEvent.MESSAGE_REACTIONS_UPDATED,data:{messageID:d,reactionList:[e]}})}}_generatePartialUserInfo({userIDList:e,userProfileMap:t}){const s=[];return null==e||e.forEach((e=>{t.has(e)&&s.push(t.get(e))})),s}_generateMessageID(e){const{messageSequence:t,messageKey:s,messageIDMap:o}=e;return s?o.get(s):o.get(t)}_generateMessageKeyList(e,t){const{constants:s}=this._core,o=e[0],{conversationType:n}=o;let i=[];return n===s.OuterConstant.CONV_C2C?i=e.map((e=>{const{clientSequence:s,random:o,time:n,ID:i}=e,r=`${s}_${o}_${n}`;return t.set(r,i),r})):n===s.OuterConstant.CONV_GROUP&&(i=e.map((e=>{const{ID:s,sequence:o}=e;return t.set(o,s),o}))),i}};var Wn=new class{init(e){this._core=e;const{helper:t,InnerEvent:{MESSAGE_PUSH:s},InnerEventSubType:{C2C_MESSAGE_READ_RECEIPT:o,GROUP_MESSAGE_READ_RECEIPT:n},notificationCenter:i}=e;t.registerApi({apiName:"sendMessageReadReceipt",context:this}),t.registerApi({apiName:"getMessageReadReceiptList",context:this}),t.registerApi({apiName:"getGroupMessageReadMemberList",context:this}),i.subscribeInnerEvent(s,o,this._handleC2CMessageReadReceipt,this),i.subscribeInnerEvent(s,n,this._handleGroupMessageReadReceipt,this)}sendMessageReadReceipt(e){return h(this,void 0,void 0,(function*(){const{common:t,constants:s}=this._core,o=this._filterValidMessageSendByOther(e);if(0===o.length)throw new t.ChatError({code:s.ERROR_CODE.READ_RECEIPT_MSG_LIST_EMPTY});try{const{conversationType:e}=o[0];return e===s.OuterConstant.CONV_C2C?yield function(e){return h(this,void 0,void 0,(function*(){const{common:t,constants:s}=_n.core,o=e[0].conversationID.replace(s.OuterConstant.CONV_C2C,""),n=e.map((e=>{const{from:t,to:s,sequence:o,random:n,time:i,clientTime:r}=e;return{From_Account:t,To_Account:s,MsgSeq:o,MsgRandom:n,MsgTime:i,MsgClientTime:r}})),i={Peer_Account:o,C2CMsgInfo:n};return t.buildAndSendPacket({servcmd:"openim.c2c_msg_read_receipt",data:i})}))}(o):yield function(e){return h(this,void 0,void 0,(function*(){const{common:t,constants:s}=_n.core,o={GroupId:e[0].conversationID.replace(s.OuterConstant.CONV_GROUP,""),MsgSeqList:e.map((e=>({MsgSeq:e.sequence})))};return t.buildAndSendPacket({servcmd:"group_open_http_svc.group_msg_receipt",data:o})}))}(o),{code:0,data:{}}}catch(e){const{errorCode:s,errorInfo:o}=e;throw new t.ChatError({code:s,message:o})}}))}getMessageReadReceiptList(e){return h(this,void 0,void 0,(function*(){const{common:t,constants:s}=this._core;try{const{conversationType:t}=e[0];if(t===s.OuterConstant.CONV_GROUP){const t=this._filterValidMessageSendByMe(e);if((null==t?void 0:t.length)>0){const s=yield function(e){return h(this,void 0,void 0,(function*(){const{common:t,constants:s}=_n.core,o={GroupId:e[0].conversationID.replace(s.OuterConstant.CONV_GROUP,""),MsgSeqList:e.map((e=>({MsgSeq:e.sequence})))};return t.buildAndSendPacket({servcmd:"group_open_http_svc.get_group_msg_receipt",data:o})}))}(t),{GroupMsgReceiptList:o}=s||{};this._updateGroupMessagesReadReceiptInfo({messageList:e,readReceiptList:o})}}return{code:0,data:{messageList:e}}}catch(e){const{errorCode:s,errorInfo:o}=e;throw new t.ChatError({code:s,message:o})}}))}getGroupMessageReadMemberList(e){return h(this,void 0,void 0,(function*(){const{constants:t,common:s}=this._core,{message:o,filter:n=Ln.READ,cursor:i=""}=e,{conversationID:r,sequence:a,ID:c}=o,u=r.replace(t.OuterConstant.CONV_GROUP,""),l=e.count>=100?100:e.count;try{const e=yield function(e){return h(this,void 0,void 0,(function*(){const{sequence:t,groupID:s,filter:o,cursor:n,count:i}=e,r={MsgSeq:t,GroupId:s,Filter:o,Cursor:n,Num:i};return _n.core.common.buildAndSendPacket({servcmd:"group_open_http_svc.get_group_msg_receipt_detail",data:r})}))}({groupID:u,sequence:a,filter:n,cursor:i,count:l});if(e){const{Cursor:t,IsFinish:s,UnreadList:o,ReadList:i}=e,r={cursor:t,isCompleted:1===s,messageID:c,unreadUserIDList:[],readUserIDList:[]};return n===Ln.READ?r.readUserIDList=i.map((e=>e.Read_Account)):n===Ln.UNREAD&&(r.unreadUserIDList=o.map((e=>e.Unread_Account))),{code:0,data:r}}}catch(e){const{errorCode:t,errorInfo:o}=e;throw new s.ChatError({code:t,message:o})}}))}_handleC2CMessageReadReceipt(e){const t=[],{constants:s,helper:o}=this._core,{C2cMsgInfo:n,PeerReadTime:i,Peer_Account:r}=e;if(o.isEmpty(n))return;const a=`${s.OuterConstant.CONV_C2C}${r}`;null==n||n.forEach((e=>{const{TinyId:s,MsgClientTime:o,MsgRandom:n}=e,c=`${s}-${o}-${n}`,u=Bn({conversationID:a,messageID:c});u&&!u.readReceiptInfo.isPeerRead&&(u.readReceiptInfo.isPeerRead=!0,u.readReceiptInfo.timestamp=i,t.push({userID:r,messageID:c,isPeerRead:!0,timestamp:i}))})),this._emitReadReceiptEventIfNeed(t)}_updateGroupMessagesReadReceiptInfo(e){const{messageList:t,readReceiptList:s}=e,o=new Map;t.forEach((e=>{o.set(e.sequence,e)})),null==s||s.forEach((e=>{if(0===e.Code){const{MsgSeq:t,ReadNum:s,UnreadNum:n}=e,i=o.get(t);i&&(i.readReceiptInfo.readCount=s,i.readReceiptInfo.unreadCount=n)}}))}_handleGroupMessageReadReceipt(e){const t=[],{constants:s}=this._core,{GroupTips:o}=e;o.forEach((e=>{const{MsgBody:{GroupMsgReceiptList:o},GroupInfo:{GroupId:n}}=e,i=`${s.OuterConstant.CONV_GROUP}${n}`;null==o||o.forEach((e=>{const{TinyId:s,MsgClientTime:o,MsgRandom:r,ReadNum:a,UnreadNum:c}=e,u=`${s}-${o}-${r}`,l=Bn({conversationID:i,messageID:u}),d={groupID:n,messageID:u,readCount:0,unreadCount:0};l&&("number"==typeof a&&(l.readReceiptInfo.readCount=a,d.readCount=a),"number"==typeof c&&(l.readReceiptInfo.unreadCount=c,d.unreadCount=c),t.push(d))}))})),this._emitReadReceiptEventIfNeed(t)}_emitReadReceiptEventIfNeed(e){const{notificationCenter:t,OuterEvent:s}=this._core;e.length>0&&t.emitOuterEvent(s.MESSAGE_READ_RECEIPT_RECEIVED,{name:s.MESSAGE_READ_RECEIPT_RECEIVED,data:e})}_filterValidMessageSendByOther(e){return this._filterNeedReadReceiptMessages(e).filter((e=>{const{from:t}=e;return t!==this._core.common.getCurrentUserID()}))}_filterValidMessageSendByMe(e){const{OuterConstant:t}=this._core.constants;return this._filterNeedReadReceiptMessages(e).filter((e=>{const{from:s,status:o}=e;return s===this._core.common.getCurrentUserID()&&o===t.MessageStatus.SUCCESS}))}_filterNeedReadReceiptMessages(e){return e.filter((e=>!0===e.needReadReceipt))}dispose(){const{InnerEvent:{MESSAGE_PUSH:e},InnerEventSubType:{C2C_MESSAGE_READ_RECEIPT:t,GROUP_MESSAGE_READ_RECEIPT:s},notificationCenter:o}=this._core;o.unSubscribeInnerEvent(e,t,this._handleC2CMessageReadReceipt,this),o.unSubscribeInnerEvent(e,s,this._handleGroupMessageReadReceipt,this)}};function Yn(e,t,s){return h(this,void 0,void 0,(function*(){const{common:{buildAndSendPacket:o}}=_n.core,{from:n,to:i,clientSequence:r,random:a,time:c}=e;return o({servcmd:"openim_msg_ext_http_svc.set_key_values",data:{From_Account:n,To_Account:i,MsgKey:`${r}_${a}_${c}`,OperateType:s,ExtensionList:t}})}))}function zn(e,t,s){return h(this,void 0,void 0,(function*(){const{common:{buildAndSendPacket:o}}=_n.core,{to:n,sequence:i}=e;return o({servcmd:"openim_msg_ext_http_svc.group_set_key_values",data:{GroupId:n,MsgSeq:i,OperateType:s,ExtensionList:t}})}))}var Jn=new class{constructor(){this._messageExtensionsMap=new Map,this._extensionsLatestSequenceMap=new Map,this._completedFetchExtensions=new Set}init(e){this._core=e;const{notificationCenter:t,helper:{registerApi:s},InnerEvent:{MESSAGE_PUSH:o,LOGOUT:n},InnerEventSubType:{MESSAGE_EXTENSIONS_UPDATED:i}}=e;s({apiName:"setMessageExtensions",context:this}),s({apiName:"getMessageExtensions",context:this}),s({apiName:"deleteMessageExtensions",context:this}),t.subscribeInnerEvent(o,i,this._handleMessageExtensionsNotify,this),t.subscribeInnerEvent(n,this.reset,this)}setMessageExtensions(e,t){return h(this,void 0,void 0,(function*(){this._validateMessageExtensionBusinessCapability("setMessageExtensions");const{constants:{OuterConstant:s},ssoLog:o}=this._core,{ID:n,conversationID:i,sequence:r,time:a,conversationType:c}=e,u=o.createSSOLogData({method:"setMessageExtensions"});let l=t;t.length>20&&(l=t.slice(0,20),console.warn("the length of extensions cannot exceed 20"));const d=this._generateServerExtensions(e,l);try{let t;if(c===s.CONV_C2C?t=yield Yn(e,d,Nn):c===s.CONV_GROUP&&(t=yield zn(e,d,Nn)),t){const{resultList:s,successCount:o,failureCount:c}=this._handleModifyMessageExtensions(e,t);return u.setLogInfo({message:`convID:${i} messageID:${n} sequence:${r}\n time:${a} count:${l.length} successCount:${o} failCount:${c}`}).end(),{code:0,data:{extensions:s}}}return{code:0,data:{extensions:[]}}}catch(e){const{errorCode:t}=e,s=new this._core.helper.ChatError({functionName:"setMessageExtensions",code:t});throw u.setError(s).end(),s}}))}getMessageExtensions(e){return h(this,void 0,void 0,(function*(){const{utils:{isUndefined:t}}=this._core;this._validateMessageExtensionBusinessCapability("getMessageExtensions");const{conversationID:s,ID:o,sequence:n,time:i}=e,r=this._core.ssoLog.createSSOLogData({method:"getMessageExtensions"});r.setLogInfo({message:`convID:${s} messageID:${o} sequence:${n} time:${i}`});try{let s;this._completedFetchExtensions.has(o)&&(s=this._extensionsLatestSequenceMap.get(o));const n=yield this._fetchMessageExtensions(e,s);return t(s)&&n.length>1&&this._completedFetchExtensions.add(o),r.end(),{code:0,data:{extensions:n}}}catch(e){const{errorCode:t,errorInfo:s=""}=e||{},o=new this._core.common.ChatError({code:t,message:s});throw r.setError(o).end(),o}}))}deleteMessageExtensions(e,t){return h(this,void 0,void 0,(function*(){this._validateMessageExtensionBusinessCapability("deleteMessageExtensions");const{utils:{isEmpty:s},constants:{OuterConstant:o},ssoLog:n}=this._core,{conversationType:i,conversationID:r,sequence:a,ID:c,time:u}=e;let l=Gn;const d=[];s(t)||(l=bn,null==t||t.forEach((e=>{d.push({key:e,value:"",seq:0})})));const p=n.createSSOLogData({method:"deleteMessageExtensions"});p.setLogInfo({message:`convID:${r} messageID:${c} sequence:${a} time:${u} operateType:${l}`});const h=this._generateServerExtensions(e,d);try{let t;if(i===o.CONV_C2C?t=yield Yn(e,h,l):i===o.CONV_GROUP&&(t=yield zn(e,h,l)),t){const{resultList:s,successCount:o,failureCount:n}=this._handleModifyMessageExtensions(e,t);return p.setMoreMessage(`success count:${o} fail count:${n}`),p.end(),{code:0,data:{extensions:s}}}return{code:0,data:{extensions:[]}}}catch(e){const{errorCode:t}=e,s=new this._core.helper.ChatError({functionName:"deleteMessageExtensions",code:t});throw p.setError(s).end(),s}}))}reset(){this._messageExtensionsMap.clear(),this._extensionsLatestSequenceMap.clear(),this._completedFetchExtensions.clear()}dispose(){this.reset();const{notificationCenter:e,InnerEvent:{MESSAGE_PUSH:t,LOGOUT:s},InnerEventSubType:{MESSAGE_EXTENSIONS_UPDATED:o}}=this._core;e.unSubscribeInnerEvent(t,o,this._handleMessageExtensionsNotify,this),e.subscribeInnerEvent(s,this.reset,this)}_handleModifyMessageExtensions(e,t){const{ID:s}=e,{Seq:o}=t,n=t.ExtensionList||[],i=[];let r=0,a=0,c=[];return n.forEach((e=>{const{ErrorCode:t,Extension:s}=e,{Key:o,Value:n,Seq:u}=s;i.push({code:t,key:o,value:n}),0===t?r++:a++,c.push({key:o,value:n,seq:u})})),this._extensionsLatestSequenceMap.set(s,o),c.length>0&&this._updateLocalExtensions(e.ID,c),{resultList:i,successCount:r,failureCount:a}}_updateLocalExtensions(e,t){this._messageExtensionsMap.has(e)||this._messageExtensionsMap.set(e,new Map);const s=this._messageExtensionsMap.get(e);null==t||t.forEach((e=>{const{key:t,seq:o,value:n=""}=e;null==s||s.set(t,{value:n,seq:o})}))}_fetchMessageExtensions(e,t){return h(this,void 0,void 0,(function*(){const{constants:{OuterConstant:s},utils:{isEmpty:o}}=this._core;try{let n;const{conversationType:i,ID:r}=e;if(i===s.CONV_C2C?n=yield function(e,t){const{common:{buildAndSendPacket:s}}=_n.core,{from:o,to:n,clientSequence:i,random:r,time:a}=e;return s({servcmd:"openim_msg_ext_http_svc.get_key_values",data:{From_Account:o,To_Account:n,MsgKey:`${i}_${r}_${a}`,StartSeq:t}})}(e,t):i===s.CONV_GROUP&&(n=yield function(e,t){const{common:{buildAndSendPacket:s}}=_n.core,{to:o,sequence:n}=e;return s({servcmd:"openim_msg_ext_http_svc.group_get_key_values",data:{GroupId:o,MsgSeq:n,StartSeq:t}})}(e,t)),n){const{LatestSeq:t,ClearSeq:s,CompleteFlag:i}=n,a=(n.ExtensionList||[]).map((e=>({key:e.Key,value:e.Value,seq:e.Seq})));if(this._updateLocalExtensions(r,a),this._clearLocationExtensions(r,s),this._extensionsLatestSequenceMap.set(r,t),1!==i){const t=a[a.length-1].seq+1;return this._fetchMessageExtensions(e,t)}const c=[];if(this._messageExtensionsMap.has(r)){const e=this._messageExtensionsMap.get(r);null==e||e.forEach(((e,t)=>{const{value:s}=e;o(s)||c.push({key:t,value:s})}))}return c}}catch(e){console.error(e)}}))}_clearLocationExtensions(e,t){if(!(t<=0)&&this._messageExtensionsMap.has(e)){const s=this._messageExtensionsMap.get(e);null==s||s.forEach(((e,o)=>{e.seq<=t&&s.delete(o)}))}}_generateServerExtensions(e,t){const{ID:s}=e;if(this._messageExtensionsMap.has(s)){const e=this._messageExtensionsMap.get(s);return t.map((t=>{var s;const{key:o,value:n}=t;let i=0;return(null==e?void 0:e.has(o))&&(i=null===(s=e.get(o))||void 0===s?void 0:s.seq),{Key:o,Value:n,Seq:i}}))}return t.map((e=>({Key:e.key,Value:e.value,Seq:0})))}_validateMessageExtensionBusinessCapability(e){const{helper:t,constants:s}=this._core;if(!t.checkBusinessCapabilityBits(In))throw new t.ChatError({functionName:e,code:s.ERROR_CODE.NO_USE,replacement1:e})}_handleMessageExtensionsNotify(e){const{SetKVInfo:t,DeleteKVInfo:s,ClearKVInfo:o,MsgOptType:n,TinyId:i,MsgLastSeq:r,ExtensionC2cMsgInfo:a,ExtensionGroupMsgInfo:c}=(null==e?void 0:e.MsgExtensionNotify)||{},u=a||c||{},{MsgClientTime:l,MsgRandom:d}=u,p=`${i}-${l}-${d}`;this._extensionsLatestSequenceMap.set(p,r),n===Nn?this._handleMessageExtensionsUpdated({messageID:p,updateMessageExtensionsInfo:t}):n===bn?this._handleMessageExtensionsDeleted({messageID:p,deleteMessageExtensionsInfo:s}):n===Gn&&this._handleMessageExtensionsCleared({messageID:p,clearMessageExtensionsInfo:o})}_handleMessageExtensionsUpdated(e){const{notificationCenter:t,OuterEvent:s}=this._core,{messageID:o,updateMessageExtensionsInfo:n=[]}=e,i=[];n.forEach((e=>{const{MsgKeyValue:t=[]}=e,s=t.map((e=>(i.push({key:e.Key,value:e.Value}),{key:e.Key,value:e.Value,seq:e.Seq})));this._updateLocalExtensions(o,s)})),t.emitOuterEvent(s.MESSAGE_EXTENSIONS_UPDATED,{name:s.MESSAGE_EXTENSIONS_UPDATED,data:{messageID:o,extensions:i}})}_handleMessageExtensionsDeleted(e){const{notificationCenter:t,OuterEvent:s}=this._core,{messageID:o,deleteMessageExtensionsInfo:n=[]}=e,i=[];n.forEach((e=>{const{MsgKeyValue:t=[]}=e,s=t.map((e=>(i.push(e.Key),{key:e.Key,seq:e.Seq})));this._updateLocalExtensions(o,s)})),t.emitOuterEvent(s.MESSAGE_EXTENSIONS_DELETED,{name:s.MESSAGE_EXTENSIONS_DELETED,data:{messageID:o,keyList:i}})}_handleMessageExtensionsCleared(e){const{notificationCenter:t,OuterEvent:{MESSAGE_EXTENSIONS_DELETED:s},utils:{isEmpty:o}}=this._core,{messageID:n,clearMessageExtensionsInfo:i=[]}=e,r=[];i.forEach((e=>{const{ClearMsgSeq:t}=e;if(this._messageExtensionsMap.has(n)){(this._messageExtensionsMap.get(n)||[]).forEach(((e,s)=>{e.seq<=t&&!o(e.value)&&r.push(s)}))}this._clearLocationExtensions(n,t)})),t.emitOuterEvent(s,{name:s,data:{messageID:n,keyList:r}})}};const Qn={key:"message",required:!0,rules:["object"],allowEmpty:!1,customValidator:e=>{const{constants:{OuterConstant:t}}=_n.core;return e.status!==t.MessageStatus.SUCCESS?"message is not success":!0===e.isSupportExtension||"message is not support extension"}},Xn={setMessageExtensions:[Qn,{key:"extensions",required:!0,rules:["array"],allowEmpty:!1}],getMessageExtensions:[Qn],deleteMessageExtensions:[Qn]},Zn=Object.assign(Object.assign(Object.assign({deleteMessage:[{required:!0,rules:["array"],allowEmpty:!1}],revokeMessage:[{required:!0,rules:["object"],allowEmpty:!1}],resendMessage:[{key:"message",required:!0,rules:["object"],allowEmpty:!1},{key:"options",required:!1,rules:["object"],allowEmpty:!1}],getMessageList:{conversationID:{required:!0,rules:["string"],allowEmpty:!1},nextReqMessageID:{required:!1,rules:["string"],allowEmpty:!0},count:{required:!1,rules:["number"],allowEmpty:!0}},getMessageListHopping:{conversationID:{required:!0,rules:["string"],allowEmpty:!1},sequence:{required:!1,rules:["number"],allowEmpty:!0},direction:{required:!1,rules:["number"],allowEmpty:!0},count:{required:!1,rules:["number"],allowEmpty:!0}},createTextAtMessage:{to:{required:!0,rules:["string"],allowEmpty:!1},conversationType:{required:!0,rules:["string"],allowEmpty:!1,customValidator:e=>"GROUP"===e||"conversationType should be GROUP."},payload:{required:!0,rules:["object"],allowEmpty:!1,customValidator:e=>{const t=function(e){var t;if("string"!=typeof(null==e?void 0:e.text)||"string"==typeof e.text&&0===(null===(t=null==e?void 0:e.text)||void 0===t?void 0:t.length))return"payload.text is invalid.";return!0}(e);return!0!==t?t:!((null==e?void 0:e.atUserList)&&!Array.isArray(e.atUserList))||"atUserList should be an array or undefind."}}},findMessage:[{required:!0,rules:["string"],allowEmpty:!1}],translateText:{sourceTextList:{required:!0,rules:["array"],allowEmpty:!1},sourceLanguage:{required:!0,rules:["string"],allowEmpty:!1},targetLanguage:{required:!0,rules:["string"],allowEmpty:!1}},createForwardMessage:{to:{required:!0,rules:["string"],allowEmpty:!1},conversationType:{required:!0,rules:["string"],allowEmpty:!1,customValidator:e=>!(!e.startsWith("C2C")&&!e.startsWith("GROUP"))||"conversationType is invalid."},payload:{required:!0,rules:["object"],allowEmpty:!1}},createLocationMessage:{to:{required:!0,rules:["string"],allowEmpty:!1},conversationType:{required:!0,rules:["string"],allowEmpty:!1},payload:{required:!0,rules:["object"],allowEmpty:!1,customValidator:e=>{const{utils:{isString:t,isNumber:s}}=_n.core;return t(null==e?void 0:e.description)?s(null==e?void 0:e.longitude)?!!s(null==e?void 0:e.latitude)||"payload.latitude must be a number.":"payload.longitude must be a number.":"payload.description must be a string."}}}},{addMessageReaction:[{key:"message",required:!0,rules:["object"],allowEmpty:!1},{key:"reactionID",required:!0,rules:["string"],allowEmpty:!1}],removeMessageReaction:[{key:"message",required:!0,rules:["object"],allowEmpty:!1},{key:"reactionID",required:!0,rules:["string"],allowEmpty:!1}],getMessageReactions:{messageList:{required:!0,rules:["array"],allowEmpty:!1},maxUserCountPerReaction:{required:!1,rules:["number"],allowEmpty:!0,customValidator:e=>"number"!=typeof e?"maxUserCountPerReaction is invalid.":!(e<0||e>10)||"maxUserCountPerReaction should between [0, 10]."}},getAllUserListOfMessageReaction:{message:{required:!0,rules:["object"],allowEmpty:!1,customValidator:e=>"success"===e.status||"message is invalid."},reactionID:{required:!0,rules:["string"],allowEmpty:!1},nextSeq:{required:!1,rules:["number"],allowEmpty:!0},count:{required:!1,rules:["number"],allowEmpty:!0}}}),{sendMessageReadReceipt:[{required:!0,rules:["array"],allowEmpty:!1}],getMessageReadReceiptList:[{required:!0,rules:["array"],allowEmpty:!1}],getGroupMessageReadMemberList:{message:{required:!0,rules:["object"],allowEmpty:!1},filter:{required:!1,rules:["number"],allowEmpty:!0},count:{required:!1,rules:["number"],allowEmpty:!0},cursor:{required:!1,rules:["string"],allowEmpty:!0}}}),Xn),ei=Object.assign(Object.assign(Object.assign({deleteMessage:!0,revokeMessage:!0,resendMessage:!0,getMessageList:!0,getMessageListHopping:!0,createTextAtMessage:!0,findMessage:!0,translateText:!0,createForwardMessage:!0,createLocationMessage:!0},{addMessageReaction:!0,removeMessageReaction:!0,getMessageReactions:!0,getAllUserListOfMessageReaction:!0}),{sendMessageReadReceipt:!0,getMessageReadReceiptList:!0,getGroupMessageReadMemberList:!0}),{setMessageExtensions:!0,getMessageExtensions:!0,deleteMessageExtensions:!0});class ti{constructor(e){this._core=e}deleteMessage(e){return h(this,void 0,void 0,(function*(){const{to:t,messageIdentifiers:s}=e,o={From_Account:this._core.common.getCurrentUserID(),To_Account:t,MsgKeyList:s};return this._core.common.buildAndSendPacket({servcmd:"openim.delete_c2c_msg_ramble",data:o})}))}revokeMessage(e){return h(this,void 0,void 0,(function*(){const{to:t,from:s,sequence:o,time:n,random:i}=e,r={MsgInfo:{From_Account:s,To_Account:t,MsgSeq:o,MsgRandom:i,MsgTimeStamp:n}};return this._core.common.buildAndSendPacket({servcmd:"openim.msgwithdraw",data:r})}))}}class si{constructor(e){this._core=e}deleteMessage(e){return h(this,void 0,void 0,(function*(){const{to:t,messageIdentifiers:s}=e,o={GroupId:t,Deleter_Account:this._core.common.getCurrentUserID(),Seqs:s};return this._core.common.buildAndSendPacket({servcmd:"group_open_http_svc.delete_group_ramble_msg_by_seq",data:o})}))}revokeMessage(e){return h(this,void 0,void 0,(function*(){const{to:t,sequence:s}=e,o={GroupId:t,MsgSeqList:[{MsgSeq:s}]};return this._core.common.buildAndSendPacket({servcmd:"group_open_http_svc.group_msg_recall",data:o})}))}}class oi{constructor(e){this._core=e}generateRevokeMessage(e){const{conversationID:t,sequence:s,random:o,tinyID:n,clientTime:i,revokeReason:r,revoker:a}=e;let c={};const{messageDataHandler:u}=this._core.message;return c=u.revokeMessage({conversationID:t,sequence:s,random:o,revoker:a}),c||(c={conversationID:t,sequence:s},n&&i&&o&&(c.ID=`${n}-${i}-${o}`)),c=Object.assign(Object.assign({},c),{revoker:a,revokeReason:r,revokerInfo:{userID:a,nick:"",avatar:""}}),c}updateRevokerInfo(e){return h(this,void 0,void 0,(function*(){const t=e.map((e=>e.revoker));try{const s=yield this._fetchUserInfos(t);s&&e.forEach((e=>{const{revoker:t}=e;s[t]&&(e.revokerInfo.nick=s[t].nick||"",e.revokerInfo.avatar=s[t].avatar||"",e.revokerInfo.userID=t)}))}catch(e){console.debug(e)}}))}_fetchUserInfos(e){return h(this,void 0,void 0,(function*(){var t,s;const o=yield null===(t=this._core.user.userProfile)||void 0===t?void 0:t.getUserProfile({userIDList:e});return(null==o?void 0:o.data)?null===(s=o.data)||void 0===s?void 0:s.reduce(((e,{userID:t,nick:s,avatar:o})=>(e[t]={nick:s||"",avatar:o||""},e)),{}):null}))}}var ni=new class{constructor(){this._core=null,this._c2cMessageAction=null,this._groupMessageAction=null}init(e){this._core=e,this._groupMessageAction=new si(e),this._c2cMessageAction=new ti(e),this._messageHelper=new oi(e);const{helper:t}=e;t.registerApi({apiName:"deleteMessage",context:this}),t.registerApi({apiName:"revokeMessage",context:this}),t.registerApi({apiName:"resendMessage",context:this}),t.registerApi({apiName:"findMessage",context:this})}deleteMessage(e){return h(this,void 0,void 0,(function*(){let t=[],s=[];const{conversationID:o,conversationType:n}=e[0],i=o.replace(n,"");if("@TIM#SYSTEM"===n)throw new this._core.helper.ChatError({code:Un});if(e.forEach((e=>{const{conversationID:i,conversationType:r,status:a,_onlineOnlyFlag:c,sequence:u,random:l,time:d}=e||{};if("success"===a&&i===o&&r===n){if(!c){const e="C2C"===r?`${u}_${l}_${d}`:String(u);t.push(e)}s.push(e)}})),0===t.length)return this._handleDeleteMessageSuccess(s),{code:0,data:{messageList:s}};t.length>30&&(t=t.slice(0,30),s=s.slice(0,30));try{return"C2C"===n?yield this._c2cMessageAction.deleteMessage({to:i,messageIdentifiers:t}):yield this._groupMessageAction.deleteMessage({to:i,messageIdentifiers:t}),this._handleDeleteMessageSuccess(s),{code:0,data:{messageList:s}}}catch(e){const{errorCode:t}=e;throw new this._core.helper.ChatError({functionName:"deleteMessage",code:t})}}))}revokeMessage(e){return h(this,void 0,void 0,(function*(){var t;const s=this._core.ssoLog.createSSOLogData({method:"revokeMessage"}),{conversationType:o,isRevoked:n}=e;let i=null;if("@TIM#SYSTEM"===o)throw new this._core.helper.ChatError({message:"system message cannot be revoked"});if(n)throw new this._core.helper.ChatError({message:"message has been revoked"});s.setLogInfo({message:`type:${e.type} from:${e.from} to:${e.to}`});try{if(i="C2C"===o?yield this._c2cMessageAction.revokeMessage(e):yield this._groupMessageAction.revokeMessage(e),i){const{RecallRetList:o}=i,n=(null===(t=null==o?void 0:o[0])||void 0===t?void 0:t.RetCode)||0;if(0!==n)throw new this._core.helper.ChatError({code:n});return s.end(),yield this._handleRevokeMessageSuccess(e),{code:0,data:{message:e}}}}catch(e){const{errorCode:t}=e,s=new this._core.helper.ChatError({functionName:"revokeMessage",code:t});throw this._core.ssoLog.getSSOLogData("revokeMessage").setError(s).end(),s}}))}resendMessage(e,t){return h(this,void 0,void 0,(function*(){var s,o;return e.isResend=!0,e.status="unSend",null===(o=null===(s=this._core)||void 0===s?void 0:s.apiMap)||void 0===o?void 0:o.sendMessage(e,t)}))}findMessage(e){return this._core.message.messageDataHandler.findMessage(e)}_handleDeleteMessageSuccess(e){if(0===e.length)return;const{message:{messageDataHandler:t},common:{isTopic:s},notificationCenter:o,InnerEvent:n}=this._core;e.forEach((e=>{e.isDeleted=!0;const s=t.getLocalMessageList(e.conversationID);null==s||s.forEach((t=>{t.ID===e.ID&&(t.isDeleted=!0)}))}));const{conversationID:i=""}=e[0];s(i)?o.emitInnerEvent(n.TOPIC_MESSAGE_DELETED,i):o.emitInnerEvent(n.MESSAGE_DELETED,i)}_handleRevokeMessageSuccess(e){return h(this,void 0,void 0,(function*(){var t;const s=null===(t=this._core.store.get("login"))||void 0===t?void 0:t.userId,{conversationID:o,sequence:n,random:i}=e;this._core.message.messageDataHandler.revokeMessage({conversationID:o,sequence:n,random:i,revoker:s}),yield this._messageHelper.updateRevokerInfo([e])}))}};class ii{static parseServerPushElement(e){const{MsgContent:t={}}=e,{Index:s,Data:o}=t;return new ii({index:s,data:o})}constructor(e){this.type=mn.MSG_FACE;const{index:t,data:s}=e;this.content={index:t,data:s}}validateBeforeSend(){var e,t;return"number"==typeof(null===(e=this.content)||void 0===e?void 0:e.index)&&"string"==typeof(null===(t=this.content)||void 0===t?void 0:t.data)?{isValid:!0}:{isValid:!1,error:{message:"content is invalid"}}}transformToServerFormat(e){const{isMergerMessage:t=!1}=e||{},s=t?this.payload:this.content,{index:o,data:n}=s;return{MsgType:this.type,MsgContent:{Index:o,Data:n}}}}class ri{static parseServerPushElement(e){const{MsgContent:t={}}=e,{Desc:s,Longitude:o,Latitude:n}=t;return new ri({description:s,longitude:o,latitude:n})}constructor(e){this.type=mn.MSG_LOCATION;const{description:t,longitude:s,latitude:o}=e;this.content={description:t,longitude:s,latitude:o}}validateBeforeSend(){return{isValid:!0}}transformToServerFormat(e){const{isMergerMessage:t=!1}=e||{},s=t?this.payload:this.content,{description:o,longitude:n,latitude:i}=s;return{MsgType:this.type,MsgContent:{Desc:o,Longitude:n,Latitude:i}}}}var ai=new class{init(e){this._core=e,e.message.messageFactory.registerElementClass(mn.MSG_FACE,ii),e.message.messageFactory.registerElementClass(mn.MSG_LOCATION,ri),e.helper.registerApi({apiName:"createFaceMessage",context:this}),e.helper.registerApi({apiName:"createTextAtMessage",context:this}),e.helper.registerApi({apiName:"createForwardMessage",context:this}),e.helper.registerApi({apiName:"createLocationMessage",context:this})}createFaceMessage(e){if(!e)return null;const{index:t,data:s}=(null==e?void 0:e.payload)||{},o=new ii({index:t,data:s}),n=this._core.common.getCurrentUserID(),i=this._core.message.messageFactory.createMessage(Object.assign(Object.assign({},e),{from:n}));return i.setElement(o),i}createTextAtMessage(e){const{atUserList:t}=(null==e?void 0:e.payload)||{},s=this._core.apiMap.createTextMessage(e),{OuterConstant:o}=this._core;if(!s)return null;if(Array.isArray(t)){const e=[],n=[];t.forEach((t=>{t!==o.MSG_AT_ALL?(e.push({GroupAtAllFlag:Sn,GroupAt_Account:t}),n.push(t)):(e.push({GroupAtAllFlag:En}),n.push(o.MSG_AT_ALL))})),s._groupAtInfoList=e,s.atUserList=n}return s}createForwardMessage(e){const{helper:t,OuterConstant:s}=this._core,{to:o,conversationType:n,priority:i,payload:r,needReadReceipt:a,receiverList:c,cloudCustomData:u="",isSupportExtension:l=!1}=e;if(!Array.isArray(r._elements))throw new t.ChatError({functionName:"createForwardMessage",code:2454});if(r.type===s.MSG_GRP_TIP)throw new t.ChatError({functionName:"createForwardMessage",code:2453});const d=this._core.common.getCurrentUserID(),p=this._core.message.messageFactory.createMessage({to:o,from:d,conversationType:n,isPlaceMessage:0,priority:i,payload:r,needReadReceipt:a,isSupportExtension:l,cloudCustomData:u,receiverList:c});return p.setRelayFlag(!0),p.setElement(r._elements[0]),p}createLocationMessage(e){if(!e)return null;const{description:t,longitude:s,latitude:o}=(null==e?void 0:e.payload)||{},n=new ri({description:t,longitude:s,latitude:o}),i=this._core.common.getCurrentUserID(),r=this._core.message.messageFactory.createMessage(Object.assign(Object.assign({},e),{from:i}));return r.setElement(n),r}};let ci=class{init(e){this._messageHelper=new oi(e),this._core=e;const{notificationCenter:t,InnerEvent:{MESSAGE_PUSH:s},InnerEventSubType:{C2C_REVOKED_MESSAGE:o},helper:{registerWorkflowStep:n},constants:{WORKFLOW_NAME:i,WORKFLOW_STEP:r}}=e;t.subscribeInnerEvent(s,o,this._handleC2CNotifyMessage,this),n(i.SYNC_SERVER_INFO_AFTER_RE_ONLINE,r.HANDLE_C2C_REVOKED_MESSAGE_FROM_SYNC_UNREAD,this._handleC2CRevokeMessagesFromUnreadMessageSync,this)}_handleC2CNotifyMessage(e){const{C2cNotifyMsgArray:t}=e;null==t||t.forEach((e=>{Object.keys(e).includes("WithdrawC2cMsgNotify")&&this._handleC2CRevokeMessage(e)}))}_handleC2CRevokeMessage(e){return h(this,void 0,void 0,(function*(){try{const{WithdrawC2cMsgNotify:{C2cWithdrawInfoArray:t}}=e;yield this._parseAndEmitC2CRevokedMessages(t)}catch(e){console.debug(e)}}))}_parseAndEmitC2CRevokedMessages(e){return h(this,void 0,void 0,(function*(){const t=[],{notificationCenter:s,OuterEvent:o,common:{getCurrentUserID:n}}=this._core;e.forEach((e=>{const{MsgRand:s,MsgSeq:o,To_Account:i,From_Account:r,RevokerInfo:{Revoker_Account:a,Revoke_Reason:c,Reason:u=c}}=e,l=n()===r?`C2C${i}`:`C2C${r}`,d=this._messageHelper.generateRevokeMessage({conversationID:l,sequence:o,random:s,revoker:a,revokeReason:u});t.push(d)})),t.length>0&&(yield this._messageHelper.updateRevokerInfo(t),s.emitOuterEvent(o.MESSAGE_REVOKED,{name:o.MESSAGE_REVOKED,data:t}))}))}_handleC2CRevokeMessagesFromUnreadMessageSync(e){return h(this,void 0,void 0,(function*(){const{revokedMessageList:t}=e.result;yield this._parseAndEmitC2CRevokedMessages(t)}))}dispose(){const{notificationCenter:e,InnerEvent:{MESSAGE_PUSH:t},InnerEventSubType:{C2C_REVOKED_MESSAGE:s}}=this._core;e.unSubscribeInnerEvent(t,s,this._handleC2CNotifyMessage,this)}},ui=class{init(e){this._messageHelper=new oi(e),this._core=e;const{notificationCenter:t,InnerEvent:{MESSAGE_PUSH:s},InnerEventSubType:{GROUP_MESSAGE_REVOKED:o}}=e;t.subscribeInnerEvent(s,o,this._handleGroupNotifyMessage,this)}_handleGroupNotifyMessage(e){const{GroupTips:t}=e;null==t||t.forEach((e=>{var t;Array.isArray(null===(t=null==e?void 0:e.MsgBody)||void 0===t?void 0:t.GroupWithdrawInfoArray)&&this._handleGroupRevokeMessage(e)}))}_handleGroupRevokeMessage(e){return h(this,void 0,void 0,(function*(){try{const{RevokerInfo:t,MsgBody:{GroupWithdrawInfoArray:s},GroupInfo:o}=e,n=[],i=[],{notificationCenter:r,OuterEvent:a,utils:{isEmpty:c},common:{isCommunity:u}}=this._core;let l=!1;o&&(l=u({groupID:o.GroupId})||!c(o.TopicId)),s.forEach((e=>{const{Random:s,MsgSeq:r,GroupId:a,MsgClientTime:c,TinyId:u,TopicId:d,RevokerInfo:{Revoker_Account:p=(null==t?void 0:t.Revoker_Account)||"",Reason:h=(null==t?void 0:t.Reason)||""}}=e,g=d?`GROUP${d}`:`GROUP${a}`,_=this._messageHelper.generateRevokeMessage({conversationID:g,sequence:r,random:s,tinyID:u,clientTime:c,revoker:p,revokeReason:h});l?(_.revokerInfo.nick=o.From_AccountNick,_.revokerInfo.avatar=o.From_AccountHeadurl,n.push(_)):i.push(_)})),i.length>0&&(yield this._messageHelper.updateRevokerInfo(i),n.push(...i)),0!==n.length&&r.emitOuterEvent(a.MESSAGE_REVOKED,{name:a.MESSAGE_REVOKED,data:n})}catch(e){console.debug(e)}}))}dispose(){const{notificationCenter:e,InnerEvent:{MESSAGE_PUSH:t},InnerEventSubType:{GROUP_MESSAGE_REVOKED:s}}=this._core;e.unSubscribeInnerEvent(t,s,this._handleGroupNotifyMessage,this)}};var li=new class{constructor(){this._c2cMessageReceiver=new ci,this._groupMessageReceiver=new ui}init(e){this._c2cMessageReceiver.init(e),this._groupMessageReceiver.init(e)}dispose(){this._c2cMessageReceiver.dispose(),this._groupMessageReceiver.dispose()}};class di{constructor(e){this._core=e;const{constants:t}=e;this._messageHelper=new oi(e),e.helper.registerWorkflowStep(t.WORKFLOW_NAME.SYNC_SERVER_INFO_AFTER_RE_ONLINE,t.WORKFLOW_STEP.GROUP_REVOKED_NOTICE_RECOVER,this._recoverGroupRevokeNotice,this)}getRoamingMessagesByAnchor(e){return this._core.message.messageHistory.getGroupRoamingMessagesByAnchor(e)}_recoverGroupRevokeNotice(e){const{recoverRevokeNoticeGroupIDList:t=[]}=e.result,s=this._filterValidGroupIDList(t);if(0===s.length)return;const o=Math.min(Math.ceil(s.length/10),5);Promise.all(Array.from({length:o},((e,t)=>{const o=10*t,n=Math.min(o+10,s.length);return this._fetchGroupRevokeNotice(s.slice(o,n))}))).catch((e=>console.error(e)))}_fetchGroupRevokeNotice(e){return h(this,void 0,void 0,(function*(){var t;try{const s=yield function(e){return h(this,void 0,void 0,(function*(){const{appStore:t,constants:{OuterConstant:s},common:o}=_n.core,n=t.groupStore.getGroupMap(),i={NotifyReqList:e.map((e=>{const t=n.get(e);return{NotifyType:1,Limit:20,Type:o.isCommunity({type:t.type,groupID:e})?s.GRP_COMMUNITY:void 0,GroupId:e,BeginTime:(null==t?void 0:t._lastRevokedTime)||0,EndTime:1e3*_n.core.common.timeManager.getServerTimeMs()}}))||[]};return o.buildAndSendPacket({servcmd:"group_open_http_svc.batch_get_group_notify",data:i})}))}(e);if(s){const e=[];null===(t=null==s?void 0:s.NotifyRspList)||void 0===t||t.forEach((t=>{const{GroupId:s,NotifyMsgList:o}=t,n=this._parseServerRevokeMessageList({groupID:s,serverRevokeMessageList:o});e.push(...n)})),0!==e.length&&(yield this._emitMessageRevokedEvent(e))}}catch(e){console.error(e)}}))}_parseServerRevokeMessageList(e){const{serverRevokeMessageList:t,groupID:s}=e,o=[];return null==t||t.forEach((e=>{const{ClientTime:t,MsgSeq:n,Random:i,RevokerInfo:{Revoker_Account:r="",Reason:a=""}}=e,c=`GROUP${s}`,u=this._messageHelper.generateRevokeMessage({conversationID:c,sequence:n,random:i,clientTime:t,revoker:r,revokeReason:a});o.push(u)})),o}_filterValidGroupIDList(e){const{constants:{OuterConstant:t}}=this._core,s=this._core.appStore.groupStore.getGroupMap();return(null==e?void 0:e.filter((e=>{if(!s.has(e))return!1;const o=s.get(e);return(null==o?void 0:o.type)!==t.GRP_AVCHATROOM&&!(null==o?void 0:o.isSupportTopic)})))||[]}_emitMessageRevokedEvent(e){return h(this,void 0,void 0,(function*(){const{notificationCenter:t,OuterEvent:s}=this._core;yield this._messageHelper.updateRevokerInfo(e),t.emitOuterEvent(s.MESSAGE_REVOKED,{name:s.MESSAGE_REVOKED,data:e})}))}}class pi{constructor(e){this._historyMessageListFetchAnchors=new Map,this._core=e,this._messageHelper=new oi(e)}getRoamingMessagesByAnchor(e){return h(this,void 0,void 0,(function*(){var t;try{const{conversationID:s,count:o,messageID:n,time:i,direction:r}=e;let a=i,c="";if(!i){const e=n?this._core.message.messageDataHandler.findMessage(n):null;if(a=(null==e?void 0:e.time)||0,n&&this._historyMessageListFetchAnchors.has(s)){const e=this._historyMessageListFetchAnchors.get(s);a=e.lastMessageTime,c=e.messageKey}}const u=s.replace(Fn,""),l=yield function(e){return h(this,void 0,void 0,(function*(){const{peerAccount:t,count:s,lastMessageTime:o,messageKey:n,direction:i}=e,r={Peer_Account:t,MaxCnt:s,WithRecalledMsg:1,LastMsgTime:o,MsgKey:n,GetDirection:i};return _n.core.common.buildAndSendPacket({servcmd:"openim.getroammsg",data:r})}))}({count:o,lastMessageTime:a,messageKey:c,peerAccount:u,direction:r});if(l){const{MsgList:e=[],Complete:o,MsgKey:n,LastMsgTime:i}=l;this._historyMessageListFetchAnchors.set(s,{messageKey:n,lastMessageTime:i});const r=[];for(let t=0;t<e.length;t++){const s=e[t],o=this._parseMessage(s);r.push(o)}const a=this._core.message.messageHelper.filterValidMessages(r);return{messageList:a,nextReqMessageIDFromServer:null===(t=a[0])||void 0===t?void 0:t.ID,lastMessageTime:i,hasNoMoreHistoryMessage:1===o}}}catch(e){throw new this._core.helper.ChatError({code:null==e?void 0:e.code})}}))}clearHistoryMessageListFetchAnchors(e){this._historyMessageListFetchAnchors.delete(e)}reset(){this._historyMessageListFetchAnchors.clear()}_parseMessage(e){const t=Fn,s=this._core.message.messageHelper.parseServerPushMessage(e),o=this._core.message.messageFactory.createMessage(Object.assign(Object.assign({},s),{conversationType:t,flow:"in"}));return o.setElement(s.elements),o}}var hi=new class{constructor(){this._clearedConversations=new Set,this._fetchedCompleteConversations=new Set}init(e){this._core=e,this._groupMessageHistory=new di(e),this._c2cMessageHistory=new pi(e),this._messageHelper=new oi(e),e.helper.registerApi({apiName:"getMessageList",context:this}),e.helper.registerApi({apiName:"getMessageListHopping",context:this}),e.helper.registerApi({apiName:"clearHistoryMessage",context:this})}getMessageList(e){return h(this,void 0,void 0,(function*(){try{let{conversationID:t,nextReqMessageID:s}=e;const o=qn;if("@TIM#SYSTEM"===t)return{code:0,data:{messageList:[],isCompleted:!1,nextMessageSeq:""}};const n=this._core.ssoLog.createSSOLogData({method:"getMessageList"}),i=this._getAvailableLocalMessagesCount({conversationID:t,nextReqMessageID:s});if(this._needFetchHistoryMessageList({conversationID:t,availableLocalMessagesCount:i,targetCount:o})){let e=null;if(t.startsWith($n)?e=yield this._groupMessageHistory.getRoamingMessagesByAnchor({conversationID:t,sequence:Number(s),count:o,direction:vn.FORWARD}):t.startsWith(Fn)&&(e=yield this._c2cMessageHistory.getRoamingMessagesByAnchor({conversationID:t,messageID:s,count:o,direction:vn.FORWARD})),e){const{nextReqMessageIDFromServer:o,hasNoMoreHistoryMessage:r,messageList:a}=e,c=this._core.message.messageDataHandler.prependLocalMessageList({messageList:a,conversationID:t});!function(e){const{appStore:t,message:s,OuterConstant:o}=_n.core,n=t.conversationStore.getConversation(e),i=s.messageDataHandler.getLocalMessageList(e);if(!n||0===i.length||e===o.CONV_SYSTEM)return;const r=[];for(let e=0;e<i.length;e++)"in"!==i[e].flow?"out"!==i[e].flow||i[e].isRead||i[e].setIsRead(!0):r.push(i[e]);let a=0;if(n.type===o.CONV_C2C){const e=r.slice(-n.unreadCount).filter((e=>e.isRevoked)).length;a=r.length-n.unreadCount-e}else a=r.length-n.unreadCount;for(let e=0;e<a&&!r[e].isRead;e++)r[e].setIsRead(!0)}(t),yield Vn(t),t.startsWith(Fn)&&(yield xn({messageList:a,conversationID:t}));const u=this._core.message.messageDataHandler.getLocalMessageList(t).slice(0,c.length+i),l=u.filter((e=>e.isRevoked));yield this._messageHelper.updateRevokerInfo(l),r&&this._fetchedCompleteConversations.add(t);const d={nextReqMessageID:r?"":String(o),messageList:u,isCompleted:r},p=u.map((e=>e.sequence));return n.setLogInfo({message:`conversationID: ${t} nextReqMessageID: ${s} \n availableLocalMessagesCount: ${i} sequenceList: ${JSON.stringify(p)} `}).end(),{code:0,data:d}}return{code:0,data:{messageList:[],isCompleted:!1,nextReqMessageID:""}}}n.setLogInfo({message:`conversationID: ${t} nextReqMessageID: ${s} availableLocalMessagesCount: ${i}}`}).end();return{code:0,data:yield this._getMessageListFromMemory({conversationID:t,nextReqMessageID:s,count:o})}}catch(e){const t=new this._core.helper.ChatError({code:null==e?void 0:e.code});this._core.ssoLog.getSSOLogData("getMessageList").setError(t).end(),console.debug(t)}}))}getMessageListHopping(e){return h(this,void 0,void 0,(function*(){var t,s;const{conversationID:o,sequence:n,time:i,direction:r=vn.FORWARD}=e,{isEmpty:a}=this._core.helper;if(![vn.BACKWARD,vn.FORWARD].includes(r))throw new this._core.helper.ChatError({message:"direction must be 0 or 1"});let{count:c=qn}=e;c=c>qn?qn:c;let u=null;if(o.startsWith($n)){if(u=yield this._groupMessageHistory.getRoamingMessagesByAnchor({conversationID:o,sequence:n,count:c,direction:r}),u){const{nextReqMessageIDFromServer:e,hasNoMoreHistoryMessage:o,messageList:i,invisibleSequenceList:c}=u;if(this._core.message.messageDataHandler.storeSparseMessageList(i),r===vn.FORWARD){const t=o&&e<1;return{code:0,data:{messageList:i,isCompleted:t,nextMessageSeq:t?"":e}}}if(r===vn.BACKWARD){if(a(i)&&a(c))return{code:0,data:{messageList:[],isCompleted:!0,nextMessageSeq:""}};const e=(null===(t=null==i?void 0:i[i.length-1])||void 0===t?void 0:t.sequence)||0,r=(null===(s=null==c?void 0:c[c.length-1])||void 0===s?void 0:s.sequence)||0;return{code:0,data:{messageList:i.filter((e=>e.sequence>=n)),isCompleted:!o,nextMessageSeq:o?Math.max(e,r)+1:""}}}return{code:0,data:u}}}else if(o.startsWith(Fn)&&(u=yield this._c2cMessageHistory.getRoamingMessagesByAnchor({conversationID:o,count:c+1,time:i,direction:r}),u)){const{messageList:e,lastMessageTime:t,hasNoMoreHistoryMessage:s}=u;return s||(r===vn.FORWARD?e.shift():e.pop()),this._core.message.messageDataHandler.storeSparseMessageList(e),{code:0,data:{messageList:e,isCompleted:s,nextMessageTime:s?"":t}}}}))}clearHistoryMessage(e){return h(this,void 0,void 0,(function*(){var t;const{appStore:s,common:{ChatError:o,getCurrentUserID:n},OuterConstant:{CONV_C2C:i,CONV_GROUP:r},message:a,apiMap:c,ssoLog:u}=this._core,l=s.conversationStore.getConversation(e);if(!l)throw new o({code:kn});const d=u.createSSOLogData({method:"clearHistoryMessage"});d.setLogInfo({message:`convID:${e}`});const p={fromAccount:n()},{type:g}=l;g===i?(p.type=wn,p.toAccount=e.replace(i,"")):g===r&&(p.type=Pn,p.toGroupID=e.replace(r,""));try{yield null===(t=null==c?void 0:c.setMessageRead)||void 0===t?void 0:t.call(c,{conversationID:e});const s=yield function(e){return h(this,void 0,void 0,(function*(){const{fromAccount:t,type:s,toAccount:o,toGroupID:n}=e,i={From_Account:t,Type:s,To_Account:o,ToGroupid:n};return _n.core.common.buildAndSendPacket({servcmd:"recentcontact.clear_msg",data:i})}))}(p);return s&&(d.end(),a.messageDataHandler.deleteConversationMessageList(e),this._clearedConversations.add(e),this._fetchedCompleteConversations.delete(e),this._c2cMessageHistory.clearHistoryMessageListFetchAnchors(e),this._updateConversationLastMessage(e)),{code:0,data:{conversationID:e}}}catch(e){const{errorCode:t}=e,s=new this._core.helper.ChatError({functionName:"clearHistoryMessage",code:t});throw d.setError(s).end(),s}}))}_updateConversationLastMessage(e){const{appStore:t}=this._core;t.conversationStore.updateConversation(e,{lastMessage:this._generateLastMessage()},{needSort:!0})}_getAvailableLocalMessagesCount({conversationID:e,nextReqMessageID:t}){const s=this._core.message.messageDataHandler.getLocalMessageList(e),{length:o}=s;if(!t)return o;let n=-1;return(null==e?void 0:e.startsWith(Fn))?n=s.findIndex((e=>e.ID===t)):(null==e?void 0:e.startsWith($n))&&(n=s.findIndex((e=>t.includes("-")?e.ID===t:String(e.sequence)===t))),-1===n?0:n}_needFetchHistoryMessageList({conversationID:e,availableLocalMessagesCount:t,targetCount:s}){return!!this._clearedConversations.has(e)||t<s&&!this._fetchedCompleteConversations.has(e)}_getMessageListFromMemory(e){return h(this,arguments,void 0,(function*({conversationID:e,nextReqMessageID:t,count:s}){const o=this._core.message.messageDataHandler.getLocalMessageList(e),n=o.length;let i=n,r={isCompleted:!1,nextReqMessageID:"",messageList:[]},a=0,c=n;return t?t&&(c=o.findIndex((s=>e.startsWith(Fn)?s.ID===t:String(s.sequence)===t)),a=c>s?c-s:0,i=c):a=n>s?n-s:0,r.nextReqMessageID=0===a?"":this._generateNextReqMessageID({conversationID:e,targetIndex:a}),r.messageList=o.slice(a,c),r.isCompleted=i<=s,e.startsWith(Fn)&&(yield Vn(e),yield xn({messageList:r.messageList,conversationID:e})),r}))}_generateNextReqMessageID({conversationID:e,targetIndex:t}){const s=this._core.message.messageDataHandler.getLocalMessageList(e);return e.startsWith("C2C")?s[t].ID:String(s[t].sequence)}_generateLastMessage(){return{lastTime:0,lastSequence:0,fromAccount:"",messageForShow:"",payload:null,type:"",isRevoked:!1,cloudCustomData:"",onlineOnlyFlag:!1,nick:"",nameCard:"",version:0,isPeerRead:!1,revoker:null}}reset(){this._clearedConversations.clear(),this._fetchedCompleteConversations.clear(),this._c2cMessageHistory.reset()}dispose(){this.reset()}};var gi=new class{constructor(){this._core=null}init(e){this._core=e;const{helper:t}=e;t.registerApi({apiName:"translateText",context:this})}translateText(e){return h(this,void 0,void 0,(function*(){try{const{sourceLanguage:t,sourceTextList:s,targetLanguage:o}=e,n=yield function(e,t){return h(this,void 0,void 0,(function*(){var s,o;const{sourceTextList:n,sourceLanguage:i,targetLanguage:r}=e,{store:a,common:c}=t,u={SourceText:n,Source:i,Target:r,FromAccount:null===(s=a.get("login"))||void 0===s?void 0:s.tinyID,SDKAppID:null===(o=a.get("instance"))||void 0===o?void 0:o.sdkAppId},l=yield c.buildAndSendPacket({servcmd:"im_open_translate.ws_batch_trans_text",data:u});if(l){const{CmdErrorCode:e,TargetText:t}=l;return{cmdErrorCode:e,translatedTextList:t}}}))}({sourceLanguage:t,sourceTextList:s,targetLanguage:o},this._core);if(n){const{cmdErrorCode:{ErrorCode:e,ErrorInfo:t},translatedTextList:s}=n;if(0===e)return{code:0,data:{translatedTextList:s}};throw{errorCode:e,errorInfo:t,message:t}}}catch(e){const{errorCode:t,errorInfo:s}=e||{};throw new this._core.helper.ChatError({functionName:"translateText",code:t,message:s})}}))}};var _i=new class{init(e){this._core=e,e.helper.registerApi({apiName:"convertVoiceToText",context:this})}convertVoiceToText(e){return h(this,void 0,void 0,(function*(){var t,s;const{message:o,language:n=Cn.ZH_PY}=e;let{url:i}=o.payload||{};const r=null===(t=this._core.store.get("login"))||void 0===t?void 0:t.userID;o.from===r&&"out"===o.flow&&(i=o.payload.remoteAudioUrl),this._validateVoiceFormat(i);const a=(null===(s=Rn.exec(i))||void 0===s?void 0:s[1])||"mp3",c=Dn[n]||On;try{const e=yield function(e){var t;const{store:s,common:o}=_n.core,{url:n,format:i,serverLanguageType:r}=e,a={BytesUrl:n,BytesEngServiceType:r,BytesVoiceFormat:i,Uint32Sdkappid:null===(t=s.get("instance"))||void 0===t?void 0:t.sdkAppId,Uint64SourceType:0};return o.buildAndSendPacket({servcmd:"im_open_speech.ws_sentence_recognition",data:a})}({url:i,format:a,serverLanguageType:c});if(e){const{CmdErrorCode:t,BytesResult:s}=e;if(0===t.ErrorCode)return{code:0,data:{result:s}};throw{code:t.ErrorCode,message:t.ErrorInfo}}}catch(e){const{code:t,message:s}=e||{},o=new this._core.common.ChatError({functionName:"convertVoiceToText",code:t,message:s});console.error(o),this._core.ssoLog.createSSOLogData({method:"convertVoiceToText"}).setError(o).end()}}))}_validateVoiceFormat(e){if(!Rn.test(e))throw new this._core.common.ChatError({code:2119})}};class mi{constructor(e){const{constants:t,common:s,utils:o}=_n.core,{CONV_C2C:n,CONV_GROUP:i}=t.OuterConstant,{ID:r,tinyID:a,from:c,to:u,clientTime:l=s.timeManager.getServerTimeSeconds()||0,random:d,sequence:p,cloudCustomData:h="",nick:g="",avatar:_="",clientSequence:m,conversationType:v,groupID:f,_elements:I,time:S}=e;this.ID=r||`${a}-${l}-${d}`,this.messageRandom=d,this.from=c,this.messageSender=c,this.time=S,this.messageSequence=p,this.clientSequence=m||p,this.clientTime=l,this.cloudCustomData=h,this.messageReceiver=u,this.avatar=_,this.nick=g;const E=o.deepCopyWithMethods(I);E.forEach((e=>{e.payload=e.content,delete e.content})),this.messageBody=E,r?v.startsWith(n)?this.receiverUserID=u:v.startsWith(i)&&(this.receiverGroupID=u):f?(this.receiverGroupID=f,this.messageReceiver=f):u&&(this.receiverUserID=u,this.messageReceiver=u)}transformElementsToServerFormat(){return this.messageBody?Array.isArray(this.messageBody)?this.messageBody.map((e=>e.transformToServerFormat({isMergerMessage:!0}))):this.messageBody.transformToServerFormat({isMergerMessage:!0}):null}}class vi{static parseServerPushElement(e){const{MsgContent:t}=e,{MsgList:s=[],CompatibleText:o,AbstractList:n,Title:i,PbMsgKey:r,JsonMsgKey:a}=t||{},c=s.map((e=>Kn(e)));return new vi({messageList:c,title:i,abstractList:n,compatibleText:o,pbDownloadKey:r,downloadKey:a})}constructor(e){this.type=_n.core.constants.OuterConstant.MSG_MERGER;const{messageList:t,title:s,abstractList:o,compatibleText:n,pbDownloadKey:i="",downloadKey:r="",version:a=0,layersOverLimit:c=!1}=e,u=[];t.forEach((e=>{if(e){const t=new mi(e);u.push(t)}})),this.content={messageList:u,title:s,abstractList:o,compatibleText:n,version:a,downloadKey:r,pbDownloadKey:i,layersOverLimit:c}}validateBeforeSend(){const{isEmpty:e}=_n.core.helper;return e(this.content.messageList)?{isValid:!1,error:{message:"content is invalid"}}:{isValid:!0}}transformToServerFormat(e){const{isMergerMessage:t=!1}=e||{},s=t?this.payload:this.content,{abstractList:o,compatibleText:n,downloadKey:i,layersOverLimit:r,pbDownloadKey:a,title:c,version:u,messageList:l}=s;return{MsgType:this.type,MsgContent:{AbstractList:o,CompatibleText:n,JsonMsgKey:i,LayersOverLimit:r,PbMsgKey:a,Title:c,Version:u,MsgList:jn(l)}}}}var fi=new class{init(e){this._core=e;const{message:t,helper:s,constants:{OuterConstant:o}}=e;t.messageFactory.registerElementClass(o.MSG_MERGER,vi),s.registerApi({apiName:"createMergerMessage",context:this}),s.registerApi({apiName:"sendMessage",context:this,matcher:e=>e[0].type===o.MSG_MERGER}),s.registerApi({apiName:"downloadMergerMessage",context:this})}createMergerMessage(e){const{common:t}=this._core;if(!e)return null;const s=new vi(e.payload),o=t.getCurrentUserID(),n=this._core.message.messageFactory.createMessage(Object.assign(Object.assign({},e),{from:o}));return n.setRelayFlag(!0),n.setElement(s),n}sendMessage(e,t){return h(this,void 0,void 0,(function*(){var s,o,n;try{const i=function(e){let t="utf-8";_n.core.helper.IN_BROWSER&&document&&(t=document.charset.toLowerCase());let s,o=0,n=0;if(n=e.length,"utf-8"===t||"utf8"===t)for(let t=0;t<n;t++)s=e.codePointAt(t),s<=127?o+=1:s<=2047?o+=2:s<=65535?o+=3:(o+=4,t++);else if("utf-16"===t||"utf16"===t)for(let t=0;t<n;t++)s=e.codePointAt(t),s<=65535?o+=2:(o+=4,t++);else o=e.replace(/[^\x00-\xff]/g,"aa").length;return o}(JSON.stringify(e));let r=e,a=null;if(i>11264){r=this._core.utils.deepCopyWithMethods(e);try{const{JsonMsgKey:e,PbMsgKey:t}=yield function(e){return h(this,void 0,void 0,(function*(){const{payload:{messageList:t}}=e,s={MsgList:jn(t)};return _n.core.common.buildAndSendPacket({servcmd:"im_long_msg.save_relay_json_msg",data:s})}))}(r),{payload:s}=r;a=new vi(Object.assign(Object.assign({},s),{messageList:[],downloadKey:e,pbDownloadKey:t})),r.setElement(a)}catch(e){console.error(e)}}const{data:{message:c}}=yield null===(n=null===(o=null===(s=this._core)||void 0===s?void 0:s.message)||void 0===o?void 0:o.messageSender)||void 0===n?void 0:n.sendMessage(r,t);return a&&c.setElement(e._elements),{code:0,data:{message:c}}}catch(e){throw console.error(e),e}}))}downloadMergerMessage(e){return h(this,void 0,void 0,(function*(){try{const t=e.payload,{downloadKey:s,pbDownload:o,type:n,messageList:i}=t,r=p(t,["downloadKey","pbDownload","type","messageList"]),a=yield function(e){return h(this,void 0,void 0,(function*(){return _n.core.common.buildAndSendPacket({servcmd:"im_long_msg.get_relay_json_msg",data:{JsonMsgKey:e}})}))}(s),{MsgList:c}=a||{},u=null==c?void 0:c.map((e=>{const t=Kn(e);return new mi(t)}));return"function"==typeof e.isOnlineMessage?e.setElement({type:e.type,content:Object.assign({messageList:u},r)}):(e.payload.messageList=u,e.payload.downloadKey="",e.payload.pbDownloadKey=""),e}catch(e){console.error(e)}}))}};var Ii=new class{constructor(){this.name="MessageEnhancer"}install(e){this._core=e,_n.init(e),ni.init(e),ai.init(e),li.init(e),hi.init(e),Hn.init(e),gi.init(e),_i.init(e),Wn.init(e),fi.init(e),Jn.init(e),e.helper.registerValidateConfig({auth:ei,params:Zn}),e.notificationCenter.subscribeInnerEvent(e.InnerEvent.LOGOUT,this._reset,this),e.notificationCenter.subscribeInnerEvent(e.InnerEvent.DESTROY,this.dispose,this)}dispose(){const{notificationCenter:e,InnerEvent:t}=this._core;e.unSubscribeInnerEvent(t.LOGOUT,this._reset,this),e.unSubscribeInnerEvent(t.DESTROY,this.dispose,this),li.dispose(),hi.dispose(),Wn.dispose(),Jn.dispose()}_reset(){hi.reset()}};var Si=new class{constructor(){this._name="WebRequest"}init(e){this._core=e}request(e,t){return h(this,void 0,void 0,(function*(){var s;const{isEmpty:o}=null===(s=this._core)||void 0===s?void 0:s.utils,{downloadUrl:n="",method:i="PUT",url:r,qs:a,headers:c={},resources:u,dataType:l="text",uploadByIP:d,uploadIP:p}=e;let h=r;if(a){const e=this._queryString(a);e&&(h+=`${h.includes("?")?"&":"?"}${e}`)}const g=new XMLHttpRequest;g.open(i.toUpperCase(),h,!0),g.responseType=l;const _=Object.assign({},c);if(d&&p&&(_.host=p),!o(_))for(const e in _)_.hasOwnProperty(e)&&!["content-length","user-agent","origin","host"].includes(e.toLowerCase())&&g.setRequestHeader(e,_[e]);return g.onload=()=>{const s=this._getResponseBody(g,n,d&&p),o=this._buildResponse(g,s);if(200===g.status)t(null,o);else{if(p&&!h.includes(p))return e.url=this._domainName2IP(h,p),e.uploadByIP=!0,this.request(e,t);t({code:g.status,message:JSON.stringify(g.responseText)},o)}},g.onerror=()=>{const e=this._getResponseBody(g,n,d&&p),s=this._buildResponse(g,e),o={code:g.status,message:0===g.status?"CORS blocked or network error":JSON.stringify(g.responseText)};t(o,s)},e.onProgress&&g.upload&&(g.upload.onprogress=t=>{const{total:s,loaded:o}=t,n=Math.min(Math.floor(100*o/s),100);e.onProgress({total:s,loaded:o,percent:n/100})}),g.send(u),g}))}_buildResponse(e,t){const s={};return e.getAllResponseHeaders().trim().split("\n").forEach((e=>{if(e){const[t,o]=e.split(":").map((e=>e.trim()));s[t.toLowerCase()]=o}})),{statusCode:e.status,statusMessage:e.statusText,headers:s,data:t}}_getResponseBody(e,t,s){return 200===e.status&&t?{location:t,uploadIP:s}:{response:e.responseText,uploadIP:s}}_queryString(e,t="&",s="="){var o;const{isEmpty:n,isPlainObject:i}=null===(o=this._core)||void 0===o?void 0:o.utils;return n(e)?"":i(e)?Object.keys(e).map((o=>{const n=encodeURIComponent(o)+s;return Array.isArray(e[o])?e[o].map((e=>n+encodeURIComponent(e))).join(t):n+encodeURIComponent(e[o])})).filter(Boolean).join(t):void 0}_domainName2IP(e,t){return e.replace(/^http(s)?:\/\/(.*?)\//,`https://${t}/`)}};const Ei=["unknown","image","video","audio","log"];var Ci=new class{init(e){this._core=e}request(e,t){var s;const{MINI_APP_NAMESPACE:o,IN_ALIPAY_MINI_APP:n,IN_UNI_IOS_APP:i}=null===(s=this._core)||void 0===s?void 0:s.utils,{resources:r="",headers:a={},url:c,downloadUrl:u=""}=e;let l=c,d=null;const h=u?u.match(/^(https?:\/\/[^/]+\/)([^/]*\/?)(.*)$/):null;if(!h)return void console.warn("message Invalid download URL format");const g=decodeURIComponent(h[3]),_=g.includes("?")?g.split("?")[0]:g||"",m={key:e.fileKey||_,success_action_status:200,"Content-Type":""},v={};if(i){const[e,t]=c.split("?sign=");t&&(l=`${e}?sign=${encodeURIComponent(t)}`,v.sign=decodeURIComponent(t),v.signature=decodeURIComponent(t))}let f={url:l,header:a,name:"file",filePath:r,formData:Object.assign(Object.assign({},m),v),timeout:e.timeout||3e5};if(n){const t=p(f,["name"]);f=Object.assign(Object.assign({},t),{fileName:"file",fileType:e.fileType?Ei[e.fileType]:"image"})}return d=o.uploadFile(Object.assign(Object.assign({},f),{success:e=>{this._handleResponse({response:e,downloadUrl:u,callback:t})},fail:e=>{this._handleResponse({response:e,downloadUrl:u,callback:t})}})),d.onProgressUpdate&&d.onProgressUpdate((t=>{e.onProgress&&e.onProgress({total:t.totalBytesExpectedToSend||0,loaded:t.totalBytesSent||0,percent:t.progress?Math.floor(t.progress)/100:0})})),d}_handleResponse(e){const{downloadUrl:t,response:s,callback:o}=e,n={};if(s.header)for(const e in s.header)s.header.hasOwnProperty(e)&&(n[e.toLowerCase()]=s.header[e]);const i=+s.statusCode;200===i?o(null,{statusCode:i,headers:n,data:Object.assign(Object.assign({},s.data),{location:t})}):o({code:i,message:JSON.stringify(s.data)},{statusCode:i,headers:n,data:void 0})}};function Mi(e){return"file"===function(e){return Object.prototype.toString.call(e).match(/^\[object (.*)\]$/)[1].toLowerCase()}(e)}function yi(e){const t=e||99999999;return Math.round(Math.random()*t)}function Ti(e,t=!0,s=!0){const o=Date.now();return t?s?o-e+" ms":`${Math.round((o-e)/1e3)} s`:s?o-e:Math.round((o-e)/1e3)}function Ai(e){return`${Array.from({length:8},(()=>Math.floor(65536*(1+Math.random())).toString(16).substring(1))).join("")}-${e}`}function Oi(e,t){return Math.round(Number(e)*10**t)/10**t}function Di(e){const t=1024,s=1048576;return e<t?`${e}B`:e<s?`${Math.floor(e/t)}KB`:`${Math.floor(e/s)}MB`}function Ri(e){if(e<=1048576){return`${Oi(e/1024,1)}KB/s`}return`${Oi(e/1048576,1)}MB/s`}const Li="TIMImageElem",Ni="TIMSoundElem",bi="TIMFileElem",Gi="TIMVideoFileElem",wi="RichMediaMessagePlugin",Pi=["rich.my-imcloud.com","imrich.qcloud.com"],Ui=1,ki=2,Fi=3;var $i;!function(e){e.UNSENT="unSend",e.SUCCESS="success",e.FAIL="fail"}($i||($i={}));const qi={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 xi=new class{init(e){this._core=e}addAuthToUrl(e=""){if(this._isMiniProgramTempFile(e))return e;const t=function(e){return e?e.startsWith("https://")?e:e.startsWith("http://")?e.replace("http://","https://"):e:""}(e);return this.processResourceUrl(t)}removeAuthToUrl(e){return function(e,t){const[s,o]=e.split("?");if(!o)return s;const n=o.split("&").reduce(((e,s)=>{const[o,n]=s.split("=");return o&&o!==t&&(e[o]=n||""),e}),{}),i=Object.keys(n).map((e=>`${e}${n[e]?`=${n[e]}`:""}`)).join("&");return i?`${s}?${i}`:s}(e,"authKey")}_isMiniProgramTempFile(e){return!!this.getPlatformFlags().IN_MINI_APP&&Object.values(qi).some((t=>t.test(e)))}extractFileFromInput(e){return Mi(e)?e:function(e){if("object"!=typeof e||null===e)return!1;const t=Object.getPrototypeOf(e);if(null===t)return!0;let s=t;for(;null!==Object.getPrototypeOf(s);)s=Object.getPrototypeOf(s);return t===s}(e)&&"undefined"!=typeof uni?Array.isArray(e.tempFiles)&&e.tempFiles.length>0?e.tempFiles[0]:null:e instanceof HTMLInputElement&&e.files&&e.files.length>0?e.files[0]:null}probeImageWidthHeight(e){return h(this,void 0,void 0,(function*(){var t;const{IN_MINI_APP:s,IN_BROWSER:o}=(null===(t=this._core)||void 0===t?void 0:t.utils)||{};return this._shouldSkipProbing()?{width:0,height:0}:o?this._probeImageDimensionsWeb(e):s?this._probeImageDimensionsMiniApp(e):void 0}))}isSimpleCos(){var e;const t=(null===(e=this._core)||void 0===e?void 0:e.store.get("cloudConfig"))||{},{simple_cos:s}=t;return"0"!==s}getFileDNList(){var e;let t=Pi;const s=(null===(e=this._core)||void 0===e?void 0:e.store.get("cloudConfig"))||{},{file_dn_list:o}=s;if(void 0===o)return t;try{JSON.parse(o).forEach((e=>{t.includes(e)||t.push(e)}))}catch(e){console.warn(e),t=Pi}return t}getPlatform(){var e;return null===(e=this._core)||void 0===e?void 0:e.utils.platform}generateUUID(e,t){var s;let o=`${this.getSDKAppID()}-${this.getCurrentUserID()}-${null===(s=this._core)||void 0===s?void 0:s.utils.randomString()}`;if(t)return`${o}.${t}`;const n=e.name||e.value||e.url||e.tempFilePath,i=n&&n.slice(n.lastIndexOf(".")+1);return i&&(o=`${o}.${i}`),o}processResourceUrl(e){if(!e)return"";let t=e;const s=this.getFileDownloadProxy(),o=this.getAuthKey(),n=this.getFileDNList();s&&(e.startsWith("http://")?t=e.replace(/^http:\/\/[^/]+/,s):e.startsWith("https://")&&(t=e.replace(/^https:\/\/[^/]+/,s)));const i=o&&-1===t.indexOf("authKey=")&&function(e,t){let s=!1;if(e){const o=e.match(/:\/\/([0-9]?\.)?(.[^/:]+)/),n=o&&o[2]||"";if(n.includes("rich-dev"))return!0;for(let e=0;e<t.length;e++)if(n.endsWith(t[e])){s=!0;break}}return s}(t,n);return i&&(t=t.indexOf("?")>-1?`${t}&authKey=${o}`:`${t}?authKey=${o}`),t}getCurrentUserID(){var e,t;return null===(t=null===(e=this._core)||void 0===e?void 0:e.store.get("login"))||void 0===t?void 0:t.userId}getSDKAppID(){var e,t;return null===(t=null===(e=this._core)||void 0===e?void 0:e.store.get("instance"))||void 0===t?void 0:t.sdkAppId}getFileDownloadProxy(){var e,t;return(null===(t=null===(e=this._core)||void 0===e?void 0:e.store.get("instance"))||void 0===t?void 0:t.fileDownloadProxy)||""}getFileUploadProxy(){var e,t;return(null===(t=null===(e=this._core)||void 0===e?void 0:e.store.get("instance"))||void 0===t?void 0:t.fileUploadProxy)||""}getAuthKey(){var e,t;return(null===(t=null===(e=this._core)||void 0===e?void 0:e.store.get("login"))||void 0===t?void 0:t.authKey)||""}isPrivateNetWork(){var e,t;return null===(t=null===(e=this._core)||void 0===e?void 0:e.store.get("instance"))||void 0===t?void 0:t.proxyServer}getPlatformFlags(){var e;const{IN_BROWSER:t,IN_MINI_APP:s,IN_RN_APP:o,IN_UNI_NATIVE_APP:n}=null===(e=this._core)||void 0===e?void 0:e.utils;return{IN_BROWSER:t,IN_MINI_APP:s,IN_RN_APP:o,IN_UNI_NATIVE_APP:n}}isEmpty(e){var t;const{isEmpty:s}=null===(t=this._core)||void 0===t?void 0:t.utils;return s(e)}_probeImageDimensionsMiniApp(e){var t;const{MINI_APP_NAMESPACE:s}=(null===(t=this._core)||void 0===t?void 0:t.utils)||{};return new Promise((t=>{s.getImageInfo({src:e,success:e=>t({width:e.width,height:e.height}),fail:()=>t({width:0,height:0})})}))}_shouldSkipProbing(){var e;const{IN_RN_APP:t,IS_IE:s,IE_VERSION:o}=(null===(e=this._core)||void 0===e?void 0:e.utils)||{};return t||s&&9===o}_probeImageDimensionsWeb(e){return new Promise((t=>{const s=new Image,o=()=>{s.onload=null,s.onerror=null,s.src=""};s.onload=()=>{t({width:s.width,height:s.height}),o()},s.onerror=()=>{t({width:0,height:0}),o()},s.src=e}))}};var Vi=new class{constructor(){this.uploadFileTryCount=0,this.maxRetries=1,this.systemClockOffset=0,this.httpRequest=null,this.uploadFileType="",this.duration=900,this.fetchCosTryCount=0}init(e){var t;this._core=e;const{IN_MINI_APP:s}=e.utils;this.httpRequest=s?Ci:Si,null===(t=this.httpRequest)||void 0===t||t.init(e)}uploadToCOS(e){return h(this,void 0,void 0,(function*(){const t=`${wi} uploadToCOS`,{file:s}=e;this.uploadFileType=e.uploadFileType,console.log(`${t} options:`,e);try{const o=Date.now(),n=yield this._createCosOptions(e),i=yield this._uploadFile(n);this._handleUploadError(i,e);const r=this._createUploadResult(s,i),a=Date.now()-o,c=Di(s.size),u=`size:${c} time:${a}ms speed:${Ri(1e3*s.size/a)}`;return console.log(`${t} ok. name:${s.name} ${u}`),{uploadOptions:n,response:r}}catch(e){throw console.warn(`${t} failed, error:`,e),e}}))}_handleUploadError(e,t){var s,o;const{ChatError:n}=null===(s=this._core)||void 0===s?void 0:s.helper;if(403===e.statusCode)throw Ti(Date.now(),!1),t.url,(null===(o=null==e?void 0:e.data)||void 0===o?void 0:o.uploadIP)&&e.data.uploadIP,new n({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:Ti(Date.now(),!1),uploadSpeed:Ri(1e3*e.size/Ti(Date.now(),!1))}}_createCosOptions(e){return h(this,void 0,void 0,(function*(){const{fileName:t,resources:s,uploadMethod:o}=this._prepareUploadParams(e),n=this._isC2CConversation(e.message.conversationID)?1:2;try{const i=yield this._fetchCosSignatureUrl({fileType:this.uploadFileType,fileName:t,uploadMethod:o,duration:this.duration,userID:e.message.from,conversationType:n}),{uploadUrl:r,downloadUrl:a,requestSnapshotUrl:c,thumbUrl:u,largeUrl:l,fileKey:d}=i,p=!xi.isPrivateNetWork()&&i.uploadIP;return{url:this._getRawOrUploadProxyUrl(r),fileType:this.uploadFileType,fileName:t,resources:s,downloadUrl:a,requestSnapshotUrl:c,thumbUrl:u,largeUrl:l,fileKey:d,uploadIP:p||"",onProgress:t=>this._handleUploadProgress(t,e)}}catch(e){throw console.error("Failed to create COS pre-signed URL options:",e),e}}))}_prepareUploadParams(e){console.log(`${wi} prepareUploadParams:`,e);const{file:t}=e,{IN_MINI_APP:s,IN_RN_APP:o}=xi.getPlatformFlags(),n=s||o,i=n&&e.message.type!==bi,{name:r}=t,a=r.slice(r.lastIndexOf(".")),c=`${yi(999999)}${a}`;return{fileName:Ai(i?t.name:c),resources:n?t.url:t,uploadMethod:n?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*(){const t=`${wi} fetchCosSignatureUrl`,s=xi.isSimpleCos(),o=this._prepareCosRequestData(e),n=s?"im_cos_msg.simple_sig":"im_cos_msg.pre_sig";try{const e=yield function(e,t,s){return h(this,void 0,void 0,(function*(){try{const{helper:o,channel:n}=s,i=o.generateCosSpecifiedData({servcmd:e,data:t}),r=`${i.head.seq}${e}`;return yield n.sendPacket(i,{requestId:r})}catch(e){throw console.warn("getCosSig error:",e),e}}))}(n,o,this._core);this.fetchCosTryCount=0;const i=this._processResponse(e);return console.log(`${t} ok. isSimpleCos:${s} data:`,i),i||{}}catch(s){if(console.error(`${t} failed, error:`,s),this.fetchCosTryCount<1)return this.fetchCosTryCount++,this._fetchCosSignatureUrl(e);throw this.fetchCosTryCount=0,s}}))}_processResponse(e){var t;const s=xi.isSimpleCos(),o=s?null===(t=null==e?void 0:e.rpt_pre_sig)||void 0===t?void 0:t[0]:e;if(!o)return{};if(s){const{str_final_ip:e,rpt_pre_sig:t,uint32_file_id:s,uint32_exist_flag:n,str_download_url:i,str_upload_url:r,str_snapshot_url:a,str_file_key:c}=o;return{uploadIP:e,preSig:t,fileID:s,existFlag:n,downloadUrl:i,uploadUrl:r,requestSnapshotUrl:a,fileKey:c}}const{upload_url:n,download_url:i,snapshot_url:r,thumb_url:a,large_url:c,file_key:u}=o;return{uploadUrl:n,downloadUrl:i,requestSnapshotUrl:r,thumbUrl:a,largeUrl:c,fileKey:u}}_prepareCosRequestData(e){return xi.isSimpleCos()?{uint32_upload_method:e.uploadMethod,uint32_platform:xi.getPlatform(),uint32_sdkappid:xi.getSDKAppID(),str_user_id:e.userID,uint32_scene:e.conversationType,rpt_upload_object:[{uint32_file_id:1,uint32_file_type:e.fileType,str_file_name:e.fileName}]}:{file_type:e.fileType,file_name:e.fileName,upload_method:e.uploadMethod,Duration:e.duration}}_uploadFile(e){return h(this,void 0,void 0,(function*(){return new Promise(((t,s)=>{this.httpRequest.request(e,((o,n)=>{o&&this.uploadFileTryCount<this.maxRetries&&this.shouldRetry(o)?(this.uploadFileTryCount++,this._uploadFile(e).then(t).catch(s)):(this.uploadFileTryCount=0,o?s(o):t(n))}))}))}))}shouldRetry(e){if(!e)return!1;if(5===Math.floor(e.statusCode/100))return!0;return!(!this.isTimeRelatedError(e)||!this._isClockOutOfSync(e))&&(this._syncSystemClock(e),!0)}isTimeRelatedError(e){var t,s;try{const o=null===(t=e.error)||void 0===t?void 0:t.Code,n=null===(s=e.error)||void 0===s?void 0:s.Message;return"RequestTimeTooSkewed"===o||"AccessDenied"===o&&"Request has expired"===n}catch(e){return!1}}_isClockOutOfSync(e){var t,s,o;const n=(null===(t=e.headers)||void 0===t?void 0:t.date)||(null===(s=e.headers)||void 0===s?void 0:s.Date)||(null===(o=e.error)||void 0===o?void 0:o.ServerTime);if(!n)return!1;const i=Date.now(),r=Date.parse(n);return Math.abs(i+this.systemClockOffset-r)>=3e4}_syncSystemClock(e){var t,s,o;const n=(null===(t=e.headers)||void 0===t?void 0:t.date)||(null===(s=e.headers)||void 0===s?void 0:s.Date)||(null===(o=e.error)||void 0===o?void 0:o.ServerTime);if(n){const e=Date.now(),t=Date.parse(n);this.systemClockOffset=t-e}}_getRawOrUploadProxyUrl(e){const t=xi.getFileUploadProxy();let s=e;return t&&(s=e.replace(/^https:\/\/[^/]+/,t)),s}_isC2CConversation(e){return"C2C"===e.slice(0,3)}};const Bi=2108,ji=2251,Ki=2252,Hi=["jpg","jpeg","gif","png","bmp","image","webp"],Wi=20971520,Yi={JPG:1,JPEG:1,GIF:2,PNG:3,BMP:4,UNKNOWN:255};class zi{constructor(e,t){this.instanceID=yi(9999999),this.sizeType=e.type||0,this.type=0,this.size=e.size||0,this.width=e.width||0,this.height=e.height||0,this.imageUrl=xi.addAuthToUrl(e.imageUrl||e.url||""),this.url=xi.addAuthToUrl(e.url||t)}setSizeType(e){this.sizeType=e}setType(e){this.type=e}setImageUrl(e){e&&(this.imageUrl=xi.addAuthToUrl(e))}getImageUrl(){return this.imageUrl}}function Ji(e){const{originUrl:t,originWidth:s,originHeight:o,min:n=198}=e,i=parseInt(s)||0,r=parseInt(o)||0,a={url:void 0,width:0,height:0};if((i<=r?i:r)<=n)a.url=t,a.width=i,a.height=r;else{r<=i?(a.width=Math.ceil(i*n/r),a.height=n):(a.width=n,a.height=Math.ceil(r*n/i));const e=t&&t.indexOf("?")>-1?`${t}&`:`${t}?`;a.url=198===n?`${e}imageView2/3/w/198/h/198`:`${e}imageView2/3/w/720/h/720`}if(void 0===t){return p(a,["url"])}return a}class Qi{constructor(e){this._imageMemoryURL="",this._percent=0,this.type=Li;const{uuid:t,file:s,imageFormat:o,imageInfoArray:n=[]}=e;this._imageMemoryURL=this.createImageDataAsURL(s),this.content={imageFormat:o,uuid:t,imageInfoArray:[]},this.initImageInfoArray(n),this.autoFixUrl()}static parseServerPushElement(e){const{MsgContent:t}=e,{ImageFormat:s,ImageInfoArray:o,UUID:n}=t,i=function(e){return e.map((e=>({size:e.Size,type:e.Type,width:e.Width,height:e.Height,url:e.URL})))}(o);return new Qi({imageFormat:s,imageInfoArray:i,uuid:n})}createImageDataAsURL(e){let t="";const{IN_MINI_APP:s,IN_RN_APP:o,IN_BROWSER:n}=xi.getPlatformFlags();return e?((s||o)&&(t=e.url),n&&(t=window.URL.createObjectURL(e)),t):t}initImageInfoArray(e=[]){const t={type:0,size:0,width:0,height:0,url:""};for(let s=0;s<3;s++){const o=e[s]||Object.assign({},t),n=new zi(o,this._imageMemoryURL);n.setSizeType(s+1),n.setType(s),this.addImageInfo(n)}this.updateAccessSideImageInfoArray()}autoFixUrl(){const e=["http","https"];this.content.imageInfoArray.forEach((t=>{if(!t.url||""===t.imageUrl)return;const[s,...o]=t.imageUrl.split("://"),n=o.join("://");e.includes(s)||t.setImageUrl(`https://${n}`)}))}updatePercent(e){this._percent=Math.min(e,1)}updateImageFormat(e){this.content.imageFormat=Yi[e.toUpperCase()]||Yi.UNKNOWN}addImageInfo(e){this.content.imageInfoArray.length>=3||this.content.imageInfoArray.push(e)}updateImageInfoArray(e){const t=this.content.imageInfoArray.length;let s;for(let o=0;o<t;o++)s=this.content.imageInfoArray[o],e[o].size&&(s.size=e[o].size),e[o].url&&s.setImageUrl(e[o].url),e[o].width&&(s.width=e[o].width),e[o].height&&(s.height=e[o].height)}updateAccessSideImageInfoArray(){const[e]=this.content.imageInfoArray;e&&0!==e.width&&0!==e.height&&(!function(e){const t=e[2];e[2]=e[1],e[1]=t;for(let t=0;t<e.length;t++)e[t].setType(t)}(this.content.imageInfoArray),Object.assign(this.content.imageInfoArray[2],Ji({originWidth:e.width,originHeight:e.height,min:720})))}validateBeforeSend(){const[e]=this.content.imageInfoArray,t=!!e&&""!==e.imageUrl&&0!==e.size;return{isValid:t,error:t?null:{message:"content can not be empty"}}}transformToServerFormat(e){const{isMergerMessage:t=!1}=e||{},s=t?this.payload:this.content,{uuid:o,imageFormat:n,imageInfoArray:i}=s;return{MsgType:this.type,MsgContent:{ImageFormat:n,ImageInfoArray:this.parseImageInfoArray(i),UUID:o}}}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:xi.removeAuthToUrl(e.imageUrl)})))}}var Xi=new class{constructor(){this._messageOptionsMap=new Map}init(e){var t;this._core=e;const{notificationCenter:s,helper:o,InnerEvent:n,message:i}=e;o.registerApi({apiName:"createImageMessage",context:this}),null===(t=null==i?void 0:i.messageFactory)||void 0===t||t.registerElementClass(Li,Qi),s.subscribeInnerEvent(n.DESTROY,this._dispose,this)}createImageMessage(e){var t,s,o,n,i;try{const n=this._core.ssoLog.createSSOLogData({method:"createImageMessage"});console.log(`${wi} createImageMessage options:`,e);const i=null===(t=this._core.store.get("login"))||void 0===t?void 0:t.userId,r=null===(o=null===(s=this._core)||void 0===s?void 0:s.message.messageFactory)||void 0===o?void 0:o.createMessage(Object.assign(Object.assign({},e),{from:i})),a=this._processImage(e);e.payload.file=a;const c={imageFormat:Yi.UNKNOWN,uuid:xi.generateUUID(a),file:a,imageInfoArray:[]},u=new Qi(c);return r.setElement(u),this._messageOptionsMap.set(r.clientSequence,e),console.log(`${wi} createImageMessage OK imageMessage:`,r),n.end(),r}catch(e){throw null===(i=(n=this._core.ssoLog.getSSOLogData("createImageMessage")).setError)||void 0===i||i.call(n,e).end(),console.error(`${wi} createImageMessage error:`,e),e}}upload(e){return h(this,void 0,void 0,(function*(){console.log(`${wi} uploadImage message:`,e);const t=e.getElements()[0],{file:s}=this._messageOptionsMap.get(e.clientSequence).payload;this._validateBeforeUploadImage(s);const o=yield this._performImageUpload(t,e,s),n=this._generateImageInfo(o);return t.updateImageFormat(null==o?void 0:o.fileType),t.updateImageInfoArray(n),e}))}_performImageUpload(e,t,s){return h(this,void 0,void 0,(function*(){const{to:o}=t,n={uploadFileType:Ui,file:s,to:o,message:t,onProgress:s=>{var o,n;e.updatePercent(s),null===(n=null===(o=this._messageOptionsMap.get(t.clientSequence))||void 0===o?void 0:o.onProgress)||void 0===n||n.call(o,s)}},{uploadOptions:i,response:r}=yield Vi.uploadToCOS(n);return this._parseResponse(i,r)}))}_generateImageInfo(e){console.log(`${wi} generateImageInfo`);const{location:t,fileSize:s,width:o,height:n,smallImageUrl:i,smallImageWidth:r,smallImageHeight:a,largeImageUrl:c,largeImageWidth:u,largeImageHeight:l,imageInfoArray:d}=e,p=xi.addAuthToUrl(t),h={size:s,url:p,width:o,height:n};return(null==d?void 0:d.length)>0?this._processImageInfoArray(d,s):i&&c?[Object.assign({},h),{largeImageUrl:c,largeImageWidth:u,largeImageHeight:l},{smallImageUrl:i,smallImageWidth:r,smallImageHeight:a}]:[Object.assign({},h),this._generateThumbInfo(p,o,n,720),this._generateThumbInfo(p,o,n,198)]}_generateThumbInfo(e,t,s,o){return Ji({originUrl:e,originWidth:t,originHeight:s,min:o})}_processImageInfoArray(e,t){let s,o,n;for(const i of e)1===i.type?(o=i,o.size=t):2===i.type?(n=i,n.size=t):(s=i,s.size=t);return[Object.assign({},s),Object.assign({},n),Object.assign({},o)]}_parseResponse(e,t){return h(this,void 0,void 0,(function*(){console.log(`${wi} parseResponse`);try{const{thumbUrl:s,largeUrl:o,downloadUrl:n}=e;s&&o&&(yield this._getImageInfoByUrl(s,t,"thumb"),yield this._getImageInfoByUrl(o,t,"large"));if(xi.isSimpleCos()&&!xi.isPrivateNetWork()&&(yield this._getImageInfoArray(n,t),null==t?void 0:t.uploadIP)){const e=this._extractDomainFromUrl(n);e&&(yield this._getDownloadIP(e,t))}return t}catch(e){throw console.error("Failed to parse response:",e),e}}))}_extractDomainFromUrl(e){try{const t=e.match(/:\/\/([^\/]+)/);return t?t[1]:null}catch(e){return console.warn("Failed to extract domain from URL:",e),null}}_getImageInfoByUrl(e,t,s){return h(this,void 0,void 0,(function*(){try{const o=xi.addAuthToUrl(e),{width:n=0,height:i=0}=yield xi.probeImageWidthHeight(o);t.width=n,t.height=i,"thumb"===s?(t.smallImageUrl=e,t.smallImageWidth=n,t.smallImageHeight=i):(t.largeImageUrl=e,t.largeImageWidth=n,t.largeImageHeight=i)}catch(e){console.warn(`Failed to get ${s} image info:`,e)}}))}_validateBeforeUploadImage(e){var t;const{ChatError:s}=null===(t=this._core)||void 0===t?void 0:t.helper;if(!e)throw new s({code:ji});this._checkImageType(e),this._checkImageSize(e)}_processImage(e){var t;try{const{IN_MINI_APP:s}=null===(t=this._core)||void 0===t?void 0:t.utils;let{file:o}=e.payload;return o=s?this._processMiniAppImageFile(o):this._processWebImageFile(o),o}catch(e){throw console.warn(`${wi} _processImage error:`,e),e}}_processMiniAppImageFile(e){Mi(e)&&console.warn("FileUnsupportedInMiniApp","createImageMessage");const t=e.tempFiles[0].path||e.tempFiles[0].tempFilePath;return{url:t,name:t.slice(t.lastIndexOf("/")+1),size:e.tempFiles&&e.tempFiles[0].size||1,type:t.slice(t.lastIndexOf(".")+1).toLowerCase()}}_processWebImageFile(e){var t;const{ChatError:s}=null===(t=this._core)||void 0===t?void 0:t.helper,o=xi.extractFileFromInput(e);if(!o)throw new s({message:"Invalid file. Pass either `e.target` (from file input) or a File object"});return o}_getDownloadIP(e,t){return h(this,void 0,void 0,(function*(){const s=`${wi} getDownloadIP domainName: ${e}`;try{const o=yield function(e,t){return h(this,void 0,void 0,(function*(){try{const{helper:s,channel:o}=t,n="im_cos_msg.get_final_ip",i={str_domain:e},r=s.generateProtocolData({servcmd:n,data:i}),a=`${r.head.seq}${n}`;return yield o.sendPacket(r,{requestId:a})}catch(e){throw console.warn("getFinalIP error:",e),e}}))}(e,this._core);if(!o||!o.str_final_ip)return;console.log(`${s} ok. downloadIP:${o}`);const n=t.location.split("/");n[0]=o.str_final_ip,t.location=n.join("/")}catch(e){console.warn(e)}}))}_getImageInfoArray(e,t){return h(this,void 0,void 0,(function*(){const s=`${wi}._getImageInfoArray`;try{const o=yield function(e,t){return h(this,void 0,void 0,(function*(){try{const{helper:s,channel:o}=t,n="im_cos_msg.get_imageinfo",i={str_image_url:e},r=s.generateProtocolData({servcmd:n,data:i}),a=`${r.head.seq}${n}`;return yield o.sendPacket(r,{requestId:a})}catch(e){throw console.warn("getImageInfo error:",e),e}}))}(e,this._core);return t.imageInfoArray=this._processImageInfoResponse(o),console.log(`${s} ok`),t}catch(e){throw t.imageInfoArray=void 0,console.warn(`${s} failed, error:`,e),e}}))}_processImageInfoResponse(e){if(!e)return[];const{rpt_msg_image_info:t}=e;return t.map((e=>({type:e.uint32_image_type,url:e.str_url,width:e.uint32_width,height:e.uint32_height,imageFormat:e.str_image_format})))}_checkImageType(e){const{utils:t,helper:s}=this._core;let o="";if(t.IN_MINI_APP&&(o=e.url.slice(e.url.lastIndexOf(".")+1)),t.IN_BROWSER&&(o=e.name.slice(e.name.lastIndexOf(".")+1)),Hi.indexOf(o.toLowerCase())<0)throw new s.ChatError({code:Ki})}_checkImageSize(e){const{utils:t,helper:s}=this._core;let o=0;if(o=(t.IN_MINI_APP,e.size),0===o)throw new s.ChatError({code:Bi});if(o>=Wi)throw new s.ChatError({message:`File size exceeds limit: ${Di(Wi)}`})}_reset(){this._messageOptionsMap.clear()}_dispose(){this._reset();const{notificationCenter:e,InnerEvent:t}=this._core;e.unSubscribeInnerEvent(t.DESTROY,this._dispose,this)}};const Zi=2108,er=2401,tr="2.5.0",sr="1.18.0",or=104857600;function nr(e,t){const s=e.split("."),o=t.split("."),n=Math.max(s.length,o.length);for(;s.length<n;)s.push("0");for(;o.length<n;)o.push("0");for(let e=0;e<n;e++){const t=parseInt(s[e]),n=parseInt(o[e]);if(t>n)return 1;if(t<n)return-1}return 0}class ir{constructor(e){this.type=bi,this.uploadProgress=0;const t=this._getFileInfo(e);this.content={downloadFlag:2,fileUrl:xi.addAuthToUrl(e.url||e.fileUrl)||"",uuid:e.uuid,fileName:t.name||"",fileSize:t.size||0}}static parseServerPushElement(e){const{MsgContent:t}=e,{Download_Flag:s,Url:o,FileName:n,FileSize:i,UUID:r}=t;return new ir({downloadFlag:s,url:o,fileName:n,fileSize:i,uuid:r})}updatePercent(e){this.uploadProgress=Math.min(e,1)}updateFileUrl(e){this.content.fileUrl=e}validateBeforeSend(){const e=""!==this.content.fileUrl&&""!==this.content.fileName&&this.content.fileSize>0;return{isValid:e,error:e?null:{message:"content can not be empty"}}}transformToServerFormat(e){const{isMergerMessage:t=!1}=e||{},s=t?this.payload:this.content,{uuid:o,downloadFlag:n,fileUrl:i,fileName:r,fileSize:a}=s;return{MsgType:this.type,MsgContent:{Download_Flag:n,Url:xi.removeAuthToUrl(i),FileName:r,FileSize:a,UUID:o}}}_getFileInfo(e){if(e.fileName&&e.fileSize)return{size:e.fileSize,name:e.fileName};const{file:t}=e;return t?(xi.getPlatform().IN_UNI_NATIVE_APP&&this._processNativeAppFile(t),{size:t.size,name:t.name}):{size:0,name:""}}_processNativeAppFile(e){if(e.path&&e.path.includes(".")){const t=e.path.slice(e.path.lastIndexOf(".")+1).toLowerCase();e.type=t,e.name||(e.name=`${yi(999999)}.${t}`)}e.name||(e.type="",e.name=e.path.slice(e.path.lastIndexOf("/")+1).toLowerCase()),e.suffix&&(e.type=e.suffix),e.url||(e.url=e.path)}}var rr=new class{constructor(){this._messageOptionsMap=new Map}init(e){var t;this._core=e;const{notificationCenter:s,helper:o,InnerEvent:n,message:i}=e;o.registerApi({apiName:"createFileMessage",context:this}),null===(t=null==i?void 0:i.messageFactory)||void 0===t||t.registerElementClass(bi,ir),s.subscribeInnerEvent(n.DESTROY,this._dispose,this)}createFileMessage(e){var t,s,o,n,i;try{const n=this._core.ssoLog.createSSOLogData({method:"createFileMessage"});console.log(`${wi} createFileMessage options:`,e),this._checkVersion();const i=this._processFile(e.payload.file);e.payload.file=i;const r=null===(t=this._core.store.get("login"))||void 0===t?void 0:t.userId,a=null===(o=null===(s=this._core)||void 0===s?void 0:s.message.messageFactory)||void 0===o?void 0:o.createMessage(Object.assign(Object.assign({},e),{from:r})),c={uuid:xi.generateUUID(i),file:i},u=new ir(c);return a.setElement(u),this._messageOptionsMap.set(a.clientSequence,e),console.log(`${wi} createFileMessage success fileMessage:`,a),n.end(),a}catch(e){throw null===(i=(n=this._core.ssoLog.getSSOLogData("createFileMessage")).setError)||void 0===i||i.call(n,e).end(),console.error(`${wi} createFileMessage error:`,e),e}}upload(e){return h(this,void 0,void 0,(function*(){console.log(`${wi} uploadFile message:`,e);const{file:t}=this._messageOptionsMap.get(e.clientSequence).payload;this._validateBeforeUploadFile(t);const s=e.getElements()[0],o=yield this._performFileUpload(s,e,t),n=xi.addAuthToUrl(null==o?void 0:o.location);return s.updateFileUrl(n),e}))}_validateBeforeUploadFile(e){var t;const{ChatError:s}=null===(t=this._core)||void 0===t?void 0:t.helper;if(!e)throw new s({code:er});if(e.size>or)throw new s({message:`File size exceeds limit: ${Di(or)}`});if(0===e.size)throw new s({code:Zi})}_performFileUpload(e,t,s){return h(this,void 0,void 0,(function*(){const{to:o}=t,n={uploadFileType:Ui,file:s,to:o,message:t,onProgress:s=>{var o,n;e.updatePercent(s),null===(n=null===(o=this._messageOptionsMap.get(t.clientSequence))||void 0===o?void 0:o.onProgress)||void 0===n||n.call(o,s)}},{response:i}=yield Vi.uploadToCOS(n);return i}))}_processFile(e){var t,s;const{IN_BROWSER:o,IN_RN_APP:n,IN_WX_MINI_APP:i,IN_QQ_MINI_APP:r,IN_UNI_NATIVE_APP:a}=null===(t=this._core)||void 0===t?void 0:t.utils,{ChatError:c}=null===(s=this._core)||void 0===s?void 0:s.helper;if(o||a){const t=xi.extractFileFromInput(e);if(!t)throw new c({message:"Invalid file. Pass either `e.target` (from file input) or a File object"});return t}if(i||r){const{tempFiles:t}=e;return Object.assign(Object.assign({},t[0]),{url:t[0].path})}return n?Object.assign(Object.assign({},e),{url:e.uri}):e}_checkVersion(){var e,t;const{MINI_APP_NAMESPACE:s,IN_MINI_APP:o,IN_WX_MINI_APP:n,IN_QQ_MINI_APP:i,IN_UNI_NATIVE_APP:r}=null===(e=this._core)||void 0===e?void 0:e.utils,{ChatError:a}=null===(t=this._core)||void 0===t?void 0:t.helper;if(o){if(!(n||i||r))throw new a({message:"Unsupported mini app environment"});const e=s.getSystemInfoSync().SDKVersion;if(n&&nr(e,tr)<0){throw new a({message:`WXChooseMessageFile requires SDK version ${tr} or higher`})}if(i&&nr(e,sr)<0){throw new a({message:`QQChooseMessageFile requires SDK version ${sr} or higher`})}}}_reset(){this._messageOptionsMap.clear()}_dispose(){this._reset();const{notificationCenter:e,InnerEvent:t}=this._core;e.unSubscribeInnerEvent(t.DESTROY,this._dispose,this)}};const ar=2108,cr=2352,ur=["mp4","quicktime","mov"],lr=104857600;class dr{constructor(e){this.type=Gi,this.uploadProgress=0;const t="number"==typeof(null==e?void 0:e.videoSecond)?null==e?void 0:e.videoSecond:0;this.content={remoteVideoUrl:xi.addAuthToUrl(e.remoteVideoUrl||e.videoUrl||""),videoFormat:e.videoFormat,videoSecond:parseInt(null==t?void 0:t.toString(),10),videoSize:e.videoSize,videoUrl:xi.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:xi.addAuthToUrl(e.thumbUrl),snapshotUrl:xi.addAuthToUrl(e.thumbUrl)}}static parseServerPushElement(e){const{MsgContent:t}=e,{VideoUrl:s,VideoFormat:o,VideoSecond:n,VideoSize:i,VideoDownloadFlag:r,VideoUUID:a,ThumbUUID:c,ThumbFormat:u,ThumbWidth:l,SnapshotWidth:d,ThumbHeight:p,SnapshotHeight:h,ThumbSize:g,SnapshotSize:_,ThumbDownloadFlag:m,ThumbUrl:v,SnapshotUrl:f}=t;return new dr({videoUrl:s,videoFormat:o,videoSecond:n,videoSize:i,videoDownloadFlag:r,videoUUID:a,thumbUUID:c,thumbFormat:u,thumbWidth:l,snapshotWidth:d,thumbHeight:p,snapshotHeight:h,thumbSize:g,snapshotSize:_,thumbDownloadFlag:m,thumbUrl:v,snapshotUrl:f})}updatePercent(e){this.uploadProgress=Math.min(e,1)}updateVideoUrl(e){e&&(this.content.remoteVideoUrl=e)}updateSnapshotInfo(e){const{snapshotUrl:t,snapshotWidth:s,snapshotHeight:o}=e;xi.isEmpty(t)||(this.content.thumbUrl=this.content.snapshotUrl=t),xi.isEmpty(s)||(this.content.thumbWidth=this.content.snapshotWidth=Number(s)),xi.isEmpty(o)||(this.content.thumbHeight=this.content.snapshotHeight=Number(o))}validateBeforeSend(){const e=""!==this.content.remoteVideoUrl;return{isValid:e,error:e?null:{message:"content can not be empty"}}}transformToServerFormat(e){const{isMergerMessage:t=!1}=e||{},s=t?this.payload:this.content,{remoteVideoUrl:o,videoFormat:n,videoSecond:i,videoSize:r,videoDownloadFlag:a,videoUUID:c,thumbUUID:u,thumbFormat:l,thumbWidth:d,snapshotWidth:p,thumbHeight:h,snapshotHeight:g,thumbSize:_,snapshotSize:m,thumbDownloadFlag:v,thumbUrl:f,snapshotUrl:I}=s;return{MsgType:this.type,MsgContent:{VideoUrl:xi.removeAuthToUrl(o),VideoFormat:n,VideoSecond:i,VideoSize:r,VideoDownloadFlag:a,VideoUUID:c,ThumbUUID:u,ThumbFormat:l,ThumbWidth:d,SnapshotWidth:p,ThumbHeight:h,SnapshotHeight:g,ThumbSize:_,SnapshotSize:m,ThumbDownloadFlag:v,ThumbUrl:xi.removeAuthToUrl(f),SnapshotUrl:xi.removeAuthToUrl(I)}}}}var pr=new class{constructor(){this._messageOptionsMap=new Map}init(e){var t;this._core=e;const{notificationCenter:s,helper:o,InnerEvent:n,message:i}=e;o.registerApi({apiName:"createVideoMessage",context:this}),null===(t=null==i?void 0:i.messageFactory)||void 0===t||t.registerElementClass(Gi,dr),s.subscribeInnerEvent(n.DESTROY,this._dispose,this)}createVideoMessage(e){var t,s,o,n,i;try{const n=this._core.ssoLog.createSSOLogData({method:"createVideoMessage"});console.log(`${wi} createVideoMessage options:`,e);const i=this._processVideo(e);e.payload.file=i;const r=null===(t=this._core.store.get("login"))||void 0===t?void 0:t.userId,a=null===(o=null===(s=this._core)||void 0===s?void 0:s.message.messageFactory)||void 0===o?void 0:o.createMessage(Object.assign(Object.assign({},e),{from:r})),c={videoFormat:i.videoFile.type,videoSecond:Oi(i.videoFile.second,0),videoSize:i.videoFile.size,remoteVideoUrl:"",videoUrl:i.videoFile.url,videoUUID:xi.generateUUID(i.videoFile),thumbUUID:xi.generateUUID(i.videoFile,"jpg"),thumbWidth:i.width||200,thumbHeight:i.height||200,thumbUrl:i.thumbUrl,thumbSize:i.thumbSize,thumbFormat:"jpg"},u=new dr(c);return a.setElement(u),this._messageOptionsMap.set(a.clientSequence,e),n.end(),a}catch(e){throw null===(i=(n=this._core.ssoLog.getSSOLogData("createVideoMessage")).setError)||void 0===i||i.call(n,e).end(),console.error(`${wi} createVideoMessage error:`,e),e}}upload(e){return h(this,void 0,void 0,(function*(){console.log(`${wi} uploadVideo message:`,e);const t=e.getElements()[0],{file:s}=this._messageOptionsMap.get(e.clientSequence).payload;this._validateBeforeUploadVideo(s);const o=yield this._performVideoUpload(t,e,s),{location:n,snapshotInfo:i}=o,r=xi.addAuthToUrl(n);return t.updateVideoUrl(r),xi.isEmpty(i)||t.updateSnapshotInfo(i),e}))}_validateBeforeUploadVideo(e){var t;const{ChatError:s}=null===(t=this._core)||void 0===t?void 0:t.helper;if(e.videoFile.size>lr)throw new s({message:`File size exceeds limit: ${Di(lr)}`});if(0===e.videoFile.size)throw new s({code:ar});if(-1===ur.indexOf(e.videoFile.type))throw new s({code:cr})}_performVideoUpload(e,t,s){return h(this,void 0,void 0,(function*(){const{to:o}=t,n={uploadFileType:ki,file:s,to:o,message:t,onProgress:s=>{var o,n;e.updatePercent(s),null===(n=null===(o=this._messageOptionsMap.get(t.clientSequence))||void 0===o?void 0:o.onProgress)||void 0===n||n.call(o,s)}},{response:i,uploadOptions:r}=yield Vi.uploadToCOS(n);return{snapshotInfo:yield this._getSnapshotInfoByUrl(r.requestSnapshotUrl),location:i.location}}))}_processVideo(e){var t,s;try{const{ChatError:o}=null===(t=this._core)||void 0===t?void 0:t.helper,{IN_MINI_APP:n,IN_BROWSER:i}=null===(s=this._core)||void 0===s?void 0:s.utils;let{file:r}=e.payload,a={};if(n&&(a=this._processMiniVideoFile(r),r.name=a.name,r.url=a.url),i){const e=xi.extractFileFromInput(r);if(!e)throw new o({message:"Invalid file. Pass either `e.target` (from file input) or a File object"});r=e,a=this._processWebVideoFile(r)}return r.videoFile=a,r.thumbUrl="",r.thumbSize=0,r}catch(e){throw console.warn(`${wi} _processFile error:`,e),e}}_processMiniVideoFile(e){var t,s;const{IN_ALIPAY_MINI_APP:o}=null===(t=this._core)||void 0===t?void 0:t.utils,{ChatError:n}=null===(s=this._core)||void 0===s?void 0:s.helper;if(o)throw new n({message:"VideoUnsupportedInAlipay"});if(Mi(e))throw new n({message:"FileUnsupportedInMiniApp"});return Array.isArray(e.tempFiles)&&(e=e.tempFiles[0]),{url:e.tempFilePath,name:e.tempFilePath.slice(e.tempFilePath.lastIndexOf("/")+1),size:e.size||1,second:e.duration||0,type:e.tempFilePath.slice(e.tempFilePath.lastIndexOf(".")+1).toLowerCase()}}_processWebVideoFile(e){const{name:t,size:s=1,duration:o=0,type:n}=e,i=n.split("/")[1];return{url:window.URL.createObjectURL(e),name:t,size:s,second:o,type:i}}_getSnapshotInfoByUrl(e){return h(this,void 0,void 0,(function*(){try{console.log(`${wi} _getSnapshotInfoByUrl url:`,e);const t={version:1,platform:xi.getPlatform(),cover_name:Ai(yi(99999)),snapshot_url:e},s=yield function(e,t){return h(this,void 0,void 0,(function*(){try{const s="im_cos_msg.video_cover",{helper:o,channel:n}=t,i=o.generateCosSpecifiedData({servcmd:s,data:e}),r=`${i.head.seq}${s}`;return yield n.sendPacket(i,{requestId:r})}catch(e){throw console.warn("getSnapshotInfo error:",e),e}}))}(t,this._core),{download_url:o}=s||{};if(console.log(`${wi} _getSnapshotInfoByUrl OK snapshotUrl:`,o),xi.isEmpty(o))return{};const n=xi.addAuthToUrl(o),{width:i=0,height:r=0}=yield xi.probeImageWidthHeight(n);return{snapshotUrl:n,snapshotWidth:i,snapshotHeight:r}}catch(e){throw console.error(`${wi} _getSnapshotInfoByUrl error:`,e),e}}))}_reset(){this._messageOptionsMap.clear()}_dispose(){this._reset();const{notificationCenter:e,InnerEvent:t}=this._core;e.unSubscribeInnerEvent(t.DESTROY,this._dispose,this)}};class hr{constructor(e){this.uploadProgress=0,this.type=Ni,this.content={downloadFlag:2,second:e.second,size:e.size,url:xi.addAuthToUrl(e.url),remoteAudioUrl:xi.addAuthToUrl(e.url||""),uuid:e.uuid}}static parseServerPushElement(e){const{MsgContent:t}=e,{Url:s,Download_Flag:o,Second:n,Size:i,UUID:r}=t;return new hr({url:s,downloadFlag:o,second:n,size:i,uuid:r})}updatePercent(e){this.uploadProgress=Math.min(e,1)}updateAudioUrl(e){this.content.remoteAudioUrl=e}validateBeforeSend(){const e=""!==this.content.remoteAudioUrl;return{isValid:e,error:e?null:{message:"content can not be empty"}}}transformToServerFormat(e){const{isMergerMessage:t=!1}=e||{},s=t?this.payload:this.content,{uuid:o,downloadFlag:n,remoteAudioUrl:i,size:r,second:a}=s;return{MsgType:this.type,MsgContent:{Url:xi.removeAuthToUrl(i),Download_Flag:n,Second:a,Size:r,UUID:o}}}}const gr=2108,_r=2300,mr=20971520;var vr=new class{constructor(){this._messageOptionsMap=new Map}init(e){var t;this._core=e;const{notificationCenter:s,helper:o,InnerEvent:n,message:i}=e;o.registerApi({apiName:"createAudioMessage",context:this}),null===(t=null==i?void 0:i.messageFactory)||void 0===t||t.registerElementClass(Ni,hr),s.subscribeInnerEvent(n.DESTROY,this._dispose,this)}createAudioMessage(e){var t,s,o,n,i;try{const n=this._core.ssoLog.createSSOLogData({method:"createAudioMessage"});console.log(`${wi} createAudioMessage options:`,e);let{file:i}=e.payload;i=this._processAudioFile(e.payload.file),e.payload.file=i;const r=null===(t=this._core.store.get("login"))||void 0===t?void 0:t.userId,a=null===(o=null===(s=this._core)||void 0===s?void 0:s.message.messageFactory)||void 0===o?void 0:o.createMessage(Object.assign(Object.assign({},e),{from:r})),c={second:Math.floor((i.duration||i.second)/1e3),size:i.fileSize||i.size||1,url:i.tempFilePath||i.uri||i.url,uuid:xi.generateUUID(i)},u=new hr(c);return a.setElement(u),this._messageOptionsMap.set(a.clientSequence,e),n.end(),a}catch(e){throw null===(i=(n=this._core.ssoLog.getSSOLogData("createAudioMessage")).setError)||void 0===i||i.call(n,e).end(),console.error(`${wi} createAudioMessage error:`,e),e}}upload(e){return h(this,void 0,void 0,(function*(){console.log(`${wi} uploadAudio message:`,e);const{file:t}=this._messageOptionsMap.get(e.clientSequence).payload;this._validateBeforeUploadAudio(t);const s=e.getElements()[0],o=yield this._performAudioUpload(s,e,t),n=xi.addAuthToUrl(null==o?void 0:o.location);return s.updateAudioUrl(n),e}))}_validateBeforeUploadAudio(e){var t;const{ChatError:s}=null===(t=this._core)||void 0===t?void 0:t.helper;if(!e)throw new s({code:_r});if(e.size>mr)throw new s({message:`File size exceeds limit: ${Di(mr)}`});if(0===e.size)throw new s({code:gr})}_performAudioUpload(e,t,s){return h(this,void 0,void 0,(function*(){const{to:o}=t,n={uploadFileType:Fi,file:s,to:o,message:t,onProgress:s=>{var o,n;e.updatePercent(s),null===(n=null===(o=this._messageOptionsMap.get(t.clientSequence))||void 0===o?void 0:o.onProgress)||void 0===n||n.call(o,s)}},{response:i}=yield Vi.uploadToCOS(n);return i}))}_processAudioFile(e){var t;const{IN_MINI_APP:s,IN_BROWSER:o}=null===(t=this._core)||void 0===t?void 0:t.utils;return s?this._processMiniFile(e):o?this._processWebFile(e):void 0}_processMiniFile(e){return{url:e.tempFilePath,name:e.tempFilePath.slice(e.tempFilePath.lastIndexOf("/")+1),size:e.fileSize,second:e.duration,type:e.tempFilePath.slice(e.tempFilePath.lastIndexOf(".")+1).toLowerCase()}}_processWebFile(e){if(e.tempFilePath||e.uri)return e;const t=URL.createObjectURL(e);return e.tempFilePath=t,e}_reset(){this._messageOptionsMap.clear()}_dispose(){this._reset();const{notificationCenter:e,InnerEvent:t}=this._core;e.unSubscribeInnerEvent(t.DESTROY,this._dispose,this)}};const fr={to:{required:!0,rules:["string"],allowEmpty:!1},conversationType:{required:!0,rules:["string"],allowEmpty:!1},payload:{required:!0,rules:["object"],allowEmpty:!1},cloudCustomData:{required:!1,rules:["string"],allowEmpty:!1},priority:{required:!1,rules:["string"],allowEmpty:!1},customModerationConfigurationID:{required:!1,rules:["string"],allowEmpty:!1},onProgress:{required:!1,rules:["function"],allowEmpty:!1}},Ir={createImageMessage:fr,createAudioMessage:fr,createVideoMessage:fr,createFileMessage:fr},Sr={createImageMessage:!0,createAudioMessage:!0,createVideoMessage:!0,createFileMessage:!0},Er={[Li]:Xi,[bi]:rr,[Gi]:pr,[Ni]:vr};var Cr=new class{constructor(){this.name="RichMediaMessage"}install(e){this._core=e;const{constants:{OuterConstant:{MSG_AUDIO:t,MSG_FILE:s,MSG_IMAGE:o,MSG_VIDEO:n}}}=e;Xi.init(e),rr.init(e),pr.init(e),vr.init(e),Vi.init(e),xi.init(e),e.helper.registerApi({apiName:"sendMessage",context:this,matcher:e=>[t,s,o,n].includes(e[0].type)}),e.helper.registerValidateConfig({auth:Sr,params:Ir})}sendMessage(e,t){return h(this,void 0,void 0,(function*(){var s,o,n;try{return console.log("sendMessage message:",e),yield this._upload(e),yield null===(n=null===(o=null===(s=this._core)||void 0===s?void 0:s.message)||void 0===o?void 0:o.messageSender)||void 0===n?void 0:n.sendMessage(e,t)}catch(e){throw console.error("sendMessage error:",e),e}}))}_upload(e){return h(this,void 0,void 0,(function*(){var t,s;if(!0!==e._relayFlag)try{const t=Er[e.type];if(t){const s=this._core.ssoLog.createSSOLogData({method:"upload"});s.setLogInfo({message:`type:${e.type}`}),yield t.upload(e),s.end()}}catch(o){throw e.status=$i.FAIL,o instanceof Error&&(o.data={message:e}),this._core.message.messageDataHandler.storeConversationMessage(e),null===(s=(t=this._core.ssoLog.getSSOLogData("upload")).setError)||void 0===s||s.call(t,o).end(),o}}))}};const Mr=new class{init(e){this.core=e}},yr=e=>{const{core:{OuterConstant:t,utils:{isString:s}}}=Mr;return s(e)&&e.slice(0,3)===t.CONV_C2C},Tr=e=>{const{core:{OuterConstant:t,utils:{isString:s}}}=Mr;return s(e)&&e.slice(0,5)===t.CONV_GROUP},Ar=e=>{const{core:{OuterConstant:t,utils:{isString:s}}}=Mr;return s(e)&&e===t.CONV_SYSTEM},Or=e=>({lastTime:(null==e?void 0:e.time)||(null==e?void 0:e.lastTime)||0,lastSequence:(null==e?void 0:e.sequence)||(null==e?void 0:e.lastSequence)||0,fromAccount:(null==e?void 0:e.from)||(null==e?void 0:e.fromAccount)||"",messageForShow:Mr.core.common.getMessagePreviewText(null==e?void 0:e.type,null==e?void 0:e.payload),payload:(null==e?void 0:e.payload)||null,type:(null==e?void 0:e.type)||"",isRevoked:(null==e?void 0:e.isRevoked)||!1,cloudCustomData:(null==e?void 0:e.cloudCustomData)||"",onlineOnlyFlag:(null==e?void 0:e._onlineOnlyFlag)||!1,nick:(null==e?void 0:e.nick)||"",nameCard:(null==e?void 0:e.nameCard)||"",version:(null==e?void 0:e.version)||0,isPeerRead:(null==e?void 0:e.isPeerRead)||!1,revoker:(null==e?void 0:e.revoker)||null});function Dr(e){const{OuterConstant:t}=Mr.core;let s="";return 0===e?s=t.MSG_REMIND_ACPT_AND_NOTE:1===e?s=t.MSG_REMIND_DISCARD:2===e?s=t.MSG_REMIND_ACPT_NOT_NOTE:3===e&&(s=t.NOT_RECEIVE_OFFLINE_PUSH_EXCEPT_AT),s}function Rr(e){const{OuterConstant:t}=Mr.core;let s;return e.startsWith(t.CONV_C2C)&&(s=e.replace(t.CONV_C2C,"")),"@TLS#ERROR"===s||"@TLS#NOT_FOUND"===s}function Lr(e,t){const{helper:s}=Mr.core,o=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:`,o),o}class Nr{constructor(e){this.conversationID=e.conversationID||"",this.unreadCount=e.unreadCount||0,this.type=e.type||"",this.lastMessage=Or(e.lastMessage),this.peerReadTime=e.peerReadTime||0,this.groupAtInfoList=[],this.remark=e.remark||"",this.isPinned=e.isPinned||!1,this.messageRemindType=e.messageRemindType,this.markList=e.markList||[],this.customData=e.customData||"",this.conversationGroupList=e.conversationGroupList||[],this.draftText=e.draftText||"",this.userProfile=e.userProfile,this.groupProfile=e.groupProfile,this.subType=e.subType||"",this._isInfoCompleted=!1,this._init()}_init(){const{core:{OuterConstant:e,utils:{isUndefined:t}}}=Mr;t(this.userProfile)&&this.type===e.CONV_C2C?this.userProfile={}:t(this.groupProfile)&&this.type===e.CONV_GROUP&&(this.groupProfile={}),this.subType&&this.type===e.CONV_GROUP&&(this.subType=this.groupProfile.type||"")}updateUnreadCount(e){const{core:{OuterConstant:t,utils:{isUndefined:s}}}=Mr,{nextUnreadCount:o,isFromGetConversations:n,isUnreadC2CMessage:i}=e;s(o)||(this.subType!==t.GRP_AVCHATROOM?n&&this.type===t.CONV_GROUP||i&&this.type===t.CONV_C2C?this.unreadCount=o:this.unreadCount+=o:this.unreadCount=0)}updateLastMessage(e){this.lastMessage=Or(e)}reduceUnreadCount(){return this.unreadCount>=1&&(this.unreadCount-=1,!0)}isLastMessageRevoked(e){const{core:{OuterConstant:t}}=Mr,{sequence:s,time:o}=e;return this.type===t.CONV_C2C&&s===this.lastMessage.lastSequence&&o===this.lastMessage.lastTime||this.type===t.CONV_GROUP&&s===this.lastMessage.lastSequence}setLastMessageRevoked(e){this.lastMessage.isRevoked=e}setLastMessageRevoker(e){this.lastMessage.revoker=e}setDraftText(e){this.draftText=e}updateGroupAtInfoList(e){const{core:{common:{updateGroupAtInfo:t}}}=Mr;t(e,this.groupAtInfoList)}clearGroupAtInfoList(){this.groupAtInfoList.length=0}getProfileCompleted(){return this._isInfoCompleted}setProfileCompleted(){this._isInfoCompleted=!0}}var br,Gr;!function(e){e[e.OFF=0]="OFF",e[e.ON=1]="ON"}(br||(br={})),function(e){e[e.ONLY_CONVERSATIONID=1]="ONLY_CONVERSATIONID"}(Gr||(Gr={}));var wr;!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"}(wr||(wr={}));const Pr=0,Ur=1;var kr=new class{constructor(){this._name="ConversationDataHandler",this._totalUnreadCount=0,this._groupAtTipsList=[]}init(e){this._core=e;const{helper:t,notificationCenter:s,appStore:{conversationStore:o},constants:{WORKFLOW_NAME:n,WORKFLOW_STEP:i},InnerEvent:{SYNC_CONVERSATION_LIST:r,MESSAGE_PUSH:a,NEW_MESSAGE:c,MESSAGE_DELETED:u,MESSAGE_REVOKED:l,MESSAGE_MODIFIED:d,CONVERSATION_UPDATED:p,LOGOUT:h,DESTROY:g}}=e;this._conversationStore=o,t.registerWorkflowStep(n.SYNC_SERVER_INFO_AFTER_LOGIN,i.CONVERSATION_UPDATE_AFTER_UNREAD_SYNC_FINISHED,this._handleUnreadSyncFinished,this),t.registerWorkflowStep(n.SYNC_SERVER_INFO_AFTER_LOGIN,i.CONVERSATION_UPDATE_AFTER_GROUP_LIST_SYNC_FINISHED,this._handleGroupListSyncFinished,this),t.registerWorkflowStep(n.RECEIVE_C2C_NEW_MESSAGE,i.CREATE_OR_UPDATE_CONVERSATION_BY_RECEIVE_NEW_MESSAGE,this._handleNewMessage,this),t.registerWorkflowStep(n.RECEIVE_C2C_NEW_MESSAGE,i.CONVERSATION_UPDATE_AFTER_UNREAD_SYNC_FINISHED,this._handleUnreadSyncFinished,this),t.registerWorkflowStep(n.RECEIVE_GROUP_NEW_MESSAGE,i.CREATE_OR_UPDATE_CONVERSATION_BY_RECEIVE_NEW_MESSAGE,this._handleNewMessage,this),t.registerWorkflowStep(n.SYNC_SERVER_INFO_AFTER_RE_ONLINE,i.CONVERSATION_UPDATE_AFTER_UNREAD_SYNC_FINISHED,this._handleUnreadSyncFinished,this);const{InnerEventSubType:{GROUP_AT_TIPS:_}}=s;s.subscribeInnerEvent(r,this._handleConversationSynced,this),s.subscribeInnerEvent(c,this._handleNewMessage,this),s.subscribeInnerEvent(a,_,this._handleNewGroupAtTips,this),s.subscribeInnerEvent(u,this._handleMessageDeleted,this),s.subscribeInnerEvent(l,this._handleMessageRevoked,this),s.subscribeInnerEvent(d,this._handleMessageModified,this),s.subscribeInnerEvent(p,this._handleConversationUpdated,this),s.subscribeInnerEvent(h,this._reset,this),s.subscribeInnerEvent(g,this._dispose,this),console.log(`${this._name}.init`)}_handleConversationSynced(e){this.updateLocalConversationList({conversationUpdateFieldList:e.conversationUpdateFieldList||[],isFromGetConversations:!0,updateUnreadCount:!0}),this.emitConversationListUpdate()}_handleUnreadSyncFinished(e){const{constants:{WORKFLOW_STEP:t}}=this._core,{conversationUpdateFieldList:s=[],groupTipList:o=[],isUnreadC2CMessage:n}=e.result[t.UNREAD_MESSAGE_SYNC]||{};let i=!1;s.forEach((e=>{const{conversationID:t,unreadCount:s}=e,o=this.getLocalConversation(t);o&&o.unreadCount!==s&&(o.updateUnreadCount({nextUnreadCount:s,isUnreadC2CMessage:n}),i=!0)})),i&&this.emitConversationListUpdate(),this._handleGroupAtTipsSynced(o)}_handleGroupAtTipsSynced(e){var t;for(let s=0;s<e.length;s++)if(12===e[s].Event){if(null===(t=e[s].GroupTips[0].MsgBody)||void 0===t?void 0:t.TopicId)continue;this._handleNewGroupAtTips(e[s])}}_handleGroupListSyncFinished(e){var t;const{constants:{WORKFLOW_STEP:s}}=this._core,o=e.result[s.GROUP_LIST_SYNC]||[],{OuterConstant:{CONV_GROUP:n}}=this._core;let i=!1;for(let e=0;e<o.length;e++){const s=o[e],r=`${n}${s.groupID}`;if(!this.hasLocalConversation(r))continue;const a=this.getLocalConversation(r);a.groupProfile=JSON.parse(JSON.stringify(s)),a.lastMessage.lastSequence<s.nextMessageSeq&&(a.lastMessage.lastSequence=s.nextMessageSeq-1),a.subType||(a.subType=s.type),(null===(t=s._groupAtInfoList)||void 0===t?void 0:t.length)>0&&this._handleNewGroupAtTips({GroupTips:s._groupAtInfoList}),i=!0}i&&this.emitConversationListUpdate()}_handleNewMessage(e){const{conversationUpdateFieldList:t=[],isInstantMessage:s=!0,isUnreadC2CMessage:o=!1,updateUnreadCount:n=!0}=e.result||{};if(0===t.length)return;const{common:{isTopic:i}}=this._core;if(i(t[0].conversationID))return;this.updateLocalConversationList({conversationUpdateFieldList:t,isInstantMessage:s,isUnreadC2CMessage:o,isFromGetConversations:!1,updateUnreadCount:n});t.filter((e=>this._isConversationNeedShow(e.conversationID))).length>0&&this.emitConversationListUpdate()}_handleNewGroupAtTips(e){const{GroupTips:t=[]}=e;t.forEach((e=>{const{GroupAtTips:t,MsgBody:s,MsgRandom:o,ClientSeq:n}=e;let i={};t?i=this._convertGroupAtTipsKey(t):s?i=Object.assign({},this._convertGroupAtTipsKey(s)):e.groupAtType&&(i=Object.assign({},e)),i.__random=o,i.__sequence=n,this._groupAtTipsList.push(i)})),console.log(`${this._name}._handleNewGroupAtTips groupAtTipsList: ${JSON.stringify(this._groupAtTipsList)}`),this._updateGroupAtInfoList()}_convertGroupAtTipsKey(e){const{From_Account:t,GroupId:s,MsgSeq:o,GroupAtType:n}=e;return{from:t,groupID:s,sequence:o,groupAtType:n}}_updateGroupAtInfoList(){if(0===this._groupAtTipsList.length)return;const{common:e,OuterConstant:t}=this._core,s=e.getCurrentUserID();let o=!1;this._groupAtTipsList.forEach((e=>{const{groupID:n,from:i}=e;if(i!==s){const s=this.getLocalConversation(`${t.CONV_GROUP}${n}`);s&&(s.updateGroupAtInfoList(e),o=!0)}})),o&&this.emitConversationListUpdate(),this._groupAtTipsList.length=0}_handleMessageDeleted(e){var t,s;console.log(`${this._name}._handleMessageDeleted, conversationID:`,e);const{message:{messageDataHandler:o},OuterConstant:n}=this._core,i=(null==o?void 0:o.getLocalMessageList(e))||[];let r={};for(let e=(i.length||0)-1;e>=0;e--)if(!i[e].isDeleted){r=i[e];break}const a=this.getLocalConversation(e);if(!a)return;let c=!1;a.lastMessage.lastSequence===r.sequence&&a.lastMessage.lastTime===r.time||((null===(s=null===(t=this._core)||void 0===t?void 0:t.helper)||void 0===s?void 0:s.isEmpty(r))&&(r=void 0),a.updateLastMessage(r),c=!0),e.startsWith(n.CONV_C2C)&&this.updateUnreadCount(e),c&&(this.emitConversationListUpdate(),console.log(`${this._name}._handleMessageDeleted. update conversationID:${e} with lastMessage:`,a.lastMessage))}_handleMessageRevoked(e){const{messageList:t=[],updateUnreadCount:s=!0}=e;if(console.log(`${this._name}._handleMessageRevoked messageList:${t.length}`),0===t.length)return;let o=null,n=!1;t.forEach((e=>{o=this.getLocalConversation(e.conversationID),o&&(s&&o.reduceUnreadCount()&&(n=!0),o.isLastMessageRevoked({sequence:e.sequence,time:e.time})&&(o.setLastMessageRevoked(!0),o.setLastMessageRevoker(e.revoker),n=!0))})),n&&this.emitConversationListUpdate()}_handleMessageModified(e){console.log(`${this._name}._handleMessageModified`,JSON.stringify(e));const{conversationID:t,messageList:s}=e,o=this.getLocalConversation(t),{utils:{isEmpty:n},common:{getMessagePreviewText:i}}=this._core;if(n(o))return;const{lastMessage:r}=o;if(r){const e=(null==s?void 0:s[0])||{};r.lastTime===e.time&&r.lastSequence===e.sequence&&r.version!==e.version&&(r.type=e.type,r.payload=e.payload,r.messageForShow=i(e.type,e.payload),r.cloudCustomData=e.cloudCustomData,r.version=e.version,this.emitConversationListUpdate(),console.log(`${this._name} conversationID:${t} lastMessage updated`))}}_handleConversationUpdated(e){this.emitConversationListUpdate(null==e?void 0:e.needSort)}updateLocalConversationList(e){const{isFromGetConversations:t}=e,{newConversationList:s}=this._getTmpConversationListMapping(e);this._sortConversationList(),t||this._updateNewConversationProfile(s),console.log(`${this._name}.updateLocalConversationList newConversationList: ${s.length}`)}_getTmpConversationListMapping(e){const{OuterConstant:t}=this._core,{conversationUpdateFieldList:s,isFromGetConversations:o,isInstantMessage:n,isUnreadC2CMessage:i=!1,updateUnreadCount:r}=e,a=[],c=null==s?void 0:s.length;for(let e=0;e<c;e++){const c=new Nr(s[e]),{conversationID:u,type:l}=c;if(!Rr(u))if(this.hasLocalConversation(u)){const a=this.getLocalConversation(u);if(o){this.setLocalConversation(u,c),l===t.CONV_C2C?c.unreadCount=(null==a?void 0:a.unreadCount)||0:l===t.CONV_GROUP&&(c.groupProfile=JSON.parse(JSON.stringify(null==a?void 0:a.groupProfile)));continue}this._mergeConversationInfo({conversationID:u,tmpConversation:c,lastMessage:s[e].lastMessage,isFromGetConversations:o,isInstantMessage:n}),this._patchLastMessage({conversationID:u,lastMessage:s[e].lastMessage,isInstantMessage:n}),!0===r&&(null==a||a.updateUnreadCount({nextUnreadCount:c.unreadCount,isFromGetConversations:o,isUnreadC2CMessage:i}))}else a.push(c),this.setLocalConversation(u,c)}return{newConversationList:a}}_mergeConversationInfo(e){const{conversationID:t,tmpConversation:s,lastMessage:o,isFromGetConversations:n,isInstantMessage:i}=e,r=this.getLocalConversation(t),a=["unreadCount","allowType","adminForbidType","payload"];!1===i&&a.push("lastMessage"),n&&a.push("isPinned");const{utils:{isUndefined:c,isEmpty:u},common:{deepMerge:l}}=this._core;c(i)&&o&&null===(null==r?void 0:r.lastMessage.payload)&&(r.lastMessage.payload=o.payload),u(null==r?void 0:r.lastMessage.revoker)||(r.lastMessage.revoker=null);l(r,s,a,[null,void 0,"",0,NaN])}_patchLastMessage(e){const{OuterConstant:t}=this._core,{conversationID:s,lastMessage:o,isInstantMessage:n}=e,i=this.getLocalConversation(s);if(i&&o){const{payload:e,nameCard:s,nick:r,cloudCustomData:a=""}=o;n&&(e&&(i.lastMessage.payload=e),i.type===t.CONV_GROUP&&(i.lastMessage.nameCard=s,i.lastMessage.nick=r)),i.lastMessage.cloudCustomData!==a&&(i.lastMessage.cloudCustomData=a)}}_sortConversationList(){const{utils:{isEmpty:e}}=this._core,t=[...this._conversationStore.getConversationMap()],s=[],o=[],n=[],i=[];t.forEach((t=>{!0===t[1].isPinned?e(t[1].lastMessage.lastTime)?o.push(t):s.push(t):e(t[1].lastMessage.lastTime)?i.push(t):n.push(t)}));const r=s.sort(((e,t)=>t[1].lastMessage.lastTime-e[1].lastMessage.lastTime)).concat(o).concat(n.sort(((e,t)=>t[1].lastMessage.lastTime-e[1].lastMessage.lastTime))).concat(i);this._updateConversationMapFromList(r)}_updateNewConversationProfile(e){if(0===e.length)return;const t=[],s=[],{OuterConstant:{CONV_GROUP:o,CONV_C2C:n}}=this._core;e.forEach((e=>{const{conversationID:i,type:r}=e;if(r===n){const e=i.replace(n,"");t.push(e)}else if(r===o){const e=i.replace(o,"");s.push(e)}})),t.length>0&&this._updateC2CConversation(t),s.length>0&&this._updateGroupConversation(s)}_updateC2CConversation(e){var t;const{OuterConstant:{CONV_C2C:s},appStore:{userStore:o},user:n}=this._core;let i=!1;null===(t=n.userProfile)||void 0===t||t.getUserProfile({userIDList:e}).then((e=>{((null==e?void 0:e.data)||[]).forEach((e=>{var t;const{userID:n}=e,r=this.getLocalConversation(`${s}${n}`);if(r){const s=(null===(t=o.getFriend(n))||void 0===t?void 0:t.remark)||"";r.remark=s,r.userProfile=e,i=!0}})),i&&this.emitConversationListUpdate()})).catch((e=>{}))}_updateGroupConversation(e){const{OuterConstant:{CONV_GROUP:t},appStore:{groupStore:s}}=this._core;let o=!1;e.forEach((e=>{const n=s.getGroup(e),i=this.getLocalConversation(`${t}${e}`);n&&i&&(i.groupProfile=n,o=!0)})),o&&this.emitConversationListUpdate()}_isConversationNeedShow(e){const t=this.getLocalConversation(e);if(this._core.utils.isUndefined(t))return!0;const{OuterConstant:s}=this._core,o=t.type===s.CONV_TOPIC,n=t.type===s.CONV_GROUP&&t.subType===s.GRP_ROOM,i=t.type===s.CONV_GROUP&&t.subType===s.GRP_LIVE;return!(o||n||i)}updateUnreadCount(e,t=!0){var s,o;let n=!1;const i=this.getLocalConversation(e),r=null===(o=null===(s=this._core)||void 0===s?void 0:s.message.messageDataHandler)||void 0===o?void 0:o.getLocalMessageList(e);if(!i)return n;const a=i.unreadCount,c=null==r?void 0:r.filter((e=>!e.isRead&&!e._onlineOnlyFlag&&!e.isDeleted)).length;return console.log(`${this._name}._updateUnreadCount conversationID:${e} currentUnreadCount:${a} newUnreadCount:${c}`),a!==c&&(i.unreadCount=c,n=!0,!0===t&&this.emitConversationListUpdate()),n}emitConversationListUpdate(e=!1){e&&this._sortConversationList();const{OuterEvent:{CONVERSATION_LIST_UPDATED:t}}=this._core,s=this.getLocalConversationList();this._emitEvent({name:t,data:s}),this._emitTotalUnreadCountUpdate()}_emitTotalUnreadCountUpdate(){var e;const t=this.getTotalUnreadMessageCount();this._totalUnreadCount!==t&&(console.log(`${this._name}._emitTotalUnreadCountUpdate from ${this._totalUnreadCount} to ${t}`),this._totalUnreadCount=t,this._emitEvent({name:null===(e=this._core)||void 0===e?void 0:e.OuterEvent.TOTAL_UNREAD_MESSAGE_COUNT_UPDATED,data:t}))}_emitEvent(e){var t;null===(t=this._core)||void 0===t||t.notificationCenter.emitOuterEvent(e.name,e)}getTotalUnreadMessageCount(){const{OuterConstant:e}=this._core,t=this.getLocalConversationList();let s=0;return t.forEach((t=>{t.type!==e.CONV_SYSTEM&&(""!==t.messageRemindType&&t.messageRemindType!==e.MSG_REMIND_ACPT_AND_NOTE||(s+=t.unreadCount))})),s}getLocalConversationList(){return[...this._conversationStore.getConversationMap().values()].filter((e=>this._isConversationNeedShow(e.conversationID)))}hasLocalConversation(e){return this._conversationStore.getConversationMap().has(e)}getLocalConversation(e){return this._conversationStore.getConversationMap().get(e)}setLocalConversation(e,t){return this._conversationStore.getConversationMap().set(e,t)}deleteLocalConversation(e){this._conversationStore.getConversationMap().delete(e)}_updateConversationMapFromList(e){this._clearConversationMap();for(const[t,s]of e)this.setLocalConversation(t,s)}_clearConversationMap(){this._conversationStore.getConversationMap().clear()}patchMessageRemindType(e,t){let s=!1;e.forEach((e=>{const o=this.getLocalConversation(e);(null==o?void 0:o.messageRemindType)!==t&&(o.messageRemindType=t,s=!0)})),console.log(`${this._name}.patchMessageRemindType conversationIDList:${e} messageRemindType:${t} hasUpdated:${s}`),s&&this.emitConversationListUpdate()}markMessageAsRead(e){const{message:{messageDataHandler:t}}=this._core,{conversationID:s,lastReadTime:o=0,lastReadSequence:n=0}=e,i=null==t?void 0:t.getLocalMessageList(s);if(0===i.length)return;const{length:r}=i;for(let e=r-1;e>=0;e--){const t=i[e],s=o&&t.time>o,r=n&&t.sequence>n;if(!s&&!r){if("in"===t.flow&&t.isRead)break;t.setIsRead(!0)}}}appendToPinnedConversation(e){const t=[...this._conversationStore.getConversationMap().entries()],s=t.findIndex((e=>!1===e[1].isPinned));t.splice(s,0,[e.conversationID,e]),this._updateConversationMapFromList(t),this.emitConversationListUpdate()}_reset(){this._clearConversationMap(),this._totalUnreadCount=0,this._groupAtTipsList=[]}_dispose(){const{notificationCenter:e,InnerEvent:{NEW_MESSAGE:t,MESSAGE_DELETED:s,MESSAGE_REVOKED:o,MESSAGE_MODIFIED:n,CONVERSATION_UPDATED:i,LOGOUT:r,DESTROY:a,SYNC_CONVERSATION_LIST:c}}=this._core,{InnerEventSubType:{GROUP_AT_TIPS:u}}=e;e.unSubscribeInnerEvent(t,this._handleNewMessage,this),e.unSubscribeInnerEvent(t,u,this._handleNewGroupAtTips,this),e.unSubscribeInnerEvent(s,this._handleMessageDeleted,this),e.unSubscribeInnerEvent(o,this._handleMessageRevoked,this),e.unSubscribeInnerEvent(n,this._handleMessageModified,this),e.unSubscribeInnerEvent(i,this._handleConversationUpdated,this),e.unSubscribeInnerEvent(c,this._handleConversationSynced,this),e.unSubscribeInnerEvent(r,this._reset,this),e.unSubscribeInnerEvent(a,this._dispose,this)}};var Fr=new class{constructor(){this._name="GetConversationList"}init(e){this._core=e;const{helper:t}=e;t.registerApi({apiName:"getConversationList",context:this})}getConversationList(e){return h(this,void 0,void 0,(function*(){return{code:0,data:{conversationList:this._getConversationList(e),isSyncCompleted:this._core.conversation.syncConversationHandler.isSyncCompleted()}}}))}_getConversationList(e){const{utils:{isUndefined:t,isArray:s,isPlainObject:o}}=this._core;if(t(e))return kr.getLocalConversationList();if(s(e)){if(0===e.length)return[];return kr.getLocalConversationList().filter((t=>e.includes(t.conversationID)))}if(o(e)){const{type:t,markType:s,groupName:o,hasUnreadCount:n,hasGroupAtInfo:i}=e;return kr.getLocalConversationList().filter((e=>this._filterType(e,t)&&this._filterMarkType(e,s)&&this._filterGroupName(e,o)&&this._filterUnreadCount(e,n)&&this._filterGroupAtInfo(e,i)))}return[]}_filterType(e,t){const{OuterConstant:s}=this._core;return t!==s.CONV_C2C&&t!==s.CONV_GROUP||e.type===t}_filterGroupName(e,t){const{utils:{isString:s}}=this._core;return!s(t)||(""===t?0===e.conversationGroupList.length:e.conversationGroupList.includes(t))}_filterMarkType(e,t){const{utils:{isNumber:s}}=this._core;return!s(t)||(0===t?0===e.markList.length:e.markList.includes(t))}_filterUnreadCount(e,t){let s=!0;return!0===t?s=e.unreadCount>=1:!1===t&&(s=0===e.unreadCount),s}_filterGroupAtInfo(e,t){let s=!0;return!0===t?s=e.groupAtInfoList.length>=1:!1===t&&(s=0===e.groupAtInfoList.length),s}};var $r=new class{constructor(){this._name="GetC2CMessageRemindType"}init(e){this._core=e}get(e){return h(this,void 0,void 0,(function*(){try{const{common:t}=this._core,s=yield function(e,t){return h(this,void 0,void 0,(function*(){const{toAccount:s,userIDList:o}=e,n={To_Account:s,Peer_Account:o};return t.common.buildAndSendPacket({servcmd:"openim.get_c2c_peer_mute_notifications",data:n})}))}({toAccount:t.getCurrentUserID(),userIDList:e},this._core),{MuteNotificationsList:o=[]}=s||{};o.forEach((e=>{const{Peer_Account:t,MuteNotifications:s}=e,o=`${this._core.OuterConstant.CONV_C2C}${t}`,n=Dr(s);kr.patchMessageRemindType([o],n)}))}catch(e){console.error(`${this._name}.get fail:`,e)}}))}};var qr=new class{constructor(){this._name="GetGroupMessageRemindType"}init(e){this._core=e}get(e){return h(this,void 0,void 0,(function*(){if(0!==e.length)try{const t=yield function(e,t){return h(this,void 0,void 0,(function*(){const{groupIDList:s,responseFilter:o}=e,n={GroupIdList:s,ResponseFilter:o};return t.common.buildAndSendPacket({servcmd:"group_open_http_svc.get_group_self_member_info",data:n})}))}({groupIDList:e,responseFilter:{MemberInfoFilter:["MsgFlag"]}},this._core),{GroupInfo:s=[]}=t||{};s.forEach((e=>{var t;const{GroupId:s,MemberList:o}=e,n=(null===(t=o[0])||void 0===t?void 0:t.MsgFlag)||"",i=`${this._core.OuterConstant.CONV_GROUP}${s}`;kr.patchMessageRemindType([i],n)}))}catch(e){console.error(`${this._name}.get fail:`,e)}}))}};var xr=new class{constructor(){this._name="GetConversationProfile"}init(e){this._core=e;const{helper:t}=e;t.registerApi({apiName:"getConversationProfile",context:this})}getConversationProfile(e){return h(this,void 0,void 0,(function*(){const{OuterConstant:{CONV_C2C:t,CONV_GROUP:s,GRP_AVCHATROOM:o},appStore:{groupStore:n},utils:{isEmpty:i}}=this._core,r={code:0,data:{}};let a=kr.getLocalConversation(e);if(Ar(e))return r.data.conversation=a,r;let c=!1;const u=yr(e)?t:s;if(i(a)&&(c=!0,a=new Nr({conversationID:e,type:u})),console.log(`${this._name}.getConversationProfile conversationID:${e} isNewConversation:${c}`),r.data.conversation=a,null==a?void 0:a.getProfileCompleted())return r;if(u===t){const s=e.replace(t,"");yield this._handleC2CConversation(a,s),c&&(yield $r.get([s]))}if(u===s){const t=e.replace(s,"");if(!n.getGroup(t))return r;yield this._handleGroupConversation(a,t),c&&a.groupProfile.type!==o&&(yield qr.get([t]))}return r}))}_handleC2CConversation(e,t){return h(this,void 0,void 0,(function*(){var s,o;const{user:n,helper:i,utils:{isEmpty:r},appStore:{conversationStore:a,userStore:c}}=this._core,{conversationID:u}=e,l=yield null===(s=n.userProfile)||void 0===s?void 0:s.getUserProfile({userIDList:[t]});if(0===(null==l?void 0:l.data.length))throw new i.ChatError({code:wr.USER_OR_GRP_NOT_FOUND});e.userProfile=null==l?void 0:l.data[0];const d=null===(o=c.getFriend(t))||void 0===o?void 0:o.remark;r(d)||e.remark===d||(e.remark=d),e.setProfileCompleted();const p=kr.hasLocalConversation(u);console.log(`${this._name}._handleC2CConversation conversationID:${u} hasLocalConversation: ${p}`),p?a.updateConversation(u,e):kr.appendToPinnedConversation(e)}))}_handleGroupConversation(e,t){return h(this,void 0,void 0,(function*(){const{apiMap:{getGroupProfile:s},appStore:{conversationStore:o}}=this._core,{conversationID:n}=e,i=yield s({groupID:t});e.groupProfile=null==i?void 0:i.data.group,e.setProfileCompleted();const r=kr.hasLocalConversation(n);console.log(`${this._name}._handleGroupConversation conversationID:${n} hasLocalConversation: ${r}`),r?o.updateConversation(n,e):kr.appendToPinnedConversation(e)}))}};var Vr=new class{init(e){const{helper:t}=e;t.registerApi({apiName:"getTotalUnreadMessageCount",context:this})}getTotalUnreadMessageCount(){return kr.getTotalUnreadMessageCount()}};var Br=new class{constructor(){this._serverGroupConversationLastReadSeqMap=new Map,this._name="SetMessageRead"}init(e){this._core=e;const{helper:t,common:{isTopic:s},notificationCenter:o,InnerEvent:{MESSAGE_PUSH:n},InnerEventSubType:{ALL_MESSAGE_READ:i}}=e;t.registerApi({apiName:"setMessageRead",context:this,matcher:e=>!s(e[0].conversationID)}),t.registerApi({apiName:"setAllMessageRead",context:this}),o.subscribeInnerEvent(n,i,this._handleAllMessageRead,this)}handleC2CMessageReadSync(e){const{helper:{isEmpty:t},OuterConstant:s}=this._core;e.forEach((e=>{const{ReadC2cMsgNotify:o}=e;if(!t(o)){const{UinPairReadArray:e=[]}=o;e.forEach((e=>{const{From_Account:t,LastReadTime:o}=e,n=`${s.CONV_C2C}${t}`;console.log(`${this._name}.handleC2CMessageReadSync conversationID:${n} lastReadTime:${o}`),kr.markMessageAsRead({conversationID:n,lastReadTime:o}),kr.updateUnreadCount(n)}))}}))}handleGroupMessageReadSync(e){const{OuterConstant:t,utils:{isUndefined:s}}=this._core;e.forEach((e=>{const{GroupReadInfoArray:o}=e.MsgBody;s(o)||o.forEach((e=>{const{GroupId:s,LastReadMsgSeq:o}=e,n=`${t.CONV_GROUP}${s}`;console.log(`${this._name}.handleGroupMessageReadSync conversationID:${n} lastReadSequence:${o}`),kr.markMessageAsRead({conversationID:n,lastReadSequence:o}),kr.updateUnreadCount(n),this._clearGroupAtInfoList(n)}))}))}setMessageRead(e){return h(this,void 0,void 0,(function*(){var t,s;const{OuterConstant:o}=this._core,{conversationID:n}=e,i={code:0,data:{}},r=kr.getLocalConversation(n);if(console.log(`${this._name}.setMessageRead conversationID:${n} unreadCount:${(null==r?void 0:r.unreadCount)||0}`),!r)return i;const a=!(null===(s=null===(t=this._core)||void 0===t?void 0:t.helper)||void 0===s?void 0:s.isEmpty(r.groupAtInfoList));if(r.type===o.CONV_GROUP&&a&&this._deleteGroupAtTips(n),0===r.unreadCount)return i;const{ssoLog:c,helper:{ChatError:u}}=this._core,l=c.createSSOLogData({method:"setMessageRead"});l.setLogInfo({message:`conversationID:${n}`});try{if(r.type===o.CONV_C2C){const e=this._getLocalMessageMaxTime(r);yield this._setC2CMessageRead(n,e),l.setLogInfo({moreMessage:`lastMessageTime:${e}`}).end()}if(r.type===o.CONV_GROUP){const e=this._getLocalMessageMaxSequence(r);yield this._setGroupMessageRead(n,e),l.setLogInfo({moreMessage:`lastMessageSequence:${e}`}).end()}}catch(e){const{errorCode:t,errorInfo:s}=e,o=new u({functionName:"setMessageRead",code:t,message:s});throw l.setError(o).end(),o}return r.type===o.CONV_SYSTEM&&(r.unreadCount=0),kr.emitConversationListUpdate(),i}))}setAllMessageRead(){return h(this,arguments,void 0,(function*(e={}){const{OuterConstant:{READ_ALL_MSG:t},ssoLog:s}=this._core,o=s.createSSOLogData({method:"setAllMessageRead"});e.scope||(e.scope=t);const{scope:n}=e,i=this._generateSetAllMessageReadRequestData(n);if(i.allC2CMessageReadStatus===Pr&&0===i.groupMessageReadInfoList.length)return{code:0};try{const e=yield function(e){return h(this,void 0,void 0,(function*(){const{allC2CMessageReadStatus:t,groupMessageReadInfoList:s}=e,o={C2CReadAllMsg:t,GroupReadInfo:s};return Mr.core.common.buildAndSendPacket({servcmd:"openim.read_all_unread_msg",data:o})}))}(i);if(e){const{GroupReadInfoArray:t,C2CReadAllMsg:s}=e,i=this._parseGroupReadInfo(t);this._updateAllConversationReadStatus({allC2CMessageReadStatus:s})>0&&kr.emitConversationListUpdate(),o.setLogInfo({message:`scope:${n} failureGroups:${JSON.stringify(i)}`}).end()}return{code:0}}catch(e){const{errorCode:t}=e,s=new this._core.helper.ChatError({functionName:"setAllMessageRead",code:t});throw o.setError(s).end(),s}}))}_handleAllMessageRead(e){const{GroupReadInfoArray:t,C2CReadAllMsg:s}=e;this._parseGroupReadInfo(t);this._updateAllConversationReadStatus({allC2CMessageReadStatus:s})>0&&kr.emitConversationListUpdate()}_updateAllConversationReadStatus(e){const{OuterConstant:{CONV_C2C:t,CONV_GROUP:s},appStore:o}=this._core,n=o.conversationStore.getConversationMap(),{allC2CMessageReadStatus:i}=e;let r=0;for(const[e,o]of n)if(o.unreadCount>=1){if(i===Ur&&o.type===t){const t=this._getLocalMessageMaxTime(o);kr.markMessageAsRead({conversationID:e,lastReadTime:t})}else if(o.type===s){const t=e.replace(s,"");if(this._serverGroupConversationLastReadSeqMap.has(t)){const s=this._serverGroupConversationLastReadSeqMap.get(t);kr.markMessageAsRead({conversationID:e,lastReadSequence:s})}}kr.updateUnreadCount(e,!1)&&(r+=1)}return r}_generateSetAllMessageReadRequestData(e){const{OuterConstant:{CONV_C2C:t,CONV_GROUP:s,READ_ALL_C2C_MSG:o},appStore:n}=this._core,i={allC2CMessageReadStatus:Pr,groupMessageReadInfoList:[]},r=n.conversationStore.getConversationMap();for(const[,n]of r){const{type:r,unreadCount:a}=n;if(this._shouldSetAllMessageRead({scope:e,type:r,unreadCount:a}))if(r===t&&i.allC2CMessageReadStatus===Pr){if(i.allC2CMessageReadStatus=Ur,e===o)break}else if(r===s){const e=this._getLocalMessageMaxSequence(n),{groupID:t}=n.groupProfile;i.groupMessageReadInfoList.push({GroupId:t,MsgSeq:e})}}return i}_parseGroupReadInfo(e){const{utils:{isUndefined:t}}=this._core,s=[];return null==e||e.forEach((e=>{const{GroupId:o,MsgSeq:n,RetCode:i,LastReadMsgSeq:r}=e;t(i)?this._serverGroupConversationLastReadSeqMap.set(o,r):(this._serverGroupConversationLastReadSeqMap.set(o,n),0!==i&&s.push(`${o}-${n}-${i}`))})),s}_deleteGroupAtTips(e){return h(this,void 0,void 0,(function*(){console.log(`${this._name}._deleteGroupAtTips conversationID:${e}`);const t=kr.getLocalConversation(e);if(!t)return;const s=(null==t?void 0:t.groupAtInfoList)||[];if(0!==s.length)try{const{common:{getCurrentUserID:t,isCommunity:o},OuterConstant:{CONV_GROUP:n,CONV_AT_ALL:i}}=this._core;let r=[...s];if(o({groupID:e.replace(n,"")})&&(r=s.filter((e=>!e.atTypeArray.includes(i))),0===r.length))return void this._clearGroupAtInfoList(e,!1);const a=r.map((e=>({From_Account:e.from,To_Account:t(),MsgSeq:e.__sequence,MsgRandom:e.__random,GroupId:e.groupID})));yield function(e,t){return h(this,void 0,void 0,(function*(){const{messageListToDelete:s}=e,o={DelMsgList:s};return t.common.buildAndSendPacket({servcmd:"openim.deletemsg",data:o})}))}({messageListToDelete:a},this._core),console.log(`${this._name}._deleteGroupAtTips ok. count:${s.length}`),this._clearGroupAtInfoList(e)}catch(e){console.error(`${this._name}._deleteGroupAtTips fail:`,e)}}))}_clearGroupAtInfoList(e,t=!0){const s=kr.getLocalConversation(e);s&&(s.groupAtInfoList.length>0&&(s.clearGroupAtInfoList(),console.log(`${this._name}._clearGroupAtInfoList conversationID:${e} needEmitConversationUpdate:${t}`)),t&&kr.emitConversationListUpdate())}_getLocalMessageMaxTime(e){var t;const{conversationID:s}=e,o=this._core.message.messageDataHandler.getLocalMessageList(s),n=Math.max(...o.map((e=>e.time)));let i=(null===(t=null==e?void 0:e.lastMessage)||void 0===t?void 0:t.lastTime)||0;return n>i&&(console.log(`${this._name}._getLocalMessageMaxTime update lastMessageTime from ${i} to ${n}`),i=n),i}_getLocalMessageMaxSequence(e){var t;const{conversationID:s}=e,o=this._core.message.messageDataHandler.getLocalMessageList(s),n=Math.max(...o.map((e=>e.sequence)));let i=(null===(t=null==e?void 0:e.lastMessage)||void 0===t?void 0:t.lastSequence)||0;return n>i&&(console.log(`${this._name}._getLocalMessageMaxSequence update lastMessageSequence from ${i} to ${n}`),i=n),i}_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}`),kr.markMessageAsRead({conversationID:e,lastReadTime:t}),kr.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(e,t){return h(this,void 0,void 0,(function*(){const{groupID:s,lastMessageSequence:o}=e,n={GroupId:s,MsgReadedSeq:o};return t.common.buildAndSendPacket({servcmd:"group_open_http_svc.msg_read_report",data:n})}))}({groupID:e.replace("GROUP",""),lastMessageSequence:t},this._core),console.log(`${this._name}._setGroupMessageRead ok, lastReadSequence:${t}`),kr.markMessageAsRead({conversationID:e,lastReadSequence:t}),kr.updateUnreadCount(e)}catch(e){throw console.warn(`${this._name}._setGroupMessageRead fail:`,e),e}}))}_shouldSetAllMessageRead(e){const{OuterConstant:{CONV_C2C:t,CONV_GROUP:s,READ_ALL_MSG:o,READ_ALL_C2C_MSG:n,READ_ALL_GROUP_MSG:i}}=this._core,{type:r,scope:a,unreadCount:c}=e;return!(c<=0)&&(!(r!==t||![o,n].includes(a))||!(r!==s||![o,i].includes(a)))}};var jr=new class{constructor(){this._name="PinConversation"}init(e){this._core=e;const{helper:t}=e;t.registerApi({apiName:"pinConversation",context:this})}handleConversationPinned(e,t){const{utils:{isArray:s}}=this._core;if(!s(e))return;const{OuterConstant:o}=this._core;let n=!1;e.forEach((e=>{const{Type:s,To_Account:i,GroupId:r}=e;let a;1===s?a=kr.getLocalConversation(`${o.CONV_C2C}${i}`):2===s&&(a=kr.getLocalConversation(`${o.CONV_GROUP}${r}`)),a&&(console.log(`${this._name}.handleConversationPinned conversationID:${a.conversationID} localPinned:${a.isPinned} remotePinned:${t}`),t&&!a.isPinned&&(a.isPinned=!0,n=!0),!t&&a.isPinned&&(a.isPinned=!1,n=!0))})),n&&kr.emitConversationListUpdate(!0)}pinConversation(e){return h(this,void 0,void 0,(function*(){const{OuterConstant:t,common:s,ssoLog:o,helper:{ChatError:n}}=this._core,{conversationID:i,isPinned:r}=e,a={code:0,data:{conversationID:i}},c=kr.getLocalConversation(i);if(c&&c.isPinned===r)return a;if(Ar(i))return c&&(c.isPinned=r),kr.emitConversationListUpdate(!0),a;const u=o.createSSOLogData({method:"pinConversation"});u.setLogInfo({message:`conversationID:${i} isPinned:${r}`});try{let e=null;yr(i)?e={Type:1,To_Account:i.replace(t.CONV_C2C,"")}:Tr(i)&&(e={Type:2,GroupId:i.replace(t.CONV_GROUP,"")});const o=yield function(e,t){return h(this,void 0,void 0,(function*(){const{fromAccount:s,operationType:o,itemList:n}=e,i={From_Account:s,OperationType:o,RecentContactItem:n};return t.common.buildAndSendPacket({servcmd:"recentcontact.top",data:i})}))}({fromAccount:s.getCurrentUserID(),operationType:!0===r?1:2,itemList:[e]},this._core);if(u.end(),console.log(`${this._name}.pinConversation ok, conversationID:${i} isPinned:${r}.`),o){if(c)c.isPinned!==r&&(c.isPinned=r);else{const e=new Nr({conversationID:i,type:yr(i)?t.CONV_C2C:t.CONV_GROUP,isPinned:r});kr.setLocalConversation(i,e)}kr.emitConversationListUpdate(!0)}return a}catch(e){const{errorCode:t,errorInfo:s}=e,o=new n({functionName:"pinConversation",code:t,message:s});throw u.setError(o).end(),console.error(`${this._name}.pinConversation fail:`,o),o}}))}};var Kr=new class{constructor(){this._name="DeleteConversation"}init(e){this._core=e;const{helper:t}=e;t.registerApi({apiName:"deleteConversation",context:this})}handleConversationDeleted(e){const{utils:{isArray:t}}=this._core;if(!t(e))return;const{OuterConstant:s}=this._core,o=[];e.forEach((e=>{const{Type:t,Peer_Account:n,GroupId:i}=e;1===t&&o.push(`${s.CONV_C2C}${n}`),2===t&&o.push(`${s.CONV_GROUP}${i}`)})),console.log(`${this._name}.handleConversationDeleted conversationIDList:${o}`),this._deleteLocalConversationList(o)}deleteConversation(e){return h(this,void 0,void 0,(function*(){const{utils:{isString:t}}=this._core;if(t(e))return console.log(`${this._name}.deleteConversation conversationID:${e}`),void(yield this._deleteConversation({conversationIDList:[e],flag:Gr.ONLY_CONVERSATIONID}));const s=Object.assign({},e);s.conversationIDList.length>100&&(s.conversationIDList=s.conversationIDList.slice(0,100)),yield this._deleteConversation(s)}))}_deleteConversation(e){return h(this,void 0,void 0,(function*(){const{conversationIDList:t,clearHistoryMessage:s=!0,flag:o=0}=e,{ssoLog:n,helper:{ChatError:i}}=this._core,r=`conversationIDList:${t} clearHistoryMessage:${s}`,a=n.createSSOLogData({method:"deleteConversation"});a.setLogInfo({message:r}),console.log(`${this._name}._deleteConversation ${r}`);try{const e=yield Promise.all([this._deleteConversationFromLocal(t),this._deleteConversationFromServer(t,s)]),n=[...e[0],...e[1]];if(0===n.length)throw new this._core.helper.ChatError({code:wr.CONV_NOT_FOUND});return a.end(),console.log(`${this._name}._deleteConversation ok.`),{code:0,data:o===Gr.ONLY_CONVERSATIONID?{conversationID:n[0]}:{conversationIDList:n}}}catch(e){const{errorCode:t,errorInfo:s}=e,o=new i({functionName:"deleteConversation",code:t,message:s});throw a.setError(o).end(),console.error(`${this._name}._deleteConversation fail:`,o),o}}))}_deleteConversationFromLocal(e){const{OuterConstant:t}=this._core;return e.filter((e=>{var s;if(!kr.hasLocalConversation(e))return!1;const o=null===(s=kr.getLocalConversation(e))||void 0===s?void 0:s.type;return o!==t.CONV_GROUP||this._hasLocalGroup(e)?o===t.CONV_SYSTEM&&(this._deleteLocalConversation(e),!0):(this._deleteLocalConversation(e),!0)}))}_deleteConversationFromServer(e,t){return h(this,void 0,void 0,(function*(){const{OuterConstant:s,common:o}=this._core,n={fromAccount:o.getCurrentUserID(),conversationList:[],clearHistoryMessage:t?1:0};if(e.forEach((e=>{var t;if(kr.hasLocalConversation(e)){const o=(null===(t=kr.getLocalConversation(e))||void 0===t?void 0:t.type)||"",i=e.replace(o,"");o===s.CONV_C2C?n.conversationList.push({To_Account:i,Type:1}):o===s.CONV_GROUP&&this._hasLocalGroup(e)&&n.conversationList.push({ToGroupid:i,Type:2})}})),0===n.conversationList.length)return[];const i=yield function(e,t){return h(this,void 0,void 0,(function*(){const{fromAccount:s,conversationList:o,clearHistoryMessage:n}=e,i={From_Account:s,ContactItem:o,ClearRamble:n};return t.common.buildAndSendPacket({servcmd:"recentcontact.batch_delete",data:i})}))}(n,this._core);if(i){const{ResultItem:e=[]}=i,t=[];return e.length>0&&e.forEach((e=>{if(0===e.ResultCode){const o=1===e.type?`${s.CONV_C2C}${e.To_Account}`:`${s.CONV_GROUP}${e.ToGroupid}`;t.push(o)}})),this._deleteLocalConversationList(t),t}return[]}))}_deleteLocalConversationList(e){let t=!1;e.forEach((e=>{kr.hasLocalConversation(e)&&(this._deleteLocalConversation(e,!1),t=!0)})),console.log(`${this._name}._deleteLocalConversationList isUpdate:${t}`),t&&kr.emitConversationListUpdate()}_deleteLocalConversation(e,t=!0){const s=kr.hasLocalConversation(e);console.log(`${this._name}._deleteLocalConversation conversationID:${e} has:${s}`),s&&(kr.deleteLocalConversation(e),this._deleteConversationLocalMessage(e),t&&kr.emitConversationListUpdate())}_hasLocalGroup(e){const{OuterConstant:{CONV_GROUP:t},appStore:{groupStore:s}}=this._core,o=e.replace(t,"");return!!s.getGroup(o)}_deleteConversationLocalMessage(e){console.log(`${this._name}._deleteConversationLocalMessage conversationID:${e}`),this._core.message.messageDataHandler.deleteConversationMessageList(e)}};var Hr=new class{constructor(){this._name="SetConversationDraft"}init(e){this._core=e;const{helper:t}=e;t.registerApi({apiName:"setConversationDraft",context:this})}setConversationDraft(e){return h(this,void 0,void 0,(function*(){const{conversationID:t,draftText:s}=e;if(console.log(`${this._name} conversationID:${t} draftText:${s}`),!kr.hasLocalConversation(t))throw new this._core.helper.ChatError({code:wr.CONV_NOT_FOUND});const o=kr.getLocalConversation(t);return null==o||o.setDraftText(s),kr.emitConversationListUpdate(),{code:0,data:{conversation:o}}}))}};var Wr=new class{constructor(){this._name="SetC2CMessageRemindType"}init(e){this._core=e}set(e,t){return h(this,void 0,void 0,(function*(){e.length>30&&(console.warn(`${this._name}.set userIDList length:${e.length} exceeds limit 30`),e.splice(30));const s=function(){const{MSG_REMIND_ACPT_AND_NOTE:e,MSG_REMIND_DISCARD:t,MSG_REMIND_ACPT_NOT_NOTE:s}=Mr.core.OuterConstant;return{[e]:0,[t]:1,[s]:2}}()[t],o=yield function(e,t){return h(this,void 0,void 0,(function*(){const{userIDList:s,receiveMessageOption:o}=e,n={Peer_Account:s,Mute_Notifications:o};return t.common.buildAndSendPacket({servcmd:"openim.set_c2c_peer_mute_notifications",data:n})}))}({userIDList:e,receiveMessageOption:s},this._core),{ErrorList:n=[]}=o||{},i=[];n.forEach((t=>{const{Peer_Account:s,ErrorCode:o}=t;i.push({userID:s,code:o});const n=e.indexOf(s);n>-1&&e.splice(n,1)}));const r=[],a=[],{OuterConstant:c}=this._core;return e.forEach((e=>{a.push(`${c.CONV_C2C}${e}`),r.push({userID:e})})),kr.patchMessageRemindType(a,t),{code:0,data:{successUserIDList:r,failureUserIDList:i}}}))}};var Yr=new class{constructor(){this._name="SetGroupMessageRemindType"}init(e){this._core=e}set(e,t){return h(this,void 0,void 0,(function*(){const{common:{getCurrentUserID:s,isTopic:o},OuterConstant:n}=this._core;if(yield function(e,t){return h(this,void 0,void 0,(function*(){const{groupID:s,userID:o,receiveMessageOption:n}=e,i={GroupId:s,Member_Account:o,MsgFlag:n};return t.common.buildAndSendPacket({servcmd:"group_open_http_svc.modify_group_member_info",data:i})}))}({groupID:e,userID:s(),receiveMessageOption:t},this._core),!o(e)){const s=`${n.CONV_GROUP}${e}`;kr.patchMessageRemindType([s],t)}return{code:0,data:{groupID:e,messageRemindType:t}}}))}};var zr=new class{constructor(){this._name="SetMessageRemindType"}init(e){this._core=e;const{helper:t}=e;t.registerApi({apiName:"setMessageRemindType",context:this})}handleC2CMessageRemindTypeSync(e){const{helper:{isEmpty:t},OuterConstant:s}=this._core;e.forEach((e=>{const{MuteNotificationsSync:o}=e;if(!t(o)){const{To_Account:e,MuteNotifications:t}=o,n=e.map((e=>`${s.CONV_C2C}${e}`)),i=Dr(t);console.log(`${this._name}.handleC2CMessageRemindTypeSync conversationIDList:${n} messageRemindType:${i}`),kr.patchMessageRemindType(n,i)}}))}setMessageRemindType(e){return h(this,void 0,void 0,(function*(){const t="setMessageRemindType",{groupID:s,userIDList:o,messageRemindType:n}=e,{helper:i,utils:{isUndefined:r}}=this._core;try{if(!r(s)){console.log(`${this._name}.${t} groupID:${s} messageRemindType:${n}`);return yield Yr.set(s,n)}if(!r(o)){console.log(`${this._name}.${t} userIDList:${o} messageRemindType:${n}`);return yield Wr.set(o,n)}throw new i.ChatError({functionName:t,message:"userIDList or groupID is required"})}catch(e){const s=new i.ChatError({functionName:t,code:null==e?void 0:e.errorCode,message:null==e?void 0:e.errorInfo});throw console.error(`${this._name}.${t} fail:`,s),s}}))}};var Jr=new class{init(e){console.log("ConversationAction.init"),this._core=e,Fr.init(e),xr.init(e),Vr.init(e),Br.init(e),jr.init(e),Kr.init(e),Hr.init(e),zr.init(e);const{notificationCenter:t,InnerEvent:{MESSAGE_PUSH:s,DESTROY:o}}=this._core,{InnerEventSubType:{CONV_MODIFIED:n,C2C_MESSAGE_READ_SYNC:i,GROUP_MESSAGE_READ_SYNC:r,C2C_REMIND_TYPE_SYNC:a}}=t;t.subscribeInnerEvent(s,n,this._onConversationModified,this),t.subscribeInnerEvent(s,i,this._onC2CMessageReadSync,this),t.subscribeInnerEvent(s,a,this._onC2CMessageRemindTypeSync,this),t.subscribeInnerEvent(s,r,this._onGroupMessageReadSync,this),t.subscribeInnerEvent(o,this._dispose,this)}_onConversationModified(e){const{constants:{ConvModifyPushType:t}}=this._core,{RecentContactMod:s=[]}=e;s.forEach((e=>{const{PushType:s}=e;if(s===t.CONV_DELETED){const{RecentContactList:t}=e.RecentContactDeleteItem;Kr.handleConversationDeleted(t)}if(s===t.CONV_PINED){const{RecentContactList:t}=e.RecentContactTopItem;jr.handleConversationPinned(t,!0)}if(s===t.CONV_UNPINED){const{RecentContactList:t}=e.RecentContactTopItem;jr.handleConversationPinned(t,!1)}}))}_onC2CMessageReadSync(e){const{C2cNotifyMsgArray:t=[]}=e;Br.handleC2CMessageReadSync(t)}_onC2CMessageRemindTypeSync(e){const{C2cNotifyMsgArray:t=[]}=e;zr.handleC2CMessageRemindTypeSync(t)}_onGroupMessageReadSync(e){const{GroupTips:t=[]}=e;Br.handleGroupMessageReadSync(t)}_dispose(){const{notificationCenter:e,InnerEvent:{MESSAGE_PUSH:t,DESTROY:s}}=this._core,{InnerEventSubType:{CONV_MODIFIED:o,C2C_MESSAGE_READ_SYNC:n,GROUP_MESSAGE_READ_SYNC:i,C2C_REMIND_TYPE_SYNC:r}}=e;e.unSubscribeInnerEvent(t,o,this._onConversationModified,this),e.unSubscribeInnerEvent(t,n,this._onC2CMessageReadSync,this),e.unSubscribeInnerEvent(t,r,this._onC2CMessageRemindTypeSync,this),e.unSubscribeInnerEvent(t,i,this._onGroupMessageReadSync,this),e.unSubscribeInnerEvent(s,this._dispose,this)}};var Qr=new class{init(e){this._core=e;const{helper:t}=e;t.registerApi({apiName:"setAllReceiveMessageOpt",context:this})}setAllReceiveMessageOpt(e){return h(this,void 0,void 0,(function*(){try{const{OuterConstant:{MSG_REMIND_ACPT_NOT_NOTE:t}}=this._core,{messageRemindType:s=t,isRepeated:o=!0}=e,{startTime:n=0,endTime:i=0}=this._calcStartAndEndTime(e),r=yield function(e){return h(this,void 0,void 0,(function*(){const{common:t}=Mr.core,{startTime:s,endTime:o,isRepeated:n,messageRemindType:i}=e,r={StartTime:s,EndTime:o,IsRepeated:n,Level:i};return t.buildAndSendPacket({servcmd:"im_msg_db_logic.ws_set_do_not_disturb",data:r})}))}({messageRemindType:this._getType(s),startTime:n,endTime:i,isRepeated:o?br.ON:br.OFF});return{code:0,data:{errorCode:r.ErrorCode,errorInfo:r.ErrorInfo}}}catch(e){Lr("setAllReceiveMessageOpt",e)}}))}_calcStartAndEndTime(e){const{startHour:t=0,startMinute:s=0,startSecond:o=0,duration:n=0,isRepeated:i=!0}=e,r=new Date,a=new Date(r.getFullYear(),r.getMonth(),r.getDate(),t,s,o),c=Math.round(a.getTime()/1e3);let u=c+n;return i&&n>=86400&&(u=c+86400),{startTime:c,endTime:u}}_getType(e){const{OuterConstant:t}=this._core;return{[t.MSG_REMIND_ACPT_AND_NOTE]:0,[t.MSG_REMIND_DISCARD]:1,[t.MSG_REMIND_ACPT_NOT_NOTE]:2}[e]}};var Xr=new class{init(e){this._core=e;const{helper:t,notificationCenter:s,InnerEvent:o}=e;t.registerApi({apiName:"getAllReceiveMessageOpt",context:this}),s.subscribeInnerEvent(o.MESSAGE_PUSH,s.InnerEventSubType.ALL_RECEIVE_MESSAGE_OPTION,this.onAllReceiveMsgOptionNotify,this)}onAllReceiveMsgOptionNotify(e){const t=this._handleResult(e),{notificationCenter:s,OuterEvent:{ALL_RECEIVE_MESSAGE_OPT_UPDATED:o}}=this._core;s.emitOuterEvent(o,{name:o,data:t})}getAllReceiveMessageOpt(){return h(this,void 0,void 0,(function*(){try{const e=yield function(){return h(this,void 0,void 0,(function*(){const{common:e}=Mr.core,t={To_Account:e.getCurrentUserID()};return e.buildAndSendPacket({servcmd:"im_msg_db_logic.ws_get_do_not_disturb",data:t})}))}();return{code:0,data:this._handleResult(e)}}catch(e){Lr("getAllReceiveMessageOpt",e)}}))}_handleResult(e){const{OuterConstant:t}=this._core,{MSG_REMIND_ACPT_AND_NOTE:s,MSG_REMIND_DISCARD:o,MSG_REMIND_ACPT_NOT_NOTE:n}=t,i={0:s,1:o,2:n},{Level:r,StartTime:a,EndTime:c,IsRepeated:u}=e;return{messageRemindType:i[r]||s,startTime:a,endTime:c,isRepeated:u===br.ON}}};var Zr=new class{init(e){console.log("ReceiveMessageOptions.init"),this._core=e,Wr.init(e),Yr.init(e),$r.init(e),qr.init(e),Qr.init(e),Xr.init(e)}};const ea=e=>!yr(e)&&!Tr(e)&&!Ar(e),ta={getConversationProfile:[{key:"conversationID",required:!0,rules:["string"],allowEmpty:!1,customValidator:e=>!ea(e)||"conversationID is invalid."}],setMessageRead:{conversationID:{required:!0,rules:["string"],allowEmpty:!1,customValidator:e=>!ea(e)||"conversationID is invalid."}},pinConversation:{conversationID:{required:!0,rules:["string"],allowEmpty:!1,customValidator:e=>!ea(e)||"conversationID is invalid."},isPinned:{required:!0,rules:["boolean"],allowEmpty:!1}},deleteConversation:[{key:"options",required:!0,rules:["string","object"],allowEmpty:!1,customValidator:e=>{const{core:{utils:{isArray:t,isObject:s,isString:o}}}=Mr;if(!o(e)&&!s(e))return"options is String or Object.";if(o(e)&&ea(e))return"conversationID is invalid.";if(s(e)){if(!t(e.conversationIDList))return"conversationIDList is not Array.";if(0===e.conversationIDList.length)return"conversationIDList is empty.";if(e.conversationIDList.some((e=>{if(ea(e))return!0})))return"conversationIDList includes invalid conversationID.";if(e.clearHistoryMessage&&"boolean"!=typeof e.clearHistoryMessage)return"clearHistoryMessage is not Boolean."}return!0}}],setConversationDraft:{conversationID:{required:!0,rules:["string"],allowEmpty:!1,customValidator:e=>!(!yr(e)&&!Tr(e))||"conversationID is invalid."},draftText:{required:!0,rules:["string"],allowEmpty:!0}},setAllReceiveMessageOpt:{messageRemindType:{required:!1,rules:["string"],allowEmpty:!0},startHour:{required:!1,rules:["number"],allowEmpty:!0},startMinute:{required:!1,rules:["number"],allowEmpty:!0},startSecond:{required:!1,rules:["number"],allowEmpty:!0},duration:{required:!1,rules:["number"],allowEmpty:!0},isRepeated:{required:!1,rules:["boolean"],allowEmpty:!0}}},sa={getConversationList:!0,getConversationProfile:!0,getTotalUnreadCount:!0,setMessageRead:!0,pinConversation:!0,deleteConversation:!0,setConversationDraft:!0,setMessageRemindType:!0,getAllReceiveMessageOpt:!0,setAllReceiveMessageOpt:!0};var oa=new class{constructor(){this.name="Conversation"}install(e){Mr.init(e),Jr.init(e),Zr.init(e),kr.init(e),e.helper.registerValidateConfig({auth:sa,params:ta})}};const na=new class{init(e){this.core=e}},ia="AVChatRoom",ra="AV_HISTORY_MSG",aa="GRP_COUNTER",ca="Set",ua="Increase",la="Decrease",da=0,pa=1,ha=2,ga=["Type","Name","Introduction","Notification","FaceUrl","Owner_Account","CreateTime","InfoSeq","LastInfoTime","LastMsgTime","MemberNum","MaxMemberNum","ApplyJoinOption","NextMsgSeq","ShutUpAllMember","InviteJoinOption","LastRecallTime"],_a=["Type","Name","Introduction","Notification","FaceUrl","CreateTime","Owner_Account","LastInfoTime","LastMsgTime","NextMsgSeq","MemberNum","MaxMemberNum","ApplyJoinOption","InviteJoinOption"],ma=["Role","JoinTime","MsgFlag","MsgSeq"],va=["Role","JoinTime","MsgSeq","MsgFlag","NameCard"],fa=0,Ia=1,Sa="notStart",Ea="resolved",Ca="rejected",Ma=10018,ya=11e3,Ta=2,Aa=["Owner","Admin","Member"],Oa=["Role","JoinTime","NameCard","ShutUpUntil","OnlineStatus"],Da=0,Ra=1,La=2,Na=4,ba=1,Ga=2,wa=3,Pa=4,Ua=5,ka=1,Fa=0,$a=4,qa=6,xa=400,Va=300,Ba={from:!0,groupID:!0,groupName:!0,to:!0},ja={from:!0,groupID:!0,groupName:!0,to:!0,type:!0},Ka=2,Ha=4,Wa=5,Ya=7,za=8,Ja=15,Qa=20,Xa=21,Za=2600,ec=2602,tc=2603,sc=2620,oc=2621,nc=2623,ic=2660,rc=2661,ac=2681,cc=2683,uc=2684,lc=2685,dc=2687,pc=3122,hc=10018,gc=e=>e===na.core.OuterConstant.GRP_PUBLIC,_c=e=>e===na.core.OuterConstant.GRP_AVCHATROOM,mc=(e,t)=>{const{isArray:s}=na.core.utils;if(!s(e)||!s(t))return!1;let o=!1;return t.forEach((({key:t,value:s})=>{const n=e.find((e=>e.key===t));n?n.value!==s&&(n.value=s,o=!0):(e.push({key:t,value:s}),o=!0)})),o},vc=e=>{const t=[];if(!e)return t;for(let s=0,o=e.length;s<o;s++){const{Key:o,Value:n}=e[s];t.push({key:o,value:n})}return t},fc=e=>{const t=[];for(let s=0,o=e.length;s<o;s++){const{key:o,value:n}=e[s];t.push({Key:o,Value:n})}return t};function Ic(e,t){const{helper:s}=na.core;if(!s.checkBusinessCapabilityBits(t))throw new s.ChatError({functionName:e,code:pc,replacement1:e})}function Sc(e,t){const{helper:s}=na.core,o=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:`,o),o}const Ec=["groupID","name","avatar","type","introduction","notification","ownerID","selfInfo","createTime","infoSequence","lastInfoTime","lastMessage","nextMessageSeq","memberCount","maxMemberCount","memberList","joinOption","groupCustomField","muteAllMembers","isSupportTopic","inviteOption","_lastRevokedTime","_groupAtInfoList"];class Cc{constructor(e){this.groupID="",this.name="",this.avatar="",this.type="",this.introduction="",this.notification="",this.ownerID="",this.createTime=0,this.selfInfo={messageRemindType:"",joinTime:"",nameCard:"",role:"",userID:"",memberCustomField:void 0,readedSequence:0,excludedUnreadSequenceList:void 0},this.lastMessage={lastTime:0,lastSequence:0,fromAccount:"",messageForShow:""},this.nextMessageSeq=0,this.memberCount=0,this.maxMemberCount=0,this.joinOption="",this.inviteOption="",this.groupCustomField=[],this.muteAllMembers=!1,this.isSupportTopic=!1,this._lastRevokedTime=0,this._groupAtInfoList=[],this._initGroup(e)}_initGroup(e){const{utils:{isString:t}}=na.core;for(const s in e)Ec.indexOf(s)<0||("selfInfo"!==s?"isSupportTopic"!==s?"muteAllMembers"===s&&t(e[s])?this.muteAllMembers="On"===e[s]:this[s]=e[s]:this.isSupportTopic=1===e[s]:this.updateSelfInfo(e[s]))}updateGroup(e){const{utils:{isArray:t,isUndefined:s,isNumber:o,isString:n},common:{deepMerge:i}}=na.core;e.appid=void 0,e.grossTopicNextMsgSeq=void 0,e.selfInfo&&(e.selfInfo.grossTopicReadSeq=void 0);const r=JSON.parse(JSON.stringify(e));r.lastMsgTime&&(this.lastMessage.lastTime=r.lastMsgTime),n(r.muteAllMembers)&&(r.muteAllMembers="On"===r.muteAllMembers),r.groupCustomField&&mc(this.groupCustomField,r.groupCustomField),s(r.isSupportTopic)||(this.isSupportTopic=o(r.isSupportTopic)?1===r.isSupportTopic:r.isSupportTopic),i(this,r,["members","errorCode","lastMsgTime","groupCustomField","isSupportTopic"]),t(r.members)&&r.members.length>0&&r.members.forEach((e=>{e.userID===this.selfInfo.userID&&i(this.selfInfo,e,["sequence"])}))}updateSelfInfo(e){const{nameCard:t,joinTime:s,role:o,messageRemindType:n,readedSequence:i,excludedUnreadSequenceList:r}=e,{common:{deepMerge:a}}=na.core;a(this.selfInfo,{nameCard:t,joinTime:s,role:o,messageRemindType:n,readedSequence:i,excludedUnreadSequenceList:r},[],["",null,void 0,0,NaN])}setSelfNameCard(e){this.selfInfo.nameCard=e}}var Mc=new class{constructor(){this._name="GroupDataHandler"}init(e){this._core=e;const{appStore:{groupStore:t}}=e;this._groupMap=t.getGroupMap(),console.log(`${this._name}.init`)}hasLocalGroup(e){return this._groupMap.has(e)}getLocalGroup(e){return this._groupMap.get(e)}updateLocalGroup(e){const{common:{getCurrentUserID:t}}=this._core;let s;e.forEach((e=>{var t;s=e.groupID,this.hasLocalGroup(s)?null===(t=this.getLocalGroup(s))||void 0===t||t.updateGroup(e):this._groupMap.set(s,new Cc(e))}));const o=t();for(const[,e]of this._groupMap)e.selfInfo.userID=o,"Owner"===e.selfInfo.role&&(e.ownerID=o)}deleteLocalGroup(e){this._groupMap.delete(e)}getLocalGroupList(){const{OuterConstant:{GRP_ROOM:e,GRP_LIVE:t}}=this._core;return[...this._groupMap.values()].filter((s=>{const{type:o}=s;return o!==e&&o!==t}))}clearLocalGroup(){this._groupMap.clear()}emitGroupListUpdate(){const e=this.getLocalGroupList(),{OuterEvent:{GROUP_LIST_UPDATED:t},notificationCenter:s}=this._core;s.emitOuterEvent(t,{name:t,data:e})}updateConversationGroupProfile(e){const{appStore:{conversationStore:t},OuterConstant:{CONV_GROUP:s}}=this._core,o=`${s}${e}`;if(t.getConversation(o)){const s=this.getLocalGroup(e);t.updateConversation(o,{groupProfile:s})}}reset(){this.clearLocalGroup()}};function yc(e,t){return h(this,void 0,void 0,(function*(){const{type:s,limit:o,offset:n,supportTopic:i=0,memberAccount:r,responseFilter:a}=e,c={Type:s,Limit:o,Offset:n,Member_Account:r,ResponseFilter:a,SupportTopic:i,NeedAppDefineData:1};return t.common.buildAndSendPacket({servcmd:"group_open_http_svc.get_joined_group_list",data:c})}))}const Tc=function(e){return{code:0,data:e||{}}};var Ac=new class{constructor(){this._name="GetGroupList",this._pagingStatus=Sa,this.PAGING_GRP_COUNT_LIMIT=200}init(e){this._core=e;const{helper:t,constants:{WORKFLOW_NAME:s,WORKFLOW_STEP:o}}=e;t.registerApi({apiName:"getGroupList",context:this}),t.registerWorkflowStep(s.SYNC_SERVER_INFO_AFTER_LOGIN,o.GROUP_LIST_SYNC,this._syncGroupList,this)}getGroupList(){return h(this,arguments,void 0,(function*(e=!1){if(e){const e=[];return yield this._pagingGetJoinedCommunityList({limit:this.PAGING_GRP_COUNT_LIMIT,offset:0,groupList:e}),Mc.updateLocalGroup(e),Mc.getLocalGroupList()}if(console.log(`${this._name}.getGroupList pagingStatus:${this._pagingStatus}`),this._pagingStatus===Ca||this._pagingStatus===Sa)return this._syncGroupList().then((()=>{const e=Mc.getLocalGroupList();return Tc({groupList:e,isSyncCompleted:this._isSyncCompleted()})})).catch((e=>{throw console.error(`${this._name}.getGroupList fail:`,e),e}));const t=Mc.getLocalGroupList();return console.log(`${this._name}.getGroupList return group count:${t.length}`),Tc({groupList:t,isSyncCompleted:this._isSyncCompleted()})}))}_syncGroupList(){return h(this,void 0,void 0,(function*(){this._pagingStatus===Sa&&Mc.clearLocalGroup();const e=this.PAGING_GRP_COUNT_LIMIT,t=[];try{yield this._pagingGetGroupList({limit:e,offset:0,groupList:t}),this._pagingStatus=Ea,this._groupListTreeShaking(t),Mc.updateLocalGroup(t);const s=Mc.getLocalGroupList();return console.log(`${this._name}._syncGroupList ok, count:${s.length}`),Mc.emitGroupListUpdate(),s}catch(e){throw this._pagingStatus=Ca,console.error(`${this._name}._syncGroupList fail:`,e),e}}))}_pagingGetGroupList(e){return h(this,void 0,void 0,(function*(){const{isCommunityRelay:t=!1,groupList:s}=e;let o,{limit:n,offset:i}=e;const r=[...ga];t&&(o=this._core.OuterConstant.GRP_COMMUNITY,r.push("AtInfoList"));try{const e=yield yc({type:o,limit:n,offset:i,memberAccount:this._core.store.get("login").userId,responseFilter:{GroupBaseInfoFilter:r,SelfInfoFilter:[...ma]}},this._core),{GroupIdList:a=[],TotalCount:c=0}=e||{},u=this._convertGroupKey(a);s.push(...u);const l=i+n,d=!(c>l),p=`offset:${i} limit:${n} total:${c} isCompleted:${d} current:${s.length} isCommunityRelay:${t}`;return console.log(`${this._name}._pagingGetGroupList ok. ${p}`),t?d?s:(i=l,this._pagingGetGroupList({isCommunityRelay:!0,limit:n,offset:i,groupList:s})):d?(console.log(`${this._name}._pagingGetGroupList start to get community list`),i=0,this._pagingGetGroupList({isCommunityRelay:!0,limit:n,offset:i,groupList:s})):(i=l,this._pagingGetGroupList({limit:n,offset:i,groupList:s}))}catch(e){if(e.ErrorCode===Ma)return console.warn(`${this._name}._pagingGetGroupList response size exceeds the limit, request count:${n}`),n=50,this._pagingGetGroupList({isCommunityRelay:t,limit:n,offset:i,groupList:s});if(t)return e.code===ya&&console.log(`${this._name}._pagingGetGroupList ok. community unavailable`),s;throw e}}))}_pagingGetJoinedCommunityList(e){return h(this,void 0,void 0,(function*(){const{common:{getCurrentUserID:t},OuterConstant:s}=this._core,{groupList:o}=e;let{limit:n,offset:i}=e;try{const e=yield yc({limit:n,offset:i,type:s.GRP_COMMUNITY,memberAccount:t(),supportTopic:1,responseFilter:{GroupBaseInfoFilter:[...ga],SelfInfoFilter:[...ma]}},this._core),{GroupIdList:r=[],TotalCount:a=0}=e||{},c=this._convertGroupKey(r);o.push(...c);const u=i+n,l=!(a>u),d=`offset:${i} limit:${n} total:${a} isCompleted:${l} current:${o.length}`;return console.log(`${this._name}._pagingGetJoinedCommunityList ok. ${d}`),l?o:(i=u,this._pagingGetJoinedCommunityList({limit:n,offset:i,groupList:o}))}catch(e){if(e.code===hc)return console.warn(`${this._name}._pagingGetJoinedCommunityList response size exceeds the limit, request count:${n}`),n=50,this._pagingGetJoinedCommunityList({limit:n,offset:i,groupList:o});throw e}}))}_groupListTreeShaking(e){const t=new Map([...Mc.getLocalGroupList()]);for(let s=0,o=e.length;s<o;s++)t.delete(e[s].groupID);const s=[...t.keys()];for(let e=0,t=s.length;e<t;e++)Mc.deleteLocalGroup(s[e])}_isSyncCompleted(){return this._pagingStatus===Ea}_convertGroupKey(e){const t=[];for(let s=0,o=e.length;s<o;s++){const{AppDefinedData:o,ApplyJoinOption:n,CreateTime:i,FaceUrl:r,GroupId:a,Introduction:c,InviteJoinOption:u,LastInfoTime:l,LastMsgTime:d,MemberNum:p,MaxMemberNum:h,MuteAllMember:g,Name:_,NextMsgSeq:m,Notification:v,Owner_Account:f,Type:I,LastRecallTime:S,SelfInfo:E,AtInfoList:C=[],SupportTopic:M}=e[s],y=vc(o),T=this._convertSelfInfo(E),A=this._convertAtInfoList(a,C);t.push({groupCustomField:y,joinOption:n,createTime:i,avatar:r,groupID:a,introduction:c,inviteOption:u,lastInfoTime:l,lastMsgTime:d,memberCount:p,maxMemberCount:h,muteAllMembers:g,name:_,nextMessageSeq:m,notification:v,ownerID:f,type:I,selfInfo:T,_lastRevokedTime:S,_groupAtInfoList:A,isSupportTopic:M})}return t}_convertSelfInfo(e){const{JoinTime:t,MsgFlag:s,MsgSeq:o,NoUnreadSeqList:n,Role:i}=e;return{joinTime:t,messageRemindType:s,readedSequence:o,excludedUnreadSequenceList:n,role:i}}_convertAtInfoList(e,t){if(0===t.length)return[];const s=[];return t.forEach((t=>{const{AtFlagList:o,AtMsgSeq:n,From_Account:i}=t;s.push({groupID:e,groupAtType:o,sequence:n,from:i})})),s}};var Oc=new class{constructor(){this._name="CreateGroup"}init(e){this._core=e;const{helper:t}=e;t.registerApi({apiName:"createGroup",context:this})}createGroup(e){return h(this,void 0,void 0,(function*(){var t;this._preCheckParams(e);const{ssoLog:s,helper:{ChatError:o}}=this._core,n=s.createSSOLogData({method:"createGroup"});try{const{utils:{isEmpty:s},common:{getCurrentUserID:o}}=this._core,i=yield function(e,t){return h(this,void 0,void 0,(function*(){const{name:s,type:o,groupID:n,introduction:i,notification:r,avatar:a,maxMemberNum:c,joinOption:u,inviteOption:l,memberList:d,groupCustomField:p,isSupportTopic:h}=e;let g;d&&(g=d.map((e=>{const{userID:t,memberCustomField:s}=e;return{Member_Account:t,AppMemberDefinedData:s?fc(s):void 0}})));const _={Name:s,Type:o,GroupId:n,Introduction:i,Notification:r,FaceUrl:a,MaxMemberCount:c,ApplyJoinOption:u,InviteJoinOption:l,MemberList:g,AppDefinedData:p,SupportTopic:h,webPushFlag:1};return t.common.buildAndSendPacket({servcmd:"group_open_http_svc.create_group",data:_})}))}(Object.assign(Object.assign({},e),{ownerID:o()}),this._core),{GroupId:r,OverJoinedGroupLimit_Account:a=[]}=i||{};n.setLogInfo({message:`groupID:${r}`}).end(),console.log(`${this._name}.createGroup ok, type:${e.type} groupID:${r} overLimitUserIDList:${a}`),s(e.memberList)||s(a)||(e.memberList=null===(t=e.memberList)||void 0===t?void 0:t.filter((e=>a.includes(e.userID)))),Mc.updateLocalGroup([Object.assign(Object.assign({},e),{groupID:r})]);const c=Mc.getLocalGroup(r);return this._notNeedSendCustomMessage(e)||(this._sendCustomMessage(r,e.type),Mc.emitGroupListUpdate()),Tc({group:c})}catch(t){const{errorCode:s,errorInfo:i}=t,r=new o({functionName:"createGroup",code:s,message:i});throw n.setLogInfo({message:`groupID:${e.groupID||""}`}).setError(r).end(),console.error(`${this._name}.createGroup fail:`,r),r}}))}_preCheckParams(e){const{type:t,groupID:s}=e,{utils:{isEmpty:o,isUndefined:n},common:{isCommunity:i}}=this._core,r=!o(s);if(!(()=>{const{GRP_PUBLIC:e,GRP_WORK:t,GRP_MEETING:s,GRP_AVCHATROOM:o,GRP_COMMUNITY:n}=na.core.OuterConstant;return[e,t,s,o,n]})().includes(t))throw new this._core.helper.ChatError({code:Za});if(!i({type:t})){if(r&&i({groupID:s}))throw new this._core.helper.ChatError({code:ec});n(e.isSupportTopic)||(e.isSupportTopic=void 0)}if(this._canIUseMemberList(t)||n(e.memberList)||(e.memberList=void 0),this._canIUseJoinOption(t)||n(e.joinOption)||(e.joinOption=void 0),i({type:t})){if(r&&!i({groupID:s}))throw new this._core.helper.ChatError({code:ec});e.isSupportTopic=this._canIUseTopic(e)?1:0}}_canIUseMemberList(e){return!_c(e)}_canIUseJoinOption(e){return gc(e)||this._core.common.isCommunity({type:e})}_canIUseTopic(e){const{isSupportTopic:t}=e;return!0===t}_notNeedSendCustomMessage(e){const{type:t,isSupportTopic:s}=e,{OuterConstant:{GRP_AVCHATROOM:o,GRP_COMMUNITY:n}}=this._core;return t===o||t===n&&1===s}_sendCustomMessage(e,t){var s,o,n,i,r,a;const{OuterConstant:c}=this._core;let u="Create Group",l=fa;t===c.GRP_COMMUNITY&&(u="Create Community",l=Ia);const d={to:e,conversationType:"GROUP",payload:{data:JSON.stringify({businessID:"group_create",content:u,cmd:l,opUser:this._core.store.get("login").userId,version:4})}},p=null===(n=null===(o=null===(s=this._core)||void 0===s?void 0:s.message)||void 0===o?void 0:o.messageFactory)||void 0===n?void 0:n.createCustomMessage(d);null===(a=null===(r=null===(i=this._core)||void 0===i?void 0:i.message)||void 0===r?void 0:r.messageSender)||void 0===a||a.sendMessage(p,{})}};var Dc=new class{constructor(){this._name="AttributesDataHandler",this._groupAttributesCache=new Map,this._groupAttributesCacheValuesCopy={}}init(e){this._core=e;const{helper:t,constants:s}=e;t.registerWorkflowStep(s.WORKFLOW_NAME.SYNC_SERVER_INFO_AFTER_RE_ONLINE,s.WORKFLOW_STEP.GROUP_ATTRIBUTE_CACHE_CLEAR,this.clearLocalMainSequence,this)}clearLocalMainSequence(){this._groupAttributesCache.forEach((e=>{e.localMainSequence=0}))}isGroupAttributesUpdated(e){const{elements:{newGroupProfile:t}}=e,{utils:{isEmpty:s,isUndefined:o}}=this._core;return!o(t)&&!s(t.groupAttributeOption)}handleGroupAttributesUpdated(e){const{groupID:t,groupAttributeOption:s}=e,{serverMainSequence:o,groupAttributeList:n=[],operation:i}=s;console.log(`${this._name}.handleGroupAttributesUpdated groupID:${t} operation:${i}`);const{utils:{isUndefined:r}}=this._core;r(i)||(this.refreshGroupAttributesCache({groupID:t,serverMainSequence:o,groupAttributeList:n,operation:i}),this.emitGroupAttributesUpdated(t))}initGroupAttributesCache(e){const{groupID:t,avChatRoomKey:s}=e;this._groupAttributesCache.set(t,{lastUpdateTime:0,localMainSequence:0,serverMainSequence:0,avChatRoomKey:s,values:new Map}),console.log(`${this._name}.initGroupAttributesCache. groupID:${t} avChatRoomKey:${s}`)}hasGroupAttributesCache(e){return this._groupAttributesCache.has(e)}getGroupAttributesCache(e){return this.hasGroupAttributesCache(e)||this.initGroupAttributesCache({groupID:e}),this._groupAttributesCache.get(e)}deleteGroupAttributesCache(e){this.hasGroupAttributesCache(e)&&this._groupAttributesCache.delete(e)}refreshGroupAttributesCache(e){const{groupID:t,serverMainSequence:s,groupAttributeList:o,operation:n}=e;if(this.hasGroupAttributesCache(t)){const e=this.getGroupAttributesCache(t),{localMainSequence:i}=e;n!==Ua&&s-i!=1||(e.serverMainSequence=s,e.localMainSequence=s,e.lastUpdateTime=Date.now(),this._updateGroupAttributesCacheValues({groupAttributes:e,groupAttributeList:o,operation:n})),s-i>1&&(e.serverMainSequence=s),this._groupAttributesCache.set(t,e),console.log(`${this._name}.refreshGroupAttributesCache. operation:${n} localMainSequence:${i} serverMainSequence:${s}`)}}_updateGroupAttributesCacheValues(e){const{groupAttributes:t,groupAttributeList:s=[],operation:o}=e;o!==wa?o!==Pa?(o===ba&&t.values.clear(),s.forEach((e=>{const{key:s,value:o,sequence:n}=e;t.values.set(s,{value:o,sequence:n})}))):s.forEach((e=>{t.values.delete(e.key)})):t.values.clear()}getGroupAttributesCacheValues(e){var t;const{groupID:s,keyList:o=[]}=e,n={};if(this.hasGroupAttributesCache(s)){const{values:e}=this.getGroupAttributesCache(s);if(0===o.length){for(const s of e.keys())n[s]=(null===(t=e.get(s))||void 0===t?void 0:t.value)||"";return n}return o.forEach((t=>{var s;e.has(t)&&(n[t]=(null===(s=e.get(t))||void 0===s?void 0:s.value)||"")})),n}return n}saveGroupAttributesCacheValuesCopy(e){this._groupAttributesCacheValuesCopy=this.getGroupAttributesCacheValues({groupID:e})}emitGroupAttributesUpdated(e){var t;const s=this.getGroupAttributesCacheValues({groupID:e}),{updatedKeyList:o,deletedKeyList:n}=this._computeValuesChangedData(s);console.log(`${this._name}.emitGroupAttributesUpdated update count:${o.length}, delete count:${n.length}`),0===o.length&&0===n.length||this._emitEvent({name:null===(t=this._core)||void 0===t?void 0:t.OuterEvent.GROUP_ATTRIBUTES_UPDATED,data:{groupID:e,groupAttributes:s,updatedKeyList:o,deletedKeyList:n}})}_computeValuesChangedData(e){const{utils:{isUndefined:t}}=this._core,s=[],o=[];return Object.keys(e).forEach((t=>{e[t]!==this._groupAttributesCacheValuesCopy[t]&&s.push(t)})),Object.keys(this._groupAttributesCacheValuesCopy).forEach((s=>{t(e[s])&&o.push(s)})),this._groupAttributesCacheValuesCopy={},{updatedKeyList:s,deletedKeyList:o}}_emitEvent(e){var t;null===(t=this._core)||void 0===t||t.notificationCenter.emitOuterEvent(e.name,e)}convertKeyValueMapToList(e){const t=[];return Object.keys(e).forEach((s=>{t.push({key:s,value:e[s]})})),t}reset(){this._groupAttributesCache.clear(),this._groupAttributesCacheValuesCopy={}}};var Rc=new class{constructor(){this._name="DismissGroup"}init(e,t){this._core=e;const{helper:s}=e;s.registerApi({apiName:"dismissGroup",context:this,matcher:()=>!t.getInstalledSubPlugins().includes(ia)})}dismissGroup(e){return h(this,void 0,void 0,(function*(){console.log(`${this._name}.dismissGroup groupID:${e}`);const{ssoLog:t,helper:{ChatError:s}}=this._core,o=t.createSSOLogData({method:"dismissGroup"});o.setLogInfo({message:`groupID:${e}`});try{yield function(e,t){return h(this,void 0,void 0,(function*(){const s={GroupId:e};return t.common.buildAndSendPacket({servcmd:"group_open_http_svc.destroy_group",data:s})}))}(e,this._core),o.end(),console.log(`${this._name}.dismissGroup ok.`);const{type:t}=Mc.getLocalGroup(e);return Mc.deleteLocalGroup(e),Mc.emitGroupListUpdate(),Dc.deleteGroupAttributesCache(e),Tc({groupID:e,type:t})}catch(e){const{errorCode:t,errorInfo:n}=e,i=new s({functionName:"dismissGroup",code:t,message:n});throw o.setError(i).end(),console.error(`${this._name}.dismissGroup fail:`,i),i}}))}};var Lc=new class{constructor(){this._name="GetGroupProfile"}init(e){this._core=e;const{helper:t}=e;t.registerApi({apiName:"getGroupProfile",context:this})}getGroupProfile(e){return h(this,void 0,void 0,(function*(){const{groupID:t,groupCustomFieldFilter:s}=e,o={groupIDList:[t],responseFilter:{GroupBaseInfoFilter:[...ga],AppDefinedDataFilter_Group:s,MemberInfoFilter:[...va]}},{ssoLog:n,helper:{ChatError:i}}=this._core,r=n.createSSOLogData({method:"getGroupProfile"});r.setLogInfo({message:`groupID:${t}`});try{const e=yield this.getGroupProfileAdvance(o),{successGroupList:s,failureGroupList:n}=e;if(n.length>0)throw n[0];let i;return!Mc.hasLocalGroup(t)&&_c(s[0].type)?i=new Cc(s[0]):(Mc.updateLocalGroup(s),i=Mc.getLocalGroup(t)),i.isSupportTopic||Mc.updateConversationGroupProfile(t),r.end(),console.log(`${this._name}.getGroupProfile ok.`),Tc({group:i})}catch(e){const{code:t,message:s}=e,o=new i({functionName:"getGroupProfile",code:t,message:s});throw r.setError(o).end(),console.error(`${this._name}.getGroupProfile fail:`,o),e}}))}getGroupProfileAdvance(e){return h(this,void 0,void 0,(function*(){const{groupIDList:t}=e,{common:{isCommunity:s}}=this._core,o=t.filter((e=>!s({groupID:e}))),n=t.filter((e=>s({groupID:e})));o.length>50&&(o.length=50),n.length>50&&(n.length=50);const i=yield Promise.all([this._getGroupProfileAdvance(Object.assign(Object.assign({},e),{groupIDList:o})),this._getGroupProfileAdvance(Object.assign(Object.assign({},e),{groupIDList:n,isCommunityProfile:!0}))]),r=[],a=[];return i.forEach((e=>{r.push(...e.successGroupList),a.push(...e.failureGroupList)})),{successGroupList:r,failureGroupList:a}}))}_getGroupProfileAdvance(e){return h(this,void 0,void 0,(function*(){const{isCommunityProfile:t=!1}=e,s=p(e,["isCommunityProfile"]);if(0===s.groupIDList.length)return{successGroupList:[],failureGroupList:[]};try{const e=yield function(e,t){return h(this,void 0,void 0,(function*(){const{groupIDList:s,responseFilter:o}=e,n={GroupIdList:s,ResponseFilter:o};return t.common.buildAndSendPacket({servcmd:"group_open_http_svc.get_group_self_member_info",data:n})}))}(s,this._core),{GroupInfo:t=[]}=e||{},o=this._convertGroupProfileKey(t),{utils:{isUndefined:n}}=this._core,i=o.filter((e=>n(e.errorCode)||0===e.errorCode)),r=o.filter((e=>e.errorCode&&0!==e.errorCode)).map((e=>({code:e.errorCode,message:e.errorInfo,data:{groupID:e.groupID}})));return console.log(`${this._name}._getGroupProfileAdvance ok, groupID:${s.groupIDList.join(",")}`),{successGroupList:i,failureGroupList:r}}catch(e){if(t)return{successGroupList:[],failureGroupList:[]};throw e}}))}_convertGroupProfileKey(e){const t=[];for(let s=0,o=e.length;s<o;s++){const{AppDefinedData:o,ApplyJoinOption:n,CreateTime:i,FaceUrl:r,GroupId:a,InfoSeq:c,Introduction:u,InviteJoinOption:l,LastInfoTime:d,LastMsgTime:p,MaxMemberNum:h,MemberNum:g,MuteAllMember:_,Name:m,NextMsgSeq:v,Notification:f,Owner_Account:I,ShutUpAllMember:S,ShutUpUntil:E,Type:C,MemberList:M,ErrorCode:y,ErrorInfo:T}=e[s],A=vc(o),O=this._convertMembers(M);t.push({groupCustomField:A,joinOption:n,createTime:i,avatar:r,groupID:a,infoSequence:c,introduction:u,inviteOption:l,lastInfoTime:d,lastMsgTime:p,maxMemberCount:h,memberCount:g,muteAllMembers:_,name:m,nextMessageSeq:v,notification:f,ownerID:I,shutUpAllMember:S,muteUntil:E,type:C,members:O,errorCode:y,errorInfo:T})}return t}_convertMembers(e){if(!e)return[];const t=[];for(let s=0,o=e.length;s<o;s++){const{AppMemberDefinedData:o,JoinTime:n,Member_Account:i,MsgFlag:r,MsgSeq:a,NameCard:c,Role:u}=e[s],l=vc(o);t.push({memberCustomField:l,joinTime:n,userID:i,messageRemindType:r,sequence:a,nameCard:c,role:u})}return t}};var Nc=new class{constructor(){this._groupCountersMap=new Map}init(e){this._core=e}getLocalGroupCounters(e){return this._hasLocalGroupCounters(e)||this.initGroupCountersCache({groupID:e}),this._groupCountersMap.get(e)}updateLocalGroupCounters(e){const{groupID:t,counterList:s=[],groupCounterSeq:o}=e;if(this._hasLocalGroupCounters(t)){const{counters:e,avChatRoomKey:n,groupCounterSeq:i}=this.getLocalGroupCounters(t);if(o>0&&o<i)return;s.forEach((t=>{const{Key:s,Value:o=0}=t;e.set(s,o)})),this._groupCountersMap.set(t,{lastUpdateTime:Date.now(),groupCounterSeq:o,counters:e,avChatRoomKey:n})}}initGroupCountersCache(e){const{groupID:t,avChatRoomKey:s}=e;this._groupCountersMap.set(t,{lastUpdateTime:0,groupCounterSeq:0,counters:new Map,avChatRoomKey:s})}getLocalCounters(e,t){const s={};if(!this._hasLocalGroupCounters(e))return s;const{counters:o}=this.getLocalGroupCounters(e);if(t.length>0)t.forEach((e=>{o.has(e)&&(s[e]=o.get(e))}));else for(const e of o.keys())s[e]=o.get(e);return s}deleteLocalGroupCounters(e){const{groupID:t,counterList:s=[],groupCounterSeq:o}=e;if(this._hasLocalGroupCounters(t)){const{counters:e,avChatRoomKey:n}=this.getLocalGroupCounters(t);s.forEach((t=>{e.delete(t.key)})),this._groupCountersMap.set(t,{lastUpdateTime:Date.now(),groupCounterSeq:o,counters:e,avChatRoomKey:n})}}setGroupCounters(e,t){if(!this._hasLocalGroupCounters(e))return;const s=this.getLocalGroupCounters(e),{counters:o}=s;let n=!1;Object.entries(t).forEach((([e,t])=>{o.has(e)&&o.get(e)!==t&&(o.set(e,t),n=!0)})),n&&this._groupCountersMap.set(e,Object.assign(Object.assign({},s),{lastUpdateTime:Date.now(),counters:o}))}_hasLocalGroupCounters(e){return this._groupCountersMap.has(e)}reset(){this._groupCountersMap.clear()}};var bc=new class{constructor(){this._name="JoinGroup"}init(e,t){this._core=e;const{helper:s}=e;s.registerApi({apiName:"joinGroup",context:this,matcher:()=>!t.getInstalledSubPlugins().includes(ia)})}joinGroup(e){return h(this,void 0,void 0,(function*(){const{groupID:t}=e,{ssoLog:s,ChatError:o,OuterConstant:n}=this._core,i=s.createSSOLogData({method:"joinGroup"});try{if(Mc.hasLocalGroup(t))try{return yield Lc.getGroupProfile({groupID:t}),i.setLogInfo({message:`groupID:${t} joinedStatus:${n.JOIN_STATUS_ALREADY_IN_GROUP}`}).end(),Tc({status:n.JOIN_STATUS_ALREADY_IN_GROUP})}catch(s){console.warn(`${this._name}.joinGroup ${t} was unjoined, start to join!`),Mc.deleteLocalGroup(t);const o=yield this._applyJoinGroup(e);return i.setLogInfo({message:`groupID:${t}`}).end(),o}const s=yield this._applyJoinGroup(e);return i.setLogInfo({message:`groupID:${t}`}).end(),s}catch(e){const{errorCode:t,errorInfo:s}=e,n=new o({functionName:"joinGroup",code:t,message:s});throw i.setError(n).end(),console.error(`${this._name}.joinGroup fail:`,e),e}}))}_applyJoinGroup(e){return h(this,void 0,void 0,(function*(){const{OuterConstant:t,helper:s}=this._core,{groupID:o}=e,n=Object.assign({},e),i=s.checkBusinessCapabilityBits(ra);i&&(n.historyMessageFlag=1);const r=yield function(e,t){return h(this,void 0,void 0,(function*(){const{groupID:s,applyMessage:o,historyMessageFlag:n}=e,i={GroupId:s,ApplyMsg:o,HugeGroupHistoryMsgFlag:n};return t.common.buildAndSendPacket({servcmd:"group_open_http_svc.apply_join_group",data:i})}))}(n,this._core),{Type:a,JoinedStatus:c,LongPollingKey:u,StartSeq:l,HugeGroupFlag:d,AVChatRoomKey:p,RspMsgList:g=[]}=r||{},_=`groupID:${o} joinedStatus:${c} longPollingKey:${u} startSeq:${l} avChatRoomFlag:${d} canGetAVChatRoomHistoryMsg:${i}, historyMessageCount:${g.length}`;if(console.log(`${this._name}._applyJoinGroup ok, ${_}`),c===t.JOIN_STATUS_WAIT_APPROVAL)return Tc({status:t.JOIN_STATUS_WAIT_APPROVAL,group:{groupID:o,type:a}});if(c===t.JOIN_STATUS_SUCCESS){let e=null;try{e=(yield Lc.getGroupProfile({groupID:o})).data.group}catch(t){e=new Cc({groupID:o}),console.warn(`${this._name}._applyJoinGroup getGroupProfile failed, groupID: ${o}, errorCode:`,null==t?void 0:t.code)}return this._handleJoinResult({group:e,avChatRoomFlag:d,longPollingKey:u,startSequence:l,avChatRoomKey:p,historyMessageList:g})}throw new this._core.helper.ChatError({code:ic})}))}_handleJoinResult(e){const{group:t,avChatRoomFlag:s,avChatRoomKey:o}=e;return 1===s?(Dc.initGroupAttributesCache({groupID:t.groupID,avChatRoomKey:o}),Nc.initGroupCountersCache({groupID:t.groupID,avChatRoomKey:o}),Tc(e)):(Mc.updateLocalGroup([t]),Mc.emitGroupListUpdate(),Tc({status:this._core.OuterConstant.JOIN_STATUS_SUCCESS,group:t}))}};var Gc=new class{constructor(){this._name="QuitGroup"}init(e,t){this._core=e;const{helper:s}=e;s.registerApi({apiName:"quitGroup",context:this,matcher:()=>!t.getInstalledSubPlugins().includes(ia)})}quitGroup(e){return h(this,void 0,void 0,(function*(){if(!Mc.hasLocalGroup(e))throw new this._core.helper.ChatError({code:nc});const{ssoLog:t,helper:{ChatError:s}}=this._core,o=t.createSSOLogData({method:"quitGroup"});o.setLogInfo({message:`groupID:${e}`});try{yield function(e,t){return h(this,void 0,void 0,(function*(){const s={GroupId:e};return t.common.buildAndSendPacket({servcmd:"group_open_http_svc.quit_group",data:s})}))}(e,this._core),o.end(),console.log(`${this._name}.quitGroup ok, groupID:${e}`);const{type:t}=Mc.getLocalGroup(e);return Mc.deleteLocalGroup(e),Mc.emitGroupListUpdate(),Dc.deleteGroupAttributesCache(e),Tc({groupID:e,type:t})}catch(e){const{errorCode:t,errorInfo:n}=e,i=new s({functionName:"quitGroup",code:t,message:n});throw o.setError(i).end(),console.error(`${this._name}.quitGroup fail:`,i),i}}))}};var wc=new class{constructor(){this._name="SearchGroup"}init(e){this._core=e;const{helper:t}=e;t.registerApi({apiName:"searchGroupByID",context:this})}searchGroupByID(e){return h(this,void 0,void 0,(function*(){console.log(`${this._name}.searchGroupByID groupID:${e}`);try{const t=yield function(e,t){return h(this,void 0,void 0,(function*(){const s={GroupIdList:[e],GroupBasePublicInfoFilter:[..._a]};return t.common.buildAndSendPacket({servcmd:"group_open_http_svc.get_group_public_info",data:s})}))}(e,this._core),{GroupInfo:s=[]}=t||{},{AppDefinedData:o=[],ApplyJoinOption:n,CreateTime:i,FaceUrl:r,Introduction:a,InviteJoinOption:c,MaxMemberNum:u,MemberNum:l,Name:d,Owner_Account:p,Type:g,ErrorCode:_,ErrorInfo:m}=s[0];if(0!==_)throw new this._core.helper.ChatError({code:_,message:m});console.log(`${this._name}.searchGroupByID ok.`);const v=vc(o),f=new Cc({groupID:e,name:d,avatar:r,introduction:a,joinOption:n,inviteOption:c,maxMemberCount:u,memberCount:l,type:g,ownerID:p,createTime:i,groupCustomField:v});return Tc({group:f})}catch(e){throw console.error(`${this._name}.searchGroupByID fail:`,e),e}}))}};var Pc=new class{constructor(){this._name="UpdateGroupProfile"}init(e){this._core=e;const{helper:t}=e;t.registerApi({apiName:"updateGroupProfile",context:this})}updateGroupProfile(e){return h(this,void 0,void 0,(function*(){const{groupID:t}=e,{utils:{isUndefined:s}}=this._core;let o=Mc.getLocalGroup(t);if(o){const{type:t}=o;this._canIUseJoinOption(t)||s(e.joinOption)||(console.warn(`${this._name}.updateGroupProfile joinOption is unavailable for Work/Meeting/AVChatRoom`),e.joinOption=void 0)}s(e.muteAllMembers)||(e.muteAllMembers=!0===e.muteAllMembers?"On":"Off");try{return yield function(e,t){return h(this,void 0,void 0,(function*(){const{groupID:s,name:o,avatar:n,introduction:i,notification:r,muteAllMembers:a,joinOption:c,inviteOption:u,groupCustomField:l}=e,d={GroupId:s,Name:o,FaceUrl:n,Introduction:i,Notification:r,ShutUpAllMember:a,ApplyJoinOption:c,InviteJoinOption:u,AppDefinedData:l?fc(l):void 0};return t.common.buildAndSendPacket({servcmd:"group_open_http_svc.modify_group_base_info",data:d})}))}(e,this._core),console.log(`${this._name}.updateGroupProfile groupID:${t} ok.`),o?(o.updateGroup(e),Mc.emitGroupListUpdate()):o=new Cc(e),Tc({group:o})}catch(e){throw console.error(`${this._name}.updateGroupProfile groupID:${t} fail:`,e),e}}))}_canIUseJoinOption(e){return gc(e)||this._core.common.isCommunity({type:e})}};var Uc=new class{constructor(){this._name="ChangeGroupOwner"}init(e){this._core=e;const{helper:t}=e;t.registerApi({apiName:"changeGroupOwner",context:this})}changeGroupOwner(e){return h(this,void 0,void 0,(function*(){const t="changeGroupOwner",{groupID:s,newOwnerID:o}=e,n=Mc.getLocalGroup(s),{helper:i,OuterConstant:r,common:{getCurrentUserID:a}}=this._core;if((null==n?void 0:n.type)===r.GRP_AVCHATROOM)throw new i.ChatError({functionName:t,code:sc});if(o===a())throw new i.ChatError({functionName:t,code:oc});console.log(`${this._name}.${t} groupID:${s} newOwnerID:${o}`);try{return yield function(e,t){return h(this,void 0,void 0,(function*(){const{groupID:s,newOwnerID:o}=e,n={GroupId:s,NewOwner_Account:o};return t.common.buildAndSendPacket({servcmd:"group_open_http_svc.change_group_owner",data:n})}))}(e,this._core),console.log(`${this._name}.${t} ok.`),n.ownerID=o,Mc.emitGroupListUpdate(),Tc({group:n})}catch(e){const s=new i.ChatError({functionName:t,code:null==e?void 0:e.errorCode,message:null==e?void 0:e.errorInfo});throw console.error(`${this._name}.${t} fail:`,s),s}}))}};var kc=new class{constructor(){this._name="GetGroupOnlineMemberCount",this._onlineMemberCountMap=new Map}init(e,t){this._core=e;const{helper:s}=e;s.registerApi({apiName:"getGroupOnlineMemberCount",context:this,matcher:()=>!t.getInstalledSubPlugins().includes(ia)})}getGroupOnlineMemberCount(e){return h(this,void 0,void 0,(function*(){const t="getGroupOnlineMemberCount",s=Mc.hasLocalGroup(e);if(console.log(`${this._name}.${t} groupID:${e} hasLocalGroup:${s}`),!s)return Tc({memberCount:0});const o=Date.now();if(this._onlineMemberCountMap.has(e)){const t=this._onlineMemberCountMap.get(e),{lastReqTime:s=0,memberCount:n=0}=t||{};if(o-s<=6e4)return Tc({memberCount:n})}try{const s=yield function(e,t){return h(this,void 0,void 0,(function*(){const s={GroupId:e};return t.common.buildAndSendPacket({servcmd:"group_open_http_svc.get_online_member_num",data:s})}))}(e,this._core),{OnlineMemberNum:o=0}=s||{};return this._onlineMemberCountMap.set(e,{lastReqTime:Date.now(),memberCount:o}),console.log(`${this._name}.${t} ok. groupID:${e} memberCount:${o}`),Tc({memberCount:o})}catch(e){const s=new this._core.helper.ChatError({functionName:t,code:null==e?void 0:e.errorCode,message:null==e?void 0:e.errorInfo});throw console.error(`${this._name}.${t} fail:`,s),s}}))}};var Fc=new class{init(e,t){console.log("GroupAction.init"),Ac.init(e),Oc.init(e),Rc.init(e,t),bc.init(e,t),Gc.init(e,t),wc.init(e),Lc.init(e),Pc.init(e),Uc.init(e),kc.init(e,t)}dismissGroup(e){return Rc.dismissGroup(e)}joinGroup(e){return bc.joinGroup(e)}quitGroup(e){return Gc.quitGroup(e)}getGroupOnlineMemberCount(e){return kc.getGroupOnlineMemberCount(e)}};var $c=new class{constructor(){this._name="GetGroupApplicationList"}init(e){this._core=e;const{helper:t}=e;t.registerApi({apiName:"getGroupApplicationList",context:this})}getGroupApplicationList(){return h(this,void 0,void 0,(function*(){const e="getGroupApplicationList";try{const t=yield Promise.all([this._getGroupApplicationList(),this._getGroupApplicationList({type:this._core.OuterConstant.GRP_COMMUNITY})]);console.log(`${this._name}.${e} ok.`);const s=this._handleGroupApplicationResult([...t[0],...t[1]]);return Tc({applicationList:s})}catch(t){const s=new this._core.helper.ChatError({functionName:e,code:null==t?void 0:t.errorCode,message:null==t?void 0:t.errorInfo});throw console.error(`${this._name}.${e} fail:`,s),s}}))}_getGroupApplicationList(e){return h(this,void 0,void 0,(function*(){const{type:t,startTime:s=0,limit:o=20}=e||{},{common:n}=this._core;let i;try{i=yield function(e,t){return h(this,void 0,void 0,(function*(){const{type:s,startTime:o,limit:n,handleAccount:i}=e,r={Type:s,StartTime:o,Limit:n,Handle_Account:i};return t.common.buildAndSendPacket({servcmd:"group_open_http_svc.get_pendency",data:r})}))}({type:t,startTime:s,limit:o,handleAccount:n.getCurrentUserID()},this._core)}catch(e){if(11e3!==(null==e?void 0:e.errorCode))throw e;i={}}const{NextStartTime:r=0,PendencyList:a=[]}=i||{};if(0===r)return a;const c=yield this._getGroupApplicationList(Object.assign(Object.assign({},e),{startTime:r}));return[...a,...c]}))}_handleGroupApplicationResult(e){const t=[];return e.forEach((e=>{const s=this._convertApplicationData(e),{handled:o}=s,n=p(s,["handled"]);0===o&&t.push(n)})),t}_convertApplicationData(e){const{Handled:t,AddTime:s,ApplyInviteMsg:o,Authentication:n,FromUserNickName:i,From_Account:r,GroupId:a,GroupName:c,PendencyType:u,To_Account:l}=e;return{handled:t,messageKey:s,applicant:r,applicantNick:i,groupID:a,groupName:c,authentication:n,applicationType:u,userID:l,note:o}}};var qc=new class{constructor(){this._name="HandleGroupApplication"}init(e){this._core=e;const{helper:t}=e;t.registerApi({apiName:"handleGroupApplication",context:this})}handleGroupApplication(e){return h(this,void 0,void 0,(function*(){const t="handleGroupApplication",{application:s}=e,o=this._handleParams(e);try{(null==s?void 0:s.applicationType)===Ta?yield function(e,t){return h(this,void 0,void 0,(function*(){const{groupID:s,handleAction:o,handleMessage:n,applicant:i,authentication:r,invitee:a}=e,c={GroupId:s,HandleMsg:o,ApprovalMsg:n,Applicant_Account:i,Authentication:r,Invited_Account:a};return t.common.buildAndSendPacket({servcmd:"group_open_http_svc.handle_invite_join_permission_group",data:c})}))}(o,this._core):yield function(e,t){return h(this,void 0,void 0,(function*(){const{groupID:s,handleAction:o,handleMessage:n,applicant:i,authentication:r,messageKey:a}=e,c={GroupId:s,HandleMsg:o,ApprovalMsg:n,Applicant_Account:i,Authentication:r,MsgKey:a};return t.common.buildAndSendPacket({servcmd:"group_open_http_svc.handle_apply_join_group",data:c})}))}(o,this._core),console.log(`${this._name}.${t} ok.`);const e=Mc.getLocalGroup(o.groupID);return Tc({group:e})}catch(e){const s=new this._core.helper.ChatError({functionName:t,code:null==e?void 0:e.errorCode,message:null==e?void 0:e.errorInfo});throw console.error(`${this._name}.${t} fail:`,s),s}}))}_handleParams(e){var t;const{handleAction:s,handleMessage:o,message:n,application:i}=e;let r,a,c,u,l;if(n){const{payload:e}=n||{};r=e.operatorID,a=null===(t=e.groupProfile)||void 0===t?void 0:t.groupID,c=e.authentication,u=e.messageKey}else r=(null==i?void 0:i.applicant)||"",a=(null==i?void 0:i.groupID)||"",c=(null==i?void 0:i.authentication)||"",u=(null==i?void 0:i.messageKey)||0;return(null==i?void 0:i.applicationType)===Ta&&(l=i.userID),{handleAction:s,handleMessage:o,applicant:r,invitee:l,groupID:a,authentication:c,messageKey:u}}};var xc=new class{init(e){console.log("GroupApplication.init"),$c.init(e),qc.init(e)}};let Vc=class{constructor(e){this.userID="",this.avatar="",this.nick="",this.role="",this.joinTime="",this.nameCard="",this.muteUntil=0,this.memberCustomField=[],this.isOnline=!1,this.updateMember(e)}updateMember(e){const{core:{utils:{isUndefined:t},common:{deepMerge:s}}}=na;t(e.muteTime)||(this.muteUntil=Math.floor((Date.now()+1e3*e.muteTime)/1e3)),t(e.onlineStatus)||(this.isOnline="Online"===e.onlineStatus);const o=[null,void 0,"",0,NaN];e.memberCustomField&&mc(this.memberCustomField,e.memberCustomField),s(this,e,["memberCustomField","marks","onlineStatus","muteTime"],o)}};function Bc(e,t){return h(this,void 0,void 0,(function*(){const{groupID:s,userID:o,muteTime:n,role:i,nameCard:r,memberCustomField:a}=e;let c;a&&(c=fc(a));const u={GroupId:s,Member_Account:o,ShutUpTime:n,Role:i,NameCard:r,AppMemberDefinedData:c};return t.common.buildAndSendPacket({servcmd:"group_open_http_svc.modify_group_member_info",data:u})}))}var jc=new class{constructor(){this._name="GetGroupMemberList"}init(e,t){this._core=e;const{helper:s}=e;s.registerApi({apiName:"getGroupMemberList",context:this,matcher:()=>!t.getInstalledSubPlugins().includes(ia)})}getGroupMemberList(e){return h(this,void 0,void 0,(function*(){const t="getGroupMemberList",{groupID:s,offset:o=0,count:n=100,role:i="",filter:r=""}=e;console.log(`${this._name}.${t} groupID:${s} offset:${o} count:${n} role:${i} filter:${r}`);const a=Mc.getLocalGroup(s),c=n>100?100:n,u={groupID:s,offset:o,limit:c,memberRoleFilter:Aa.includes(i)?[i]:void 0,memberInfoFilter:Oa};try{const e=yield function(e,t){return h(this,void 0,void 0,(function*(){const{groupID:s,offset:o,limit:n,memberRoleFilter:i,memberInfoFilter:r}=e,a={GroupId:s,Offset:o,Limit:n,MemberRoleFilter:i,MemberInfoFilter:r};return t.common.buildAndSendPacket({servcmd:"group_open_http_svc.get_group_member_info",data:a})}))}(u,this._core),{MemberList:n,MemberNum:i,Next:r}=e||{};console.log(`${this._name}.${t} ok, totalMemberCount:${i} next:${r}`);const{utils:{isArray:l,isEmpty:d},common:{isCommunity:p}}=this._core;if(a&&(a.memberCount=i),!l(n)||0===n.length)return Tc({memberList:[],offset:0});let g=o+c;p({groupID:s})&&(g=d(r)?0:r),n.length<c&&(g=0);let _=this._convertMemberInfo(n);_=yield this._patchAvatarAndNick(_);const m=this._generateGroupMember(_);return Tc({memberList:m,offset:g})}catch(e){const s=new this._core.helper.ChatError({functionName:t,code:null==e?void 0:e.errorCode,message:null==e?void 0:e.errorInfo});throw console.error(`${this._name}.${t} fail:`,s),s}}))}_convertMemberInfo(e){const t=[];for(let s=0,o=e.length;s<o;s++){const{AppMemberDefinedData:o,JoinTime:n,Member_Account:i,OnlineStatus:r,Role:a,ShutUpUntil:c}=e[s],u=vc(o);t.push({userID:i,joinTime:n,onlineStatus:r,role:a,muteUntil:c,memberCustomField:u})}return t}_patchAvatarAndNick(e){return h(this,void 0,void 0,(function*(){var t;const s=e.map((e=>e.userID)),o=yield null===(t=this._core.user.userProfile)||void 0===t?void 0:t.getUserProfile({userIDList:s}),n=(null==o?void 0:o.data)||[],i=new Map(n.map((e=>[e.userID,e])));return e.forEach((e=>{if(i.has(e.userID)){const{nick:t="",avatar:s=""}=i.get(e.userID);e.nick=t,e.avatar=s}})),e}))}_generateGroupMember(e){const t=[];for(let s=0,o=e.length;s<o;s++){const o=new Vc(e[s]);t.push(o)}return t}};var Kc=new class{constructor(){this._name="GetGroupMemberProfile"}init(e){this._core=e;const{helper:t}=e;t.registerApi({apiName:"getGroupMemberProfile",context:this})}getGroupMemberProfile(e){return h(this,void 0,void 0,(function*(){const t="getGroupMemberProfile",{groupID:s,userIDList:o,memberCustomFieldFilter:n}=e,i=Mc.getLocalGroup(s),{helper:r,utils:{isArray:a}}=this._core;if(i&&_c(i.type))throw new r.ChatError({functionName:t,replacement1:t,code:dc});o.length>50&&(console.warn(`${this._name}.${t} userIDList length:${o.length} exceeds limit 50`),o.splice(50));try{const e=yield function(e,t){return h(this,void 0,void 0,(function*(){const{groupID:s,userIDList:o,memberInfoFilter:n,memberCustomFieldFilter:i}=e,r={GroupId:s,Member_List_Account:o,MemberInfoFilter:n,AppDefinedDataFilter_GroupMember:i};return t.common.buildAndSendPacket({servcmd:"group_open_http_svc.get_specified_group_member_info",data:r})}))}({groupID:s,userIDList:o,memberCustomFieldFilter:n,memberInfoFilter:[...Oa]},this._core);console.log(`${this._name}.${t} ok.`);const{MemberList:i}=e||{};if(!a(i)||0===i.length)return Tc({memberList:[]});let r=this._convertMemberInfo(i);r=yield this._getMemberAvatarAndNick(r);const c=this._generateGroupMember(r);return Tc({memberList:c})}catch(e){const s=new r.ChatError({functionName:t,code:null==e?void 0:e.errorCode,message:null==e?void 0:e.errorInfo});throw console.error(`${this._name}.${t} fail:`,s),s}}))}_convertMemberInfo(e){const t=[];for(let s=0,o=e.length;s<o;s++){const{AppMemberDefinedData:o,JoinTime:n,Member_Account:i,OnlineStatus:r,Role:a,ShutUpUntil:c}=e[s],u=vc(o);t.push({userID:i,joinTime:n,onlineStatus:r,role:a,muteUntil:c,memberCustomField:u})}return t}_getMemberAvatarAndNick(e){return h(this,void 0,void 0,(function*(){var t;const s=e.map((e=>e.userID)),o=yield null===(t=this._core.user.userProfile)||void 0===t?void 0:t.getUserProfile({userIDList:s}),n=(null==o?void 0:o.data)||[],i=new Map(n.map((e=>[e.userID,e])));return e.forEach((e=>{if(i.has(e.userID)){const{nick:t="",avatar:s=""}=i.get(e.userID);e.nick=t,e.avatar=s}})),e}))}_generateGroupMember(e){const t=[];for(let s=0,o=e.length;s<o;s++){const o=new Vc(e[s]);t.push(o)}return t}};var Hc=new class{constructor(){this._name="AddGroupMember"}init(e){this._core=e;const{helper:t}=e;t.registerApi({apiName:"addGroupMember",context:this})}addGroupMember(e){return h(this,void 0,void 0,(function*(){const t="addGroupMember",{groupID:s,userIDList:o}=e,n=Mc.getLocalGroup(s),{helper:i}=this._core;if(n&&_c(n.type))throw new i.ChatError({functionName:t,code:rc});const r=o.map((e=>({Member_Account:e})));try{const e=yield function(e,t){return h(this,void 0,void 0,(function*(){const{groupID:s,userIDList:o}=e,n={GroupId:s,MemberList:o};return t.common.buildAndSendPacket({servcmd:"group_open_http_svc.add_group_member",data:n})}))}({groupID:s,userIDList:r},this._core),{MemberList:o=[]}=e||{},{failureUserIDList:i,successUserIDList:a,existedUserIDList:c,overLimitUserIDList:u}=this._handleResult(o);return console.log(`${this._name}.${t} groupID:${s} ok, successUserIDList:${a} failureUserIDList:${i} existedUserIDList:${c} overLimitUserIDList:${u}`),Tc({failureUserIDList:i,successUserIDList:a,existedUserIDList:c,overLimitUserIDList:u,group:n})}catch(e){const s=new i.ChatError({functionName:t,code:null==e?void 0:e.errorCode,message:null==e?void 0:e.errorInfo});throw console.error(`${this._name}.${t} fail:`,s),s}}))}_handleResult(e){const t=[],s=[],o=[],n=[];return e.forEach((e=>{const{Result:i,Member_Account:r}=e;i===Da?t.push(r):i===Ra?s.push(r):i===La?o.push(r):i===Na&&n.push(r)})),{failureUserIDList:t,successUserIDList:s,existedUserIDList:o,overLimitUserIDList:n}}};var Wc=new class{constructor(){this._name="DeleteGroupMember"}init(e,t){this._core=e;const{helper:s}=e;s.registerApi({apiName:"deleteGroupMember",context:this,matcher:()=>!t.getInstalledSubPlugins().includes(ia)})}deleteGroupMember(e){return h(this,void 0,void 0,(function*(){const t="deleteGroupMember",{groupID:s,userIDList:o}=e,n=Mc.getLocalGroup(s),{helper:i,utils:{isUndefined:r}}=this._core;if(r(n))throw new i.ChatError({functionName:t,code:tc});o.length>20&&(console.warn(`${this._name}.${t} userIDList length:${o.length} exceeds limit 20`),o.splice(20));try{return yield function(e,t){return h(this,void 0,void 0,(function*(){const{groupID:s,userIDList:o,reason:n}=e,i={GroupId:s,MemberToDel_Account:o,Reason:n};return t.common.buildAndSendPacket({servcmd:"group_open_http_svc.delete_group_member",data:i})}))}({groupID:s,userIDList:o},this._core),console.log(`${this._name}.${t} ok, groupID:${s} userIDList length:${o.length}`),Tc({group:n,userIDList:o})}catch(e){const s=new i.ChatError({functionName:t,code:null==e?void 0:e.errorCode,message:null==e?void 0:e.errorInfo});throw console.error(`${this._name}.${t} fail:`,s),s}}))}};var Yc=new class{constructor(){this._name="SetGroupMemberMuteTime"}init(e){this._core=e;const{helper:t}=e;t.registerApi({apiName:"setGroupMemberMuteTime",context:this})}setGroupMemberMuteTime(e){return h(this,void 0,void 0,(function*(){const t="setGroupMemberMuteTime",{helper:s}=this._core;this._preCheckSettingMuteParams(e);try{yield Bc(e,this._core);const{groupID:s,userID:o,muteTime:n}=e;console.log(`${this._name}.${t} ok, groupID:${s} userID:${o} muteTime:${n}`);const i=Mc.getLocalGroup(s),r=new Vc({userID:o,muteTime:n});return Tc({group:i,member:r})}catch(e){const o=new s.ChatError({functionName:t,code:null==e?void 0:e.errorCode,message:null==e?void 0:e.errorInfo});throw console.error(`${this._name}.${t} fail:`,o),o}}))}_preCheckSettingMuteParams(e){const{userID:t}=e,{store:s,helper:o}=this._core;if(t===s.get("login").userId)throw new o.ChatError({functionName:"setGroupMemberMuteTime",code:lc})}};var zc=new class{constructor(){this._name="SetGroupMemberRole"}init(e){this._core=e;const{helper:t}=e;t.registerApi({apiName:"setGroupMemberRole",context:this})}setGroupMemberRole(e){return h(this,void 0,void 0,(function*(){const t="setGroupMemberRole",{helper:s}=this._core;this._preCheckSettingRoleParams(e);try{yield Bc(e,this._core);const{groupID:s,userID:o,role:n}=e;console.log(`${this._name}.${t} ok, groupID:${s} userID:${o} role:${n}`);const i=Mc.getLocalGroup(s),r=new Vc({userID:o,role:n});return Tc({group:i,member:r})}catch(e){const o=new s.ChatError({functionName:t,code:null==e?void 0:e.errorCode,message:null==e?void 0:e.errorInfo});throw console.error(`${this._name}.${t} fail:`,o),o}}))}_preCheckSettingRoleParams(e){var t;const{groupID:s,userID:o,role:n}=e,{store:i,helper:r,OuterConstant:a,common:{isCommunity:c}}=this._core,u=Mc.getLocalGroup(s);if((null===(t=null==u?void 0:u.selfInfo)||void 0===t?void 0:t.role)!==a.GRP_MBR_ROLE_OWNER)throw new r.ChatError({functionName:"setGroupMemberRole",code:ac});if(o===i.get("login").userId)throw new r.ChatError({functionName:"setGroupMemberRole",code:uc});const l=[...Aa];if(c({groupID:s})&&l.push(a.GRP_MBR_ROLE_CUSTOM),!l.includes(n))throw new r.ChatError({functionName:"setGroupMemberRole",code:cc})}};var Jc=new class{constructor(){this._name="SetGroupMemberNameCard"}init(e){this._core=e;const{helper:t}=e;t.registerApi({apiName:"setGroupMemberNameCard",context:this})}setGroupMemberNameCard(e){return h(this,void 0,void 0,(function*(){const t="setGroupMemberNameCard",{helper:s,common:{getCurrentUserID:o}}=this._core;this._preCheckSettingNameCardParams(e);try{const{groupID:s,userID:n=o(),nameCard:i}=e,r={groupID:s,userID:n,nameCard:i};yield Bc(r,this._core),console.log(`${this._name}.${t} ok, groupID:${s} userID:${n} nameCard:${i}`);const a=Mc.getLocalGroup(s),c=new Vc({userID:n,nameCard:i});return Tc({group:a,member:c})}catch(e){const o=new s.ChatError({functionName:t,code:null==e?void 0:e.errorCode,message:null==e?void 0:e.errorInfo});throw console.error(`${this._name}.${t} fail:`,o),o}}))}_preCheckSettingNameCardParams(e){const{groupID:t}=e,{helper:s}=this._core,o=Mc.getLocalGroup(t);if(_c(null==o?void 0:o.type))throw new s.ChatError({functionName:"setGroupMemberNameCard",code:dc})}};var Qc=new class{constructor(){this._name="SetGroupMemberCustomField"}init(e){this._core=e;const{helper:t}=e;t.registerApi({apiName:"setGroupMemberCustomField",context:this})}setGroupMemberCustomField(e){return h(this,void 0,void 0,(function*(){const t="setGroupMemberCustomField",{helper:s,common:{getCurrentUserID:o}}=this._core;this._preCheckSettingCustomFiledParams(e);try{const{groupID:s,userID:n=o(),memberCustomField:i}=e,r={groupID:s,userID:n,memberCustomField:i};yield Bc(r,this._core),console.log(`${this._name}.${t} ok, groupID:${s} userID:${n} memberCustomField:${JSON.stringify(i)}`);const a=Mc.getLocalGroup(s),c=new Vc({userID:n,memberCustomField:i});return Tc({group:a,member:c})}catch(e){const o=new s.ChatError({functionName:t,code:null==e?void 0:e.errorCode,message:null==e?void 0:e.errorInfo});throw console.error(`${this._name}.${t} fail:`,o),o}}))}_preCheckSettingCustomFiledParams(e){const{groupID:t}=e,{helper:s}=this._core,o=Mc.getLocalGroup(t);if(_c(null==o?void 0:o.type))throw new s.ChatError({functionName:"setGroupMemberCustomField",code:dc})}};var Xc=new class{init(e,t){console.log("GroupMember.init"),jc.init(e,t),Kc.init(e),Hc.init(e),Wc.init(e,t),Yc.init(e),zc.init(e),Jc.init(e),Qc.init(e)}getGroupMemberList(e){return jc.getGroupMemberList(e)}deleteGroupMember(e){return Wc.deleteGroupMember(e)}};var Zc=new class{init(e){this._core=e;const{helper:t}=e;t.registerApi({apiName:"getGroupCounters",context:this})}getGroupCounters(e){return h(this,void 0,void 0,(function*(){const t="getGroupCounters";try{Ic(t,aa);const{groupID:s,keyList:o=[]}=e,{avChatRoomKey:n,lastUpdateTime:i}=Nc.getLocalGroupCounters(s);if(!(Date.now()-i>=this._getExpireTime())){return{code:0,data:{counters:Nc.getLocalCounters(s,o)}}}const r=yield function(e){return h(this,void 0,void 0,(function*(){const{groupID:t,GroupCounterKeys:s,avChatRoomKey:o}=e,{common:n}=na.core,i={GroupId:t,keyList:s,BytesKey:o};return n.buildAndSendPacket({servcmd:"group_open_http_svc.get_group_counter",data:i})}))}({groupID:s,keyList:o,avChatRoomKey:n}),{GroupCounter:a=[],GroupCounterSeq:c}=r;Nc.updateLocalGroupCounters({groupID:s,counterList:a,groupCounterSeq:c});return{code:0,data:{counters:Nc.getLocalCounters(s,o)}}}catch(e){Sc(t,e)}}))}_getExpireTime(){const{store:e,utils:{isUndefined:t}}=this._core,s=e.get("cloudConfig")||{},{grp_counter_expire_time:o}=s;return t(o)?3e4:Number(o)}};var eu=new class{init(e){const{helper:t}=e;t.registerApi({apiName:"setGroupCounters",context:this}),t.registerApi({apiName:"increaseGroupCounter",context:this}),t.registerApi({apiName:"decreaseGroupCounter",context:this})}setGroupCounters(e){return h(this,void 0,void 0,(function*(){return this._handleCounterOperation(ca,e)}))}increaseGroupCounter(e){return h(this,void 0,void 0,(function*(){return this._handleCounterOperation(ua,e)}))}decreaseGroupCounter(e){return h(this,void 0,void 0,(function*(){return this._handleCounterOperation(la,e)}))}_handleCounterOperation(e,t){return h(this,void 0,void 0,(function*(){const s=`${e}GroupCounter`;try{Ic(s,aa);const{groupID:o,key:n,value:i=0}=t,{avChatRoomKey:r}=Nc.getLocalGroupCounters(o),a=e===ca?this._convertObjectToList(t.counters):[{Key:n,Value:i}],c=yield this._updateGroupCounters({groupID:o,counterList:a,avChatRoomKey:r,mode:e});return Nc.setGroupCounters(o,c),{code:0,data:{counters:c}}}catch(e){Sc(s,e)}}))}_updateGroupCounters(e){return h(this,void 0,void 0,(function*(){const t=yield function(e){const{groupID:t,counterList:s,mode:o,avChatRoomKey:n}=e,{common:i}=na.core,r={GroupId:t,GroupCounter:s,Mode:o,BytesKey:n};return i.buildAndSendPacket({servcmd:"group_open_http_svc.update_group_counter",data:r})}(e),{GroupCounter:s=[]}=t,o={};return s.forEach((e=>{const{Key:t,Value:s=0}=e;o[t]=s})),o}))}_convertObjectToList(e){return Object.entries(e).map((([e,t])=>({Key:e,Value:t||0})))}};var tu=new class{init(e){this._core=e,Zc.init(e),eu.init(e)}isGroupCounterUpdated(e){const{elements:{groupCounterInfo:t}}=e,{utils:{isEmpty:s}}=this._core;return!s(t)}handleGroupCounterUpdated(e){const{to:t,elements:{groupCounterInfo:s}}=e;s.forEach((e=>{const{type:s,groupCounterSeq:o,counterList:n=[]}=e;s!==da&&s!==ha||this._processAndNotifyCounterUpdate(t,o,n),s===pa&&Nc.deleteLocalGroupCounters({groupID:t,groupCounterSeq:o,counterList:n})}))}_processAndNotifyCounterUpdate(e,t,s){const{OuterEvent:o,notificationCenter:n}=this._core;Nc.updateLocalGroupCounters({groupID:e,groupCounterSeq:t,counterList:s}),s.forEach((({Key:t,Value:s=0})=>{n.emitOuterEvent(o.GROUP_COUNTER_UPDATED,{name:o.GROUP_COUNTER_UPDATED,data:{groupID:e,key:t,value:s}})}))}reset(){Nc.reset()}};var su=new class{constructor(){this._name="InitGroupAttributes"}init(e){this._core=e;const{helper:t}=e;t.registerApi({apiName:"initGroupAttributes",context:this})}initGroupAttributes(e){return h(this,void 0,void 0,(function*(){const t="initGroupAttributes",{groupID:s,groupAttributes:o}=e,{serverMainSequence:n,avChatRoomKey:i}=Dc.getGroupAttributesCache(s),r=Dc.convertKeyValueMapToList(o);try{const e=yield function(e,t){return h(this,void 0,void 0,(function*(){const{groupID:s,mainSequence:o,groupAttributeList:n,avChatRoomKey:i}=e,r={GroupId:s,AttrMainSeq:o,GroupAttr:n,BytesKey:i,AttrControl:["RaceConflict"]};return t.common.buildAndSendPacket({servcmd:"group_open_http_svc.set_group_attr",data:r})}))}({groupID:s,avChatRoomKey:i,groupAttributeList:r,mainSequence:n},this._core),{AttrMainSeq:a,GroupAttr:c}=e||{};console.log(`${this._name}.${t} ok. groupID:${s} serverMainSequence:${a}`);const u=c.map((e=>{const{Key:t,seq:s}=e;return{key:t,value:o[t],sequence:s}}));return Dc.saveGroupAttributesCacheValuesCopy(s),Dc.refreshGroupAttributesCache({groupID:s,serverMainSequence:a,groupAttributeList:u,operation:ba}),Dc.emitGroupAttributesUpdated(s),Tc({groupAttributes:o})}catch(e){const s=new this._core.helper.ChatError({functionName:t,code:null==e?void 0:e.errorCode,message:null==e?void 0:e.errorInfo});throw console.error(`${this._name}.${t} fail:`,s),s}}))}};var ou=new class{constructor(){this._name="SetGroupAttributes"}init(e){this._core=e;const{helper:t}=e;t.registerApi({apiName:"setGroupAttributes",context:this})}setGroupAttributes(e){return h(this,void 0,void 0,(function*(){const t="setGroupAttributes",{groupID:s,groupAttributes:o}=e,{serverMainSequence:n,avChatRoomKey:i,values:r}=Dc.getGroupAttributesCache(s),a=Dc.convertKeyValueMapToList(o).map((e=>{var t;const{key:s,value:o}=e;return{key:s,value:o,seq:(null===(t=r.get(e.key))||void 0===t?void 0:t.sequence)||0}}));try{const e=yield function(e,t){return h(this,void 0,void 0,(function*(){const{groupID:s,mainSequence:o,groupAttributeList:n,avChatRoomKey:i}=e,r={GroupId:s,AttrMainSeq:o,GroupAttr:n,BytesKey:i,AttrControl:["RaceConflict"]};return t.common.buildAndSendPacket({servcmd:"group_open_http_svc.modify_group_attr",data:r})}))}({groupID:s,avChatRoomKey:i,groupAttributeList:a,mainSequence:n},this._core),{AttrMainSeq:r,GroupAttr:c}=e||{};console.log(`${this._name}.${t} ok. groupID:${s} serverMainSequence:${r}`);const u=c.map((e=>{const{Key:t,seq:s}=e;return{key:t,value:o[t],sequence:s}}));return Dc.saveGroupAttributesCacheValuesCopy(s),Dc.refreshGroupAttributesCache({groupID:s,serverMainSequence:r,groupAttributeList:u,operation:Ga}),Dc.emitGroupAttributesUpdated(s),Tc({groupAttributes:o})}catch(e){const s=new this._core.helper.ChatError({functionName:t,code:null==e?void 0:e.errorCode,message:null==e?void 0:e.errorInfo});throw console.error(`${this._name}.${t} fail:`,s),s}}))}};var nu=new class{constructor(){this._name="DeleteGroupAttributes"}init(e){this._core=e;const{helper:t}=e;t.registerApi({apiName:"deleteGroupAttributes",context:this})}deleteGroupAttributes(e){return h(this,void 0,void 0,(function*(){const t="deleteGroupAttributes",{groupID:s,keyList:o=[]}=e;try{let e;e=0===o.length?yield this._clearGroupAttributes(s):yield this._deleteGroupAttributes(s,o);const{resultList:n,serverMainSequence:i,operation:r,groupAttributeList:a}=e||{};return console.log(`${this._name}.${t} ok. groupID:${s} operation: ${r}`),Dc.saveGroupAttributesCacheValuesCopy(s),Dc.refreshGroupAttributesCache({groupID:s,serverMainSequence:i,groupAttributeList:a,operation:r}),Dc.emitGroupAttributesUpdated(s),Tc({keyList:n})}catch(e){const s=new this._core.helper.ChatError({functionName:t,code:null==e?void 0:e.errorCode,message:null==e?void 0:e.errorInfo});throw console.error(`${this._name}.${t} fail:`,s),s}}))}_deleteGroupAttributes(e,t){return h(this,void 0,void 0,(function*(){const{serverMainSequence:s,avChatRoomKey:o,values:n}=Dc.getGroupAttributesCache(e),i=[],r=[];t.forEach((e=>{if(n.has(e)){const{sequence:t=0}=n.get(e)||{};r.push({key:e,seq:t}),i.push(e)}}));const a=yield function(e,t){return h(this,void 0,void 0,(function*(){const{groupID:s,mainSequence:o,groupAttributeList:n,avChatRoomKey:i}=e,r={GroupId:s,AttrMainSeq:o,GroupAttr:n,BytesKey:i,AttrControl:["RaceConflict"]};return t.common.buildAndSendPacket({servcmd:"group_open_http_svc.delete_group_attr",data:r})}))}({groupID:e,avChatRoomKey:o,groupAttributeList:r,mainSequence:s},this._core),{AttrMainSeq:c}=a||{};return{resultList:i,serverMainSequence:c,groupAttributeList:r,operation:Pa}}))}_clearGroupAttributes(e){return h(this,void 0,void 0,(function*(){const{serverMainSequence:t,avChatRoomKey:s,values:o}=Dc.getGroupAttributesCache(e),n=[...o.keys()],i=yield function(e,t){return h(this,void 0,void 0,(function*(){const{groupID:s,mainSequence:o,avChatRoomKey:n}=e,i={GroupId:s,AttrMainSeq:o,BytesKey:n,AttrControl:["RaceConflict"]};return t.common.buildAndSendPacket({servcmd:"group_open_http_svc.clear_group_attr",data:i})}))}({groupID:e,avChatRoomKey:s,mainSequence:t},this._core),{AttrMainSeq:r}=i||{};return{resultList:n,serverMainSequence:r,operation:wa}}))}};var iu=new class{constructor(){this._name="GetGroupAttributes"}init(e){this._core=e;const{helper:t}=e;t.registerApi({apiName:"getGroupAttributes",context:this})}getGroupAttributes(e){return h(this,void 0,void 0,(function*(){const t="getGroupAttributes",{groupID:s}=e,{avChatRoomKey:o,lastUpdateTime:n,localMainSequence:i,serverMainSequence:r}=Dc.getGroupAttributesCache(s),{ssoLog:a,helper:{ChatError:c}}=this._core,u=a.createSSOLogData({method:"getGroupAttributes"});u.setLogInfo({message:`groupID:${s} localMainSequence:${i} serverMainSequence:${r} keyList:${e.keyList}`});if(Date.now()-n>=3e4||i<r)try{const n=yield this.getGroupAttributesFromServer({groupID:s,avChatRoomKey:o}),i=Dc.getGroupAttributesCacheValues(e),{serverGroupAttributeList:r=[]}=n||{};return u.setLogInfo({moreMessage:`from server, count:${r.length}`}).end(),console.log(`${this._name}.${t} from server. groupID:${s}`),Tc({groupAttributes:i})}catch(e){const s=new c({functionName:t,code:null==e?void 0:e.errorCode,message:null==e?void 0:e.errorInfo});throw u.setError(s).end(),console.error(`${this._name}.${t} fail:`,s),s}const l=Dc.getGroupAttributesCacheValues(e);return u.setLogInfo({moreMessage:"from cache."}).end(),console.log(`${this._name}.${t} from cache. groupID:${s}`),Tc({groupAttributes:l})}))}getGroupAttributesFromServer(e){return h(this,void 0,void 0,(function*(){const{utils:{isUndefined:t}}=this._core,{groupID:s,avChatRoomKey:o}=e,n=t(o)?Fa:ka,i=yield function(e,t){return h(this,void 0,void 0,(function*(){const{groupID:s,groupType:o,avChatRoomKey:n}=e,i={GroupId:s,GroupType:o,Key:n};return t.common.buildAndSendPacket({servcmd:"group_open_attr_http_svc.get_group_attr",data:i})}))}({groupID:s,avChatRoomKey:o,groupType:n},this._core),{AttrMainSeq:r=0,GroupAttrAry:a}=i||{};console.log(`${this._name}._getGroupAttributesFromServer ok. groupID:${s} serverMainSequence:${r}`);const c=a.map((e=>{const{key:t,value:s,seq:o}=e;return{key:t,value:s,sequence:o}}));return Dc.refreshGroupAttributesCache({groupID:s,serverMainSequence:r,groupAttributeList:c,operation:Ua}),{serverGroupAttributeList:a}}))}};var ru=new class{init(e){console.log("GroupAttribute.init"),su.init(e),ou.init(e),nu.init(e),iu.init(e),Dc.init(e)}isGroupAttributesUpdated(e){return Dc.isGroupAttributesUpdated(e)}handleGroupAttributesUpdated(e){const{to:t,elements:{newGroupProfile:s}}=e,{groupAttributeOption:o}=s,{serverMainSequence:n,withChangedAttributeInfo:i}=o,{localMainSequence:r}=Dc.getGroupAttributesCache(t),a=n-r;if(console.log(`GroupAttribute.handleGroupAttributesUpdated groupID:${t} withChangedAttributeInfo:${i} diffSequence:${a}`),0!==a)if(Dc.saveGroupAttributesCacheValuesCopy(t),1!==i||1!==a){if(Dc.hasGroupAttributesCache(t)){const{avChatRoomKey:e}=Dc.getGroupAttributesCache(t);iu.getGroupAttributesFromServer({groupID:t,avChatRoomKey:e}).then((()=>{Dc.emitGroupAttributesUpdated(t)})).catch((()=>{}))}}else Dc.handleGroupAttributesUpdated({groupID:t,groupAttributeOption:o})}reset(){Dc.reset()}};function au(e,t="tips"){const{ClientSeq:s,From_Account:o,MsgClientTime:n,MsgPriority:i,MsgRandom:r,MsgSeq:a,MsgTimeStamp:c,TinyId:u,ToGroupId:l,GroupInfo:d,MsgBody:p}=e,h=function(e){const{GroupCode:t,GroupId:s,GroupName:o,GroupType:n,MsgFrom_AccountExtraInfo:i,From_Account:r,To_Account:a}=e;return{groupCode:t,groupID:s,groupName:o,type:n,messageFromAccountExtraInformation:i,from:r,to:a}}(d);return{clientSequence:s,from:o,clientTime:n,priority:i,random:r,sequence:a,time:c,tinyID:u,to:l,groupProfile:h,elements:"tips"===t?cu(p):lu(p)}}function cu(e){const t={};return Object.keys(e).forEach((s=>{switch(s){case"MemberNum":t.memberCount=e[s];break;case"OpType":t.operationType=e[s];break;case"Operator_Account":t.operatorID=e[s];break;case"List_Account":t.userIDList=e[s];break;case"MsgMemberExtraInfo":t.memberInfoList=e[s].map((e=>uu(e)));break;case"MsgOperatorMemberExtraInfo":t.operatorInfo=uu(e[s]);break;case"MsgGroupNewInfo":t.newGroupProfile=function(e){const t={};return Object.keys(e).forEach((s=>{switch(s){case"GroupIntroduction":t.introduction=e[s];break;case"GroupName":t.groupName=e[s];break;case"GroupFaceUrl":t.avatar=e[s];break;case"GroupNotification":t.notification=e[s];break;case"ApplyJoinOption":t.joinOption=e[s];break;case"InviteJoinOption":t.inviteOption=e[s];break;case"ShutupAll":t.muteAllMembers=e[s];break;case"Owner_Account":t.ownerID=e[s];break;case"GroupAttrOption":t.groupAttributeOption=function(e){const{BytesChangedKeys:t,GroupAttrSeq:s,OpType:o,PushChangedAttrValFlag:n,GroupAttrInfo:i}=e,r=i.map((e=>{const{Key:t,Val:s,SubKeySeq:o}=e;return{key:t,value:s,sequence:o}}));return{changedKeyList:t,groupAttributeList:r,serverMainSequence:s,operation:o,withChangedAttributeInfo:n}}(e[s])}})),t}(e[s]);break;case"MsgMemberInfo":t.msgMemberInfo=e[s].map((e=>function(e){const{ShutupTime:t,User_Account:s}=e;return{muteTime:t,userID:s}}(e)));break;case"OnlineMemberInfo":t.onlineMemberInfo=function(e){const{ExpireTime:t,OnlineMemberNum:s}=e;return{expireTime:t,onlineMemberNum:s}}(e[s]);break;case"GroupCounterInfo":t.groupCounterInfo=function(e){return e.map((e=>{const{GroupCounterSeq:t,GroupCounter:s,Type:o}=e;return{type:o,groupCounterSeq:t,counterList:s}}))}(e[s])}})),t}function uu(e){const{ImageUrl:t,NickName:s,Role:o,UserId:n}=e;return{avatar:t,nick:s,role:o,userID:n}}function lu(e){const t={};return Object.keys(e).forEach((s=>{switch(s){case"MsgKey":t.messageKey=e[s];break;case"Operator_Account":t.operatorID=e[s];break;case"ReportType":t.operationType=e[s];break;case"Authentication":t.authentication=e[s];break;case"MsgFlag":t.messageRemindType=e[s];break;case"UserDefinedField":t.userDefinedField=e[s];break;case"RemarkInfo":t.remarkInfo=e[s];break;case"BanDuration":t.duration=e[s];break;case"MuteTime":t.muteTime=e[s]}})),t}class du{constructor(e){this.type=na.core.OuterConstant.MSG_GRP_TIP,this.content={},this._initContent(e)}static parseServerPushElement(e){const t=cu(e);return new du(t)}_initContent(e){Object.keys(e).forEach((t=>{switch(t){case"groupProfile":this._initGroupProfile(e[t]);break;case"operatorInfo":this._initOperatorInfo(e[t]);break;case"memberInfoList":case"msgMemberInfo":this._updateMemberList(e[t]);break;case"newGroupProfile":this._initNewGroupProfile(e[t]);break;case"memberExtraInfo":case"remarkInfo":case"onlineMemberInfo":break;default:this.content[t]=e[t]}})),this.content.userIDList||(this.content.userIDList=[this.content.operatorID])}_initGroupProfile(e){this.content.groupProfile={};const t=Object.keys(e);for(let s=0;s<t.length;s++){const o=t[s];Ba[o]&&(this.content.groupProfile[o]=e[o])}}_initOperatorInfo(e){this.content.operatorInfo={};const t=Object.keys(e);for(let s=0;s<t.length;s++){const o=t[s];this.content.operatorInfo[o]=e[o]}}_updateMemberList(e){this.content.memberList?this.content.memberList.forEach((t=>{e.forEach((e=>{t.userID===e.userID&&Object.assign(t,e)}))})):this.content.memberList=e}_initNewGroupProfile(e){this.content.newGroupProfile={};const t=Object.keys(e);for(let s=0;s<t.length;s++){const o=t[s];"muteAllMembers"!==o?this.content.newGroupProfile[o]=e[o]:this.content.newGroupProfile.muteAllMembers=1===e.muteAllMembers}}}var pu=new class{constructor(){this._name="GroupTipsNotification"}init(e){this._core=e;const{common:{workflowManager:t},constants:{WORKFLOW_NAME:s,WORKFLOW_STEP:o}}=e,{message:{messageFactory:n},OuterConstant:i}=e;null==n||n.registerElementClass(i.MSG_GRP_TIP,du),t.registerWorkflowStep(s.SYNC_SERVER_INFO_AFTER_RE_ONLINE,o.GROUP_TIPS_RECOVER,this._handleGroupTipsRecover,this)}onNewGroupTips(e){const{messageList:t,conversationUpdateFieldList:s}=this._handleGroupTips(e),{notificationCenter:o,OuterEvent:n,appStore:i}=this._core;null==s||s.forEach((e=>{const{conversationID:t,lastMessage:s,unreadCount:o}=e;i.conversationStore.updateConversation(t,{lastMessage:s,unreadCount:o})})),t.length>0&&(o.emitOuterEvent(n.MESSAGE_RECEIVED,{name:n.MESSAGE_RECEIVED,data:t}),this._handleGroupTipMessage(t))}_handleGroupTips(e,t=!0){const{Event:s,GroupTips:o}=e,n=new Map,i=[],r=[];for(let e=0,i=o.length;e<i;e++){const i=au(o[e],"tips");if(s===qa){if(ru.isGroupAttributesUpdated(i)){ru.handleGroupAttributesUpdated(i);continue}if(tu.isGroupCounterUpdated(i)){tu.handleGroupCounterUpdated(i);continue}}const{groupProfile:{groupID:a}}=i;if(!Mc.hasLocalGroup(a))continue;const c=this._assembleMessage(i);if(s===qa&&(c._onlineOnlyFlag=!0,r.push(c)),s===$a){if(!this._core.message.messageDataHandler.storeConversationMessage(c)&&t)continue;r.push(c)}this._handleConversationOptions(n,c)}return i.push(...n.values()),{conversationUpdateFieldList:i,messageList:r}}_assembleMessage(e){const{OuterConstant:t,message:{messageFactory:s}}=this._core;e.flow="in",e.conversationType=t.CONV_GROUP;const o=s.createMessage(e);this._patchNickAndAvatar(e.elements,o);const n=new du(Object.assign(Object.assign({},e.elements),{groupProfile:Object.assign({},e.groupProfile)}));return o.setElement(n),o.isSystemMessage=!1,o}_patchNickAndAvatar(e,t){const{utils:{isEmpty:s},OuterConstant:{GROUP_TIPS_OPERATION_TYPE:o}}=this._core,{operationType:n,memberInfoList:i,operatorInfo:r}=e;let a={};if(s(i)?s(r)||(a=r):n!==o.JOINED&&n!==o.KICKED&&n!==o.ADMIN_SET&&n!==o.ADMIN_CANCELED||(a=Object.assign({},i[0])),!s(a)){const{nick:e="",avatar:s=""}=a;t.nick=e,t.avatar=s}}_handleConversationOptions(e,t){const{common:{getMessagePreviewText:s},utils:{isObject:o}}=this._core,{conversationID:n,conversationType:i}=t;let r;if(e.has(n))r=e.get(n),"in"===t.flow&&(t._isExcludedFromUnreadCount||t._onlineOnlyFlag||r.unreadCount++),r.type=i,r.lastMessage=t._isExcludedFromLastMessage?"":Object.assign({},t);else{let e=0;"in"===t.flow&&(t._isExcludedFromUnreadCount||t._onlineOnlyFlag||(e=1)),r={conversationID:n,unreadCount:e,type:i,lastMessage:t._isExcludedFromLastMessage?"":Object.assign({},t)}}o(r.lastMessage)&&(r.lastMessage.messageForShow=s(r.lastMessage.type,r.lastMessage.payload)),e.set(n,r)}_handleGroupTipMessage(e){const{OuterConstant:{GROUP_TIPS_OPERATION_TYPE:t}}=this._core;e.forEach((e=>{const{operationType:s}=e.payload;switch(s){case t.JOINED:this._handleNewMemberJoined(e);break;case t.QUITTED:this._handleMemberQuitted(e);break;case t.KICKED:this._handleMemberKicked(e);break;case t.GROUP_PROFILE_UPDATED:this._handleGroupProfileUpdated(e)}}))}_handleNewMemberJoined(e){this._handleGroupMemberCountUpdated(e)}_handleMemberQuitted(e){this._handleGroupMemberCountUpdated(e)}_handleMemberKicked(e){this._handleGroupMemberCountUpdated(e)}_handleGroupProfileUpdated(e){var t;const{newGroupProfile:s,groupProfile:o,operatorInfo:n}=e.payload,{groupID:i}=o,r=Mc.getLocalGroup(i);Object.keys(s).forEach((e=>{switch(e){case"ownerID":this._handleGroupOwnerChanged(i,s);break;case"groupName":r.name=s[e];break;default:r[e]=s[e]}}));const{utils:{isUndefined:a}}=this._core;a(n)||(null===(t=null==r?void 0:r.selfInfo)||void 0===t?void 0:t.userID)!==n.userID||Object.keys(n).forEach((e=>{"nameCard"===e&&r.updateSelfInfo({nameCard:n[e]}),"role"===e&&this._updateSelfRole(r,n[e])})),Mc.emitGroupListUpdate(),Mc.updateConversationGroupProfile(i)}_handleGroupOwnerChanged(e,t){const{common:s,OuterConstant:o}=this._core,n=Mc.getLocalGroup(e),i=s.getCurrentUserID(),{ownerID:r}=t;i===r&&n.updateGroup({ownerID:r,selfInfo:{role:o.GRP_MBR_ROLE_OWNER}})}_updateSelfRole(e,t){const{OuterConstant:s}=this._core;let o=s.GRP_MBR_ROLE_MEMBER;t===xa?o=s.GRP_MBR_ROLE_OWNER:t===Va&&(o=s.GRP_MBR_ROLE_ADMIN),e.updateSelfInfo({role:o})}_handleGroupMemberCountUpdated(e){const{memberCount:t,groupProfile:{groupID:s}}=e.payload,o=Mc.getLocalGroup(s),{utils:{isNumber:n}}=this._core;o&&n(t)&&o.memberCount!==t&&(o.memberCount=t,Mc.emitGroupListUpdate(),Mc.updateConversationGroupProfile(s))}_handleGroupTipsRecover(e){const{utils:{isArray:t}}=this._core,{groupTipList:s}=(null==e?void 0:e.result)||{};t(s)&&s.forEach((e=>{const{messageList:t}=this._handleGroupTips({Event:e.Event,GroupTips:[e]},!1);this._handleGroupTipMessage(t)}))}};class hu{constructor(e){this.type=na.core.OuterConstant.MSG_GRP_SYS_NOTICE,this.content={},this._initContent(e)}static parseServerPushElement(e){const t=lu(e);return new hu(t)}_initContent(e){Object.keys(e).forEach((t=>{switch(t){case"remarkInfo":this.content.handleMessage=e[t];break;case"groupProfile":this._initGroupProfile(e[t]);break;case"memberInfoList":break;default:this.content[t]=e[t]}}))}_initGroupProfile(e){this.content.groupProfile={};const t=Object.keys(e);for(let s=0;s<t.length;s++){const o=t[s];ja[o]&&(this.content.groupProfile[o]=e[o])}}}var gu=new class{constructor(){this._name="GroupSystemNotification"}init(e){this._core=e;const{message:{messageFactory:t},OuterConstant:{MSG_GRP_SYS_NOTICE:s}}=e;null==t||t.registerElementClass(s,hu)}onNewGroupSystemNotification(e){const{GroupTips:t=[],isInstantMessage:s=!0}=e;console.log(`${this._name}.onNewGroupSystemNotification count:${t.length} isInstantMessage:${s}`);const{conversationUpdateFieldList:o,messageList:n}=this._handleGroupSystemNotification(t,s),{notificationCenter:i,OuterEvent:r}=this._core;o.length>0&&this._handleGroupSysTemMessage(s,n),!0===s&&n.length>0&&i.emitOuterEvent(r.MESSAGE_RECEIVED,{name:r.MESSAGE_RECEIVED,data:n})}_handleGroupSystemNotification(e,t){const s=[];let o={};for(let n=0;n<e.length;n++){const i=au(e[n],"system"),{elements:{operationType:r}}=i;if(r===Ja)continue;const a=this._assembleMessage(i);this._core.message.messageDataHandler.storeConversationMessage(a)&&(s.push(a),o=this._handleConversationOptions(a,t))}return o.lastMessage=s[s.length-1],{conversationUpdateFieldList:s.length>0?[o]:[],messageList:s}}_assembleMessage(e){const{message:{messageFactory:t},OuterConstant:s,utils:{randomInt:o}}=this._core;e.flow="in",e.conversationType=s.CONV_SYSTEM,e.conversationSubType=e.groupProfile.type,e.conversationID=s.CONV_SYSTEM;const n=t.createMessage(e),i=new hu(Object.assign(Object.assign({},e.elements),{groupProfile:Object.assign({},e.groupProfile)}));n.setElement(i),n.isSystemMessage=!0;const r=1===n.sequence&&1===n.random,a=2===n.sequence&&2===n.random;return(r||a)&&(n.sequence=o(),n.random=o(),n.generateMessageID()),n}_handleConversationOptions(e,t){const{OuterConstant:s}=this._core,o={conversationID:s.CONV_SYSTEM,unreadCount:0,type:s.CONV_SYSTEM,subType:e.conversationSubType,lastMessage:null};return t&&o.unreadCount++,o}_handleGroupSysTemMessage(e,t){e&&t.forEach((e=>{const{operationType:t}=e.payload;switch(t){case Ka:this._handleGroupJoinResult(e);break;case Ha:this._handleMemberKicked(e);break;case Wa:this._handleGroupDismissed(e);break;case Ya:this._handleGroupInvitedResult(e);break;case za:this._handleGroupQuitResult(e);break;case Qa:this._handleMessageRemindTypeSynced(e);break;case Xa:this._handleAVChatRoomMemberBanned(e)}}))}_handleGroupJoinResult(e){const{groupProfile:t}=e.payload,{groupID:s,type:o}=t,n=Mc.hasLocalGroup(s);console.log(`${this._name}._handleGroupJoinResult groupID:${s} type:${o} hasLocalGroup:${n}`),n||_c(o)||(Mc.updateLocalGroup([Object.assign({},t)]),Mc.emitGroupListUpdate())}_handleMemberKicked(e){const{groupProfile:{groupID:t,type:s}}=e.payload;Mc.hasLocalGroup(t)&&this._deleteLocalGroup(t,s),this._updateConversationProfile(t,{unreadCount:0})}_handleGroupDismissed(e){const{groupProfile:{groupID:t,type:s}}=e.payload;Mc.hasLocalGroup(t)&&this._deleteLocalGroup(t,s),this._updateConversationProfile(t,{unreadCount:0})}_handleGroupInvitedResult(e){const{groupProfile:t}=e.payload,{groupID:s}=t,o=Mc.hasLocalGroup(s);console.log(`${this._name}._handleGroupInvitedResult groupID:${s} hasLocalGroup:${o}`),o||(Mc.updateLocalGroup([Object.assign({},t)]),Mc.emitGroupListUpdate())}_handleGroupQuitResult(e){const{groupProfile:{groupID:t,type:s}}=e.payload,o=Mc.hasLocalGroup(t);console.log(`${this._name}._handleGroupQuitResult groupID:${t} type:${s} hasLocalGroup:${o}`),o&&this._deleteLocalGroup(t,s),this._updateConversationProfile(t,{unreadCount:0})}_handleMessageRemindTypeSynced(e){const{groupProfile:{groupID:t},messageRemindType:s}=e.payload;this._updateConversationProfile(t,{messageRemindType:s})}_handleAVChatRoomMemberBanned(e){const{groupProfile:{groupID:t,type:s}}=e.payload;this._deleteLocalGroup(t,s)}_deleteLocalGroup(e,t){if(_c(t)){const{appStore:{conversationStore:t},OuterConstant:{CONV_GROUP:s}}=this._core;t.deleteConversation(`${s}${e}`)}Mc.deleteLocalGroup(e),Mc.emitGroupListUpdate()}_updateConversationProfile(e,t){const{appStore:{conversationStore:s},OuterConstant:{CONV_GROUP:o}}=this._core,n=`${o}${e}`;s.getConversation(n)&&s.updateConversation(n,t)}};var _u=new class{init(e){this._core=e,console.log("GroupNotificationHandler.init"),pu.init(e),gu.init(e);const{notificationCenter:t,InnerEvent:s}=e,{InnerEventSubType:o}=t;t.subscribeInnerEvent(s.MESSAGE_PUSH,o.GROUP_TIPS_NOTIFICATION,this._onNewGroupTipsNotification,this),t.subscribeInnerEvent(s.MESSAGE_PUSH,o.GROUP_SYSTEM_NOTIFICATION,this._onNewGroupSystemNotification,this),t.subscribeInnerEvent(s.DESTROY,this._dispose,this)}_onNewGroupTipsNotification(e){pu.onNewGroupTips(e)}_onNewGroupSystemNotification(e){gu.onNewGroupSystemNotification(e)}_dispose(){const{notificationCenter:e,InnerEvent:t}=this._core,{InnerEventSubType:s}=e;e.unSubscribeInnerEvent(t.MESSAGE_PUSH,s.GROUP_TIPS_NOTIFICATION,this._onNewGroupTipsNotification,this),e.unSubscribeInnerEvent(t.MESSAGE_PUSH,s.GROUP_SYSTEM_NOTIFICATION,this._onNewGroupSystemNotification,this)}};const mu={required:!0,rules:["string"],allowEmpty:!1},vu={required:!0,rules:["number"],allowEmpty:!1},fu={required:!0,rules:["array"],allowEmpty:!1},Iu={required:!0,rules:["object"],allowEmpty:!1},Su={createGroup:{name:mu,type:mu},dismissGroup:[Object.assign({key:"groupID"},mu)],joinGroup:{groupID:mu,applyMessage:{required:!1,rules:["string"],allowEmpty:!0}},quitGroup:[Object.assign({key:"groupID"},mu)],searchGroupByID:[Object.assign({key:"groupID"},mu)],getGroupProfile:{groupID:mu,groupCustomFieldFilter:{required:!1,rules:["array"],allowEmpty:!0}},updateGroupProfile:{groupID:mu,muteAllMembers:{required:!1,rules:["boolean"],allowEmpty:!1}},changeGroupOwner:{groupID:mu,newOwnerID:mu},getGroupOnlineMemberCount:[Object.assign({key:"groupID"},mu)],handleGroupApplication:{handleAction:mu},getGroupMemberList:{groupID:mu},getGroupMemberProfile:{groupID:mu,userIDList:fu,memberCustomFieldFilter:{required:!1,rules:["array"],allowEmpty:!0}},addGroupMember:{groupID:mu,userIDList:fu},deleteGroupMember:{groupID:mu,userIDList:fu},setGroupMemberMuteTime:{groupID:mu,userID:mu,muteTime:Object.assign(Object.assign({},vu),{customValidator:e=>!(e<0)||"muteTime must be a non-negative number."})},setGroupMemberRole:{groupID:mu,userID:mu,role:mu},setGroupMemberNameCard:{groupID:mu,userID:{required:!1,rules:["string"],allowEmpty:!1},nameCard:mu},setGroupMemberCustomField:{groupID:mu,userID:{required:!1,rules:["string"],allowEmpty:!1},memberCustomField:fu},markGroupMemberList:{groupID:mu,markType:Object.assign(Object.assign({},vu),{customValidator:e=>!(e<1e3)||"markType must be greater than or equal to 1000."}),enableMark:{required:!0,rules:["boolean"],allowEmpty:!1},userIDList:fu},initGroupAttributes:{groupID:mu,groupAttributes:Iu},setGroupAttributes:{groupID:mu,groupAttributes:Iu},deleteGroupAttributes:{groupID:mu,keyList:Object.assign(Object.assign({},fu),{allowEmpty:!0})},getGroupAttributes:{groupID:mu,keyList:Object.assign(Object.assign({},fu),{allowEmpty:!0})},getGroupCounters:{groupID:mu,keyList:{required:!1,rules:["array"],allowEmpty:!0}},setGroupCounters:{groupID:mu,counters:Iu},increaseGroupCounter:{groupID:mu,key:mu,value:vu},decreaseGroupCounter:{groupID:mu,key:mu,value:vu}},Eu={getGroupList:!0,createGroup:!0,dismissGroup:!0,joinGroup:!0,quitGroup:!0,searchGroupByID:!0,getGroupProfile:!0,updateGroupProfile:!0,changeGroupOwner:!0,getGroupOnlineMemberCount:!0,getGroupApplicationList:!0,handleGroupApplication:!0,getGroupMemberList:!0,getGroupMemberProfile:!0,addGroupMember:!0,deleteGroupMember:!0,setGroupMemberMuteTime:!0,setGroupMemberRole:!0,setGroupMemberNameCard:!0,setGroupMemberCustomField:!0,markGroupMemberList:!0,initGroupAttributes:!0,setGroupAttributes:!0,getGroupAttributes:!0,deleteGroupAttributes:!0,getGroupCounters:!0,setGroupCounters:!0,increaseGroupCounter:!0,decreaseGroupCounter:!0};var Cu=new class{constructor(){this._installedSubPlugins=[],this.groupDataHandler=Mc,this.groupAction=Fc,this.groupAttribute=ru,this.groupMember=Xc,this.name="Group"}install(e,t=[]){this._core=e,na.init(e),Mc.init(e),Fc.init(e,this),Xc.init(e,this),xc.init(e),tu.init(e),ru.init(e),_u.init(e),e.helper.registerValidateConfig({auth:Eu,params:Su}),this._installSubPlugins(t);const{notificationCenter:s,InnerEvent:o}=e;s.subscribeInnerEvent(o.LOGOUT,this._reset,this),s.subscribeInnerEvent(o.DESTROY,this._dispose,this)}getInstalledSubPlugins(){return this._installedSubPlugins}_installSubPlugins(e){const{utils:{isArray:t}}=this._core;e&&t(e)&&e.forEach((e=>{var t;this._installedSubPlugins.includes(e.name)||(null===(t=e.install)||void 0===t||t.call(e,this._core,this),this._installedSubPlugins.push(e.name))}))}_reset(){Mc.reset(),ru.reset(),tu.reset()}_dispose(){this._reset();const{notificationCenter:e,InnerEvent:t}=this._core;e.unSubscribeInnerEvent(t.LOGOUT,this._reset,this),e.unSubscribeInnerEvent(t.DESTROY,this._dispose,this)}};const Mu=new class{init(e){this.core=e}};const yu="AV_MBR_LIST",Tu="AV_BAN_MBR",Au={NORMAL_MESSAGE:3,GROUP_TIPS_HAS_ROAMING:4,GROUP_SYSTEM_MESSAGE:5,GROUP_TIPS_HAS_NO_ROAMING:6,BROADCAST_MESSAGE:17,MESSAGE_REVOKED:20,MESSAGE_REACTION:21,LIVE_CUSTOM_DATA:100},Ou={GROUP_DISMISSED:5,QUIT_GROUP:8,AVCHATROOM_MEMBER_BANNED:21},Du=60,Ru=2603,Lu=2686,Nu=2688,bu=3122;class Gu{constructor(e){const{core:t,manager:s,groupID:o,getRequestParams:n,onSuccess:i,onFail:r}=e;this._name="Polling",this._core=t,this._manager=s,this._timeoutID=-1,this._isRunning=!1,this._groupID=o,this._getRequestParams=n,this._onSuccess=i,this._onFail=r}start(){this._isRunning=!0,this._request(),console.log(`${this._name}.start pollingInterval:${this._manager.getPollingInterval()}`)}isRunning(){return this._isRunning}_request(){return h(this,void 0,void 0,(function*(){try{const e=this._getRequestParams(this._groupID),t=yield function(e,t){return h(this,void 0,void 0,(function*(){const{longPollingKey:s,startSequence:o,startBroadcastSeq:n,simplifiedMessage:i}=e,r={Key:s,StartSeq:o,StartBroadcastSeq:n,DownsizeFlag:i,USP:1,HoldTime:90};return t.common.buildAndSendPacket({servcmd:"group_open_long_polling_http_svc.get_msg",data:r})}))}(e,this._core);this._onSuccess(this._groupID,t);const s=this._manager.getPollingInterval();this._runNextPolling(s)}catch(e){this._onFail(this._groupID,e),this._runNextPolling(2e3)}}))}_runNextPolling(e){this.isRunning()&&(this._timeoutID>-1&&clearTimeout(this._timeoutID),this._timeoutID=setTimeout(this._request.bind(this),e))}stop(){console.log(`${this._name}.stop`),this._timeoutID>-1&&(clearTimeout(this._timeoutID),this._timeoutID=-1),this._isRunning=!1}}class wu{constructor(e){this._maxLength=e,this._map=new Map}set(e){var t;if(this._map.size>=this._maxLength){const e=(null===(t=this._map.entries().next().value)||void 0===t?void 0:t[0])||"";this._map.delete(e)}this._map.set(e,1)}has(e){return this._map.has(e)}delete(e){this.has(e)&&this._map.delete(e)}clear(){this._map.clear()}}const Pu=e=>e===Au.GROUP_TIPS_HAS_NO_ROAMING||e===Au.GROUP_TIPS_HAS_ROAMING,Uu=e=>e===Au.GROUP_SYSTEM_MESSAGE;function ku(e){const t=function(e){const{E:t,MCT:s,MR:o,MP:n,MTS:i,GId:r,MS:a,CCD:c,F_Account:u,IsSys:l,GInf:d,MsgBody:h}=e,g=p(e,["E","MCT","MR","MP","MTS","GId","MS","CCD","F_Account","IsSys","GInf","MsgBody"]);return Object.assign({Event:t,MsgClientTime:s,MsgRandom:o,MsgPriority:n,MsgTimeStamp:i,ToGroupId:r,MsgSeq:a,CloudCustomData:c,From_Account:u,IsSystemMsg:l,GroupInfo:Fu(d),MsgBody:$u(h)},g)}(e);return function(e){const{Event:t}=e;(Pu(t)||Uu(t))&&(e.From_Account=e.From_Account||"@TIM#SYSTEM");s=t,(s===Au.BROADCAST_MESSAGE||(e=>e===Au.NORMAL_MESSAGE)(t))&&function(e){const{core:{OuterConstant:t}}=Mu;e.CloudCustomData=e.CloudCustomData||"",e.MsgBody=e.MsgBody.map((e=>{if(e.MsgType===t.MSG_CUSTOM){const{content:t={}}=e;e.content=Object.assign({Data:"",Desc:"",Ext:""},t)}return e}))}(e);var s;Pu(t)&&function(e){const{GroupJoinType:t,MsgOperatorMemberExtraInfo:s={},MsgMemberExtraInfo:o,Operator_Account:n,List_Account:i,OpType:r}=e.MsgBody||{};"number"==typeof t||1!==r&&2!==r||(e.MsgBody.GroupJoinType=2===r?0:1);o||(e.MsgBody.MsgMemberExtraInfo=i.map((e=>({UserId:e}))));1!==r||o||(e.MsgBody.MsgMemberExtraInfo=[{UserId:s.UserId}]);e.MsgBody.MsgOperatorMemberExtraInfo=Object.assign({Operator_Account:n,ImageUrl:"",NickName:""},s)}(e);Uu(t)&&function(e){const{MsgOperatorMemberExtraInfo:t={},Operator_Account:s}=e.MsgBody||{};e.MsgBody.MsgMemberExtraInfo=Object.assign({UserId:s,ImageUrl:"",NickName:""},t),e.MsgBody=Object.assign({Authentication:"",RemarkInfo:"",MsgKey:1e3*e.MsgTimeStamp},e.MsgBody),e.MsgBody=Object.keys(e.MsgBody).filter((e=>"MsgOperatorMemberExtraInfo"!==e)).reduce(((t,s)=>Object.assign(Object.assign({},t),{[s]:e.MsgBody[s]})),{})}(e)}(t),t}function Fu(e){const t=e||{},{GN:s,GT:o,F_Hd:n,F_NN:i}=t,r=p(t,["GN","GT","F_Hd","F_NN"]),a=Object.assign({GroupName:s,GroupType:o},r);return n&&(a.From_AccountHeadurl=n),i&&(a.From_AccountNick=i),a}function $u(e){let t=e;Array.isArray(e)||(t=[e]);const s=t.map((e=>{const{O_Account:t,Opt:s,L_Account:o,RT:n,UDF:i,OpInf:r,OnlineInf:a,MsgMemberExtraInfo:c}=e,u=p(e,["O_Account","Opt","L_Account","RT","UDF","OpInf","OnlineInf","MsgMemberExtraInfo"]),l=Object.assign({Operator_Account:t,OpType:s,List_Account:o,ReportType:n,UserDefinedField:i},u);return r&&(l.MsgOperatorMemberExtraInfo=function(e){const{Img:t,NN:s}=e,o=p(e,["Img","NN"]);return Object.assign({ImageUrl:t,NickName:s},o)}(r)),c&&(l.MsgMemberExtraInfo=function(e){return e.map((e=>{const{Img:t,NN:s}=e,o=p(e,["Img","NN"]);return Object.assign({ImageUrl:t,NickName:s},o)}))}(c)),a&&(l.OnlineMemberInfo=function(e){const{ET:t,Num:s}=e;return{ExpireTime:t,OnlineMemberNum:s}}(a)),l}));return Array.isArray(e)?s:s[0]}var qu=new class{constructor(){this._name="MessageParser",this._sequenceList=new wu(200),this._messageIDList=new wu(100),this._broadcastMessageIDMap=new Map,this._reportMessageStackedCount=0}init(e,t){this._core=e,this._avChatRoomHandler=t}onMessageReceived(e,t,s=!1){this._sortServerMessageList({groupID:e,serverMessageList:t,isHistoryMessage:s});const o=this._handleMessageList(e,t);if(0===o.length)return;if(!s){const{appStore:{conversationStore:t},OuterConstant:{CONV_GROUP:s}}=this._core,n=(e=>{const{core:{common:{getMessagePreviewText:t}}}=Mu;return{lastTime:(null==e?void 0:e.time)||(null==e?void 0:e.lastTime)||0,lastSequence:(null==e?void 0:e.sequence)||(null==e?void 0:e.lastSequence)||0,fromAccount:(null==e?void 0:e.from)||(null==e?void 0:e.fromAccount)||"",messageForShow:t(null==e?void 0:e.type,null==e?void 0:e.payload),payload:(null==e?void 0:e.payload)||null,type:(null==e?void 0:e.type)||"",isRevoked:(null==e?void 0:e.isRevoked)||!1,cloudCustomData:(null==e?void 0:e.cloudCustomData)||"",onlineOnlyFlag:(null==e?void 0:e._onlineOnlyFlag)||!1,nick:(null==e?void 0:e.nick)||"",nameCard:(null==e?void 0:e.nameCard)||"",version:(null==e?void 0:e.version)||0,isPeerRead:(null==e?void 0:e.isPeerRead)||!1,revoker:(null==e?void 0:e.revoker)||null}})(o[o.length-1]);t.updateConversation(`${s}${e}`,{lastMessage:n})}this._checkMessageStacked(o);const n=o.filter((e=>!0===e.isModified)),i=o.filter((e=>!1===e.isModified)),{OuterEvent:{MESSAGE_RECEIVED:r,MESSAGE_MODIFIED:a}}=this._core;n.length>0&&this._emitEvent({name:a,data:n}),i.length>0&&this._emitEvent({name:r,data:i})}_sortServerMessageList(e){const{groupID:t,serverMessageList:s,isHistoryMessage:o}=e;let n=[];this._avChatRoomHandler.isPollingSimplifiedMessage()&&!o?(s.sort(((e,t)=>e.MS-t.MS)),n=s.map((e=>e.MS))):(s.sort(((e,t)=>e.MsgSeq-t.MsgSeq)),n=s.map((e=>e.MsgSeq))),console.log(`${this._name}._sortServerMessageList groupID:${t} count:${n.length} sequenceList:${n}`),n.length=0}_handleMessageList(e,t){const{message:{messageDataHandler:s,messageHelper:o}}=this._core,n=this._avChatRoomHandler.isPollingSimplifiedMessage(),i=[],r=t.length;for(let a=0;a<r;a++){let r=t[a];if(n&&(r=ku(r)),Uu(r.Event)&&Object.values(Ou).includes(r.MsgBody.ReportType)){this._onGroupDismissed(e);break}if(null===this._filterMessageItem(r))continue;this._patchMessageType(r);const c=o.parseServerGroupMessage(r),u=this._createMessage(c);Pu(r.Event)&&this._avChatRoomHandler.isGroupAttributesUpdated(c)?this._avChatRoomHandler.handleGroupAttributesUpdated(c):null!==this._filterDuplicateMessage(u)&&(s.isMessageSentByCurrentInstance(u)||(1===c.isModified&&(u.isModified=!0),Pu(r.Event)&&this._updateLocalOnlineMemberCountFromTips(r),i.push(u)))}return i}_patchMessageType(e){const{OuterConstant:t}=this._core;Pu(e.Event)&&(e.MsgBody.MsgType=t.MSG_GRP_TIP),Uu(e.Event)&&(e.MsgBody.MsgType=t.MSG_GRP_SYS_NOTICE)}_filterMessageItem(e){const{Event:t}=e;return Object.values(Au).includes(t)?(e=>e===Au.MESSAGE_REVOKED)(t)?(this._handleMessageRevoked(e),null):(e=>e===Au.LIVE_CUSTOM_DATA)(t)?(this._onLiveCustomData(e),null):(e=>e===Au.MESSAGE_REACTION)(t)?null:e:(console.warn(`${this._name}.onMessageReceived unknown event:${t}`),null)}_createMessage(e){const{message:{messageFactory:t},OuterConstant:s}=this._core;let o=s.CONV_GROUP;e.event===Au.GROUP_SYSTEM_MESSAGE&&(o=s.CONV_SYSTEM);const n=!!e.isSystemMessage,i=t.createMessage(Object.assign(Object.assign({},e),{conversationType:o,isSystemMessage:n,flow:"in"}));return i.setElement(e.elements),i}_filterDuplicateMessage(e){const{common:t}=this._core;if(!t.isUnlimitedAVChatRoom()){if(this._sequenceList.has(e.sequence))return null;this._sequenceList.set(e.sequence)}const s=this._messageIDList.has(e.ID);return s?(console.warn(`${this._name}_filterDuplicateMessageItem ID:${e.ID} has:${s}`),null):(this._messageIDList.set(e.ID),e)}_handleMessageRevoked(e){const{OuterConstant:t,OuterEvent:{MESSAGE_REVOKED:s}}=this._core,{ToGroupId:o,MsgBody:{RevokeMsgList:n},RevokerInfo:{Revoker_Account:i,Reason:r=""}}=e,a=[];n.forEach((e=>{const{TinyId:s,MsgClientTime:n,Random:c,MsgSeq:u}=e,l={conversationID:`${t.CONV_GROUP}${o}`,ID:`${s}-${n}-${c}`,revoker:i,revokeReason:r,revokerInfo:{userID:i,nick:"",avatar:""},sequence:u};a.push(l)})),0!==a.length&&this._emitEvent({name:s,data:a})}_onLiveCustomData(e){const{OuterEvent:{ROOM_CUSTOM_DATA_RECEIVED:t}}=this._core,{ToGroupId:s,MsgSeq:o,MsgTimeStamp:n,MsgBody:i}=e,r=(null==i?void 0:i.MsgContent)||"";this._emitEvent({name:t,data:r}),console.log(`${this._name}._onLiveCustomData groupID:${s} sequence:${o} time:${n} data:${r}`)}_onGroupDismissed(e){this._avChatRoomHandler.reset(e)}_checkMessageStacked(e){const{length:t}=e;if(t>=100&&this._reportMessageStackedCount<5){const e=this._avChatRoomHandler.getJoinedGroups();this._core.ssoLog.createSSOLogData({method:"MessageStacked"}).setLogInfo({message:`count:${t} groupID:${e.join(",")}`}).end(),this._reportMessageStackedCount+=1}}_emitEvent(e){this._core.notificationCenter.emitOuterEvent(e.name,e)}onBroadcastMessageReceived(e){const{message:{messageHelper:t},OuterEvent:{MESSAGE_RECEIVED:s}}=this._core,o=this._avChatRoomHandler.isPollingSimplifiedMessage(),n=[],i=e.length;for(let s=0;s<i;s++){let i=e[s];o&&(i=ku(i));const r=t.parseServerGroupMessage(i);if(!Object.values(Au).includes(i.Event)){console.warn(`${this._name}.onBroadcastMessageReceived unknown event:${i.Event}`);continue}const a=this._createMessage(r);a.isBroadcastMessage=!0,this._broadcastMessageIDMap.has(a.ID)||(n.push(a),this._broadcastMessageIDMap.set(a.ID,1))}n.length>0&&this._emitEvent({name:s,data:n})}_updateLocalOnlineMemberCountFromTips(e){const{utils:{isEmpty:t}}=this._core,{ToGroupId:s,MsgBody:{OnlineMemberInfo:o}}=e;if(t(o))return;const{OnlineMemberNum:n=0,ExpireTime:i=Du}=o,r=Date.now();let a=this._avChatRoomHandler.getLocalOnlineMemberCount(s);t(a)?a={lastReqTime:0,lastSyncTime:0,latestUpdateTime:r,memberCount:n,expireTime:i}:(a.latestUpdateTime=r,a.memberCount=n),this._avChatRoomHandler.updateLocalOnlineMemberCount(s,a)}reset(){this._reportMessageStackedCount=0,this._sequenceList.clear(),this._messageIDList.clear(),this._broadcastMessageIDMap.clear()}};const xu=e=>{const{core:{store:t}}=Mu;return(t.get("cloudConfig")||{})[e]},Vu=e=>{const{core:{utils:{isUndefined:t}}}=Mu;return!t(e)},Bu=()=>{const e=xu("polling_interval");return Vu(e)?parseInt(e,10):300},ju=()=>{const e=xu("polling_simplified_msg");return Vu(e)?parseInt(e,10):0};var Ku=new class{constructor(){this._name="AVChatRoomHandler",this._joinedGroupMap=new Map,this._pollingRequestInfoMap=new Map,this._pollingInstanceMap=new Map,this._onlineMemberCountMap=new Map,this._pollingInterval=300,this._pollingNoMessageCount=0,this._startBroadcastSequence=1}init(e,t){this._core=e,this._parentPlugin=t,qu.init(e,this),console.log("AVChatRoomHandler.init")}onAVChatRoomSystemNotification(e){const{OuterConstant:{GRP_AVCHATROOM:t}}=this._core,{GroupTips:s=[]}=e;for(let e=0;e<s.length;e++){const{MsgBody:o,GroupInfo:{GroupId:n,GroupType:i}}=s[e],r=Object.values(Ou).includes(o.ReportType);i===t&&r&&this.reset(n)}}getPollingInterval(){return this._pollingInterval}isPollingSimplifiedMessage(){return 0!==ju()}isGroupAttributesUpdated(e){return!!this._parentPlugin.groupAttribute.isGroupAttributesUpdated(e)&&(this._parentPlugin.groupAttribute.handleGroupAttributesUpdated(e),!0)}updateLocalOnlineMemberCount(e,t){this._onlineMemberCountMap.set(e,t)}getLocalOnlineMemberCount(e){return this._onlineMemberCountMap.get(e)||{}}hasPollingInstance(e){return this._pollingInstanceMap.has(e)}getJoinedLiveList(){let e=[];return this._joinedGroupMap.size>0&&(e=[...this._joinedGroupMap.values()].filter((e=>e.type===TYPES.GRP_LIVE))),e}handleJoinGroupResult(e){return h(this,void 0,void 0,(function*(){const{utils:{isUndefined:t},OuterConstant:{CONV_GROUP:s},apiMap:{getConversationProfile:o},OuterConstant:n}=this._core,{longPollingKey:i,group:r,historyMessageList:a}=e,{groupID:c}=r;return yield this._preCheck(r),this._joinedGroupMap.set(c,r),this._parentPlugin.groupDataHandler.updateLocalGroup([r]),this._parentPlugin.groupDataHandler.emitGroupListUpdate(),o(`${s}${c}`),a.length>0&&qu.onMessageReceived(c,a,!0),t(i)?{status:n.JOIN_STATUS_SUCCESS,group:r}:this.startMessageLongPolling(e)}))}_preCheck(e){return h(this,void 0,void 0,(function*(){const{common:t,OuterConstant:s,helper:o,apiMap:{quitGroup:n}}=this._core;if(t.isUnlimitedAVChatRoom()){if(this._pollingInstanceMap.size>(()=>{const e=xu("polling_count_limit");return Vu(e)&&e>0?parseInt(e,10):20})())throw new o.ChatError({code:Nu,message:"the count of longPolling exceeds the max limit"});return}if(0===this._joinedAVChatRoomCount())return;if(e.type===s.GRP_LIVE)return;const[i,r]=this._joinedGroupMap.entries().next().value;r.selfInfo.role===s.GRP_MBR_ROLE_OWNER?this._parentPlugin.groupDataHandler.deleteLocalGroup(i):yield n(i),this.reset(i)}))}startMessageLongPolling(e){const{OuterConstant:t}=this._core,{longPollingKey:s,startSequence:o=1,group:n}=e,{groupID:i}=n;return this._pollingRequestInfoMap.set(i,{longPollingKey:s,startSequence:o}),this._pollingInterval=Bu(),this._startPolling(i),{status:t.JOIN_STATUS_SUCCESS,group:n}}_startPolling(e){if(console.log(`${this._name}._startPolling groupID:${e}`),this._pollingInstanceMap.has(e)){const t=this._pollingInstanceMap.get(e);return void((null==t?void 0:t.isRunning())||null==t||t.start())}const t=new Gu({core:this._core,manager:this,groupID:e,getRequestParams:this._handleRequestParams.bind(this),onSuccess:this._handleSuccess.bind(this),onFail:this._handleFailure.bind(this)});t.start(),this._pollingInstanceMap.set(e,t)}_handleRequestParams(e){const{longPollingKey:t,startSequence:s}=this._pollingRequestInfoMap.get(e)||{};return e===[...this._pollingInstanceMap.keys()][0]?{longPollingKey:t,startSequence:s,startBroadcastSeq:this._startBroadcastSequence,simplifiedMessage:ju()}:{longPollingKey:t,startSequence:s,simplifiedMessage:ju()}}_handleSuccess(e,t){const{ErrorCode:s}=t;if(0===s)this._hasJoinedAVChatRoom(e)&&this._handleResponseData(e,t);else{const{longPollingKey:t,startSequence:o}=this._pollingRequestInfoMap.get(e)||{};console.warn(`${this._name}._handleSuccess groupID:${e} key:${t} startSeq:${o} errorCode:${s}`)}}_handleResponseData(e,t){const{Key:s,NextSeq:o,NextBroadcastSeq:n,RspMsgList:i=[],RspBroadcastMsgList:r=[]}=t;s&&o&&this._pollingRequestInfoMap.set(e,{longPollingKey:s,startSequence:o}),n&&n>this._startBroadcastSequence&&(this._startBroadcastSequence=n),i.length>0?(0!==this._pollingNoMessageCount&&(this._pollingNoMessageCount=0,this._pollingInterval=Bu()),qu.onMessageReceived(e,i)):(this._pollingNoMessageCount+=1,this._pollingNoMessageCount===(()=>{const e=xu("polling_no_msg_count");return Vu(e)?parseInt(e,10):20})()&&(this._pollingInterval=Bu()+(()=>{const e=xu("polling_interval_plus");return Vu(e)?parseInt(e,10):2e3})())),r.length>0&&qu.onBroadcastMessageReceived(r)}_handleFailure(e,t){console.warn(`${this._name}._handleFailure groupID:${e} error:`,t)}_joinedAVChatRoomCount(){const{OuterConstant:e}=this._core;let t=[];return this._joinedGroupMap.size>0&&(t=this.getJoinedGroups().filter((t=>t.type===e.GRP_AVCHATROOM))),t.length}_hasJoinedAVChatRoom(e){return this._joinedGroupMap.has(e)}getJoinedGroups(){return[...this._joinedGroupMap.values()]}_stopPolling(e){if(e){console.log(`${this._name}._stopPolling groupID:${e}`);const{appStore:{conversationStore:t},OuterConstant:{CONV_GROUP:s}}=this._core;t.deleteConversation(`${s}${e}`);const o=this._pollingInstanceMap.get(e);return null==o||o.stop(),this._parentPlugin.groupDataHandler.deleteLocalGroup(e),this._pollingInstanceMap.delete(e),this._pollingRequestInfoMap.delete(e),this._joinedGroupMap.delete(e),void this._onlineMemberCountMap.delete(e)}console.log(`${this._name}._stopPolling all`);for(const e of this._pollingInstanceMap.values())e.stop();this._pollingInstanceMap.clear(),this._pollingRequestInfoMap.clear(),this._joinedGroupMap.clear(),this._onlineMemberCountMap.clear()}reset(e){this._stopPolling(e),this._pollingInterval=300,this._pollingNoMessageCount=0,this._startBroadcastSequence=1,qu.reset()}};var Hu=new class{init(e,t){this._core=e,this._parentPlugin=t;const{helper:s}=e;s.registerApi({apiName:"joinGroup",context:this,matcher:()=>t.getInstalledSubPlugins().length>0})}joinGroup(e){return h(this,void 0,void 0,(function*(){const{OuterConstant:t}=this._core,s=yield this._parentPlugin.groupAction.joinGroup(e),{data:{group:{type:o}}}=s;return o===t.GRP_AVCHATROOM?Ku.handleJoinGroupResult(s.data):s}))}};var Wu=new class{init(e,t){this._core=e,this._parentPlugin=t;const{helper:s}=e;s.registerApi({apiName:"quitGroup",context:this,matcher:()=>t.getInstalledSubPlugins().length>0})}quitGroup(e){return h(this,void 0,void 0,(function*(){const{OuterConstant:t}=this._core,s=yield this._parentPlugin.groupAction.quitGroup(e),{data:{type:o}}=s;return o===t.GRP_AVCHATROOM&&Ku.reset(e),s}))}};var Yu=new class{init(e,t){this._core=e,this._parentPlugin=t;const{helper:s}=e;s.registerApi({apiName:"dismissGroup",context:this,matcher:()=>t.getInstalledSubPlugins().length>0})}dismissGroup(e){return h(this,void 0,void 0,(function*(){const{OuterConstant:t}=this._core,s=yield this._parentPlugin.groupAction.dismissGroup(e),{data:{type:o}}=s;return o===t.GRP_AVCHATROOM&&Ku.reset(e),s}))}};var zu=new class{constructor(){this._name="GetAVChatRoomMemberList"}init(e,t){this._core=e,this._parentPlugin=t;const{helper:s}=e;s.registerApi({apiName:"getGroupMemberList",context:this,matcher:()=>t.getInstalledSubPlugins().length>0})}getGroupMemberList(e){return h(this,void 0,void 0,(function*(){const{appStore:{groupStore:t},helper:s,OuterConstant:o}=this._core,{groupID:n}=e,i=t.getGroup(n);if((null==i?void 0:i.type)===o.GRP_AVCHATROOM){if(s.checkBusinessCapabilityBits(yu))return this._getGroupMemberList(e)}return this._parentPlugin.groupMember.getGroupMemberList(e)}))}_getGroupMemberList(e){return h(this,void 0,void 0,(function*(){const t="_getGroupMemberList",{helper:s}=this._core;try{const s=yield function(e,t){return h(this,void 0,void 0,(function*(){const{groupID:s,offset:o=0}=e,n={GroupId:s,Timestamp:o};return t.common.buildAndSendPacket({servcmd:"group_open_avchatroom_http_svc.get_members",data:n})}))}(e,this._core),{MemberList:o=[],NextTimestamp:n=0}=s||{},i=this._handleMemberList(o);return console.log(`${this._name}.${t} ok, groupID:${e.groupID} count:${i.length} nextOffset:${n}`),{code:0,data:{memberList:i,offset:n}}}catch(e){const o=new s.ChatError({functionName:t,code:null==e?void 0:e.errorCode,message:null==e?void 0:e.errorInfo});throw console.error(`${this._name}.${t} fail:`,o),o}}))}_handleMemberList(e){return e.map((e=>{const{Member_Account:t,NickName:s="",Avatar:o="",Remark:n="",JoinTime:i=0,Marks:r=[]}=e;return{userID:t,nick:s,avatar:o,remark:n,joinTime:i,marks:r,isOnline:!0}}))}};var Ju=new class{constructor(){this._name="GetAVChatRoomOnlineMemberCount"}init(e,t){this._core=e,this._parentPlugin=t;const{helper:s}=e;s.registerApi({apiName:"getGroupOnlineMemberCount",context:this,matcher:()=>t.getInstalledSubPlugins().length>0})}getGroupOnlineMemberCount(e){return h(this,void 0,void 0,(function*(){const{appStore:{groupStore:t},OuterConstant:s}=this._core,o=t.getGroup(e);return o?o.type===s.GRP_AVCHATROOM?this._getOnlineMemberCount(e):this._parentPlugin.groupAction.getGroupOnlineMemberCount(e):{code:0,data:{memberCount:0}}}))}_getOnlineMemberCount(e){return h(this,void 0,void 0,(function*(){const t="_getOnlineMemberCount",{utils:{isEmpty:s}}=this._core,o=Ku.getLocalOnlineMemberCount(e);if(s(o)||this._isExpired(e)){const{memberCount:s=0}=yield this._getOnlineMemberCountFromServer(e);return console.log(`${this._name}.${t} ok, groupID:${e} memberCount:${s} from server.`),{code:0,data:{memberCount:s}}}return console.log(`${this._name}.${t} ok, groupID:${e} memberCount:${o.memberCount} from local.`),{code:0,data:{memberCount:o.memberCount}}}))}_isExpired(e){const t=Ku.getLocalOnlineMemberCount(e),s=Date.now(),o=s-t.lastSyncTime>1e3*t.expireTime,n=s-t.latestUpdateTime>1e4,i=s-t.lastReqTime>3e3;return o&&n&&i}_getOnlineMemberCountFromServer(e){return h(this,void 0,void 0,(function*(){const t="_getOnlineMemberCountFromServer";try{const t=yield function(e,t){return h(this,void 0,void 0,(function*(){const s={GroupId:e};return t.common.buildAndSendPacket({servcmd:"group_open_http_svc.get_online_member_num",data:s})}))}(e,this._core),{OnlineMemberNum:s=0,ExpireTime:o=Du}=t||{},n=Date.now(),i={lastSyncTime:n,latestUpdateTime:n,lastReqTime:n,memberCount:s,expireTime:o};return Ku.updateLocalOnlineMemberCount(e,i),{memberCount:s}}catch(e){const s=new this._core.helper.ChatError({functionName:t,code:null==e?void 0:e.errorCode,message:null==e?void 0:e.errorInfo});throw console.error(`${this._name}.${t} fail:`,s),s}}))}};var Qu=new class{constructor(){this._name="DeleteAVChatRoomMember"}init(e,t){this._core=e,this._parentPlugin=t;const{helper:s}=e;s.registerApi({apiName:"deleteGroupMember",context:this,matcher:()=>t.getInstalledSubPlugins().length>0})}deleteGroupMember(e){return h(this,void 0,void 0,(function*(){const t="deleteGroupMember",{appStore:{groupStore:s},utils:{isUndefined:o},helper:n,OuterConstant:i}=this._core,{groupID:r}=e,a=s.getGroup(r);if(o(a))throw new n.ChatError({functionName:t,code:Ru});if(a.type===i.GRP_AVCHATROOM){if(n.checkBusinessCapabilityBits(Tu))return this._deleteGroupMember(e);throw new n.ChatError({functionName:t,code:bu})}return this._parentPlugin.groupMember.deleteGroupMember(e)}))}_deleteGroupMember(e){return h(this,void 0,void 0,(function*(){const t="_deleteGroupMember",{appStore:{groupStore:s},helper:o}=this._core,{groupID:n,duration:i=0,userIDList:r}=e;if(0===i)throw new o.ChatError({functionName:t,code:Lu});try{yield function(e,t){return h(this,void 0,void 0,(function*(){const{groupID:s,userIDList:o,duration:n,reason:i}=e,r={GroupId:s,Members_Account:o,Duration:n,Description:i};return t.common.buildAndSendPacket({servcmd:"group_open_http_svc.ban_group_member",data:r})}))}(e,this._core),console.log(`${this._name}.${t} ok, groupID:${n}`);return{code:0,data:{group:s.getGroup(n),userIDList:r}}}catch(e){const s=new o.ChatError({functionName:t,code:null==e?void 0:e.errorCode,message:null==e?void 0:e.errorInfo});throw console.error(`${this._name}.${t} fail:`,s),s}}))}};var Xu=new class{constructor(){this._name="MarkAVChatRoomMember"}init(e){this._core=e;const{helper:t}=e;t.registerApi({apiName:"markGroupMemberList",context:this})}markGroupMemberList(e){return h(this,void 0,void 0,(function*(){const t="markGroupMemberList",{groupID:s,markType:o,enableMark:n,userIDList:i=[]}=e,r=this._generateRequestData(e);try{const e=yield function(e,t){return h(this,void 0,void 0,(function*(){const{groupID:s,operationType:o,memberList:n}=e,i={GroupId:s,CommandType:o,MemberList:n};return t.common.buildAndSendPacket({servcmd:"group_open_avchatroom_http_svc.modify_user_info",data:i})}))}(r,this._core),{MemberList:a=[]}=e||{},{successUserIDList:c,failureUserIDList:u}=this._handleResult(a,i);return console.log(`${this._name}.${t} ok, groupID:${s} markType:${o} enableMark:${n} success:${c.length} fail:${u.length}`),{code:0,data:{successUserIDList:c,failureUserIDList:u}}}catch(e){const s=new this._core.helper.ChatError({functionName:t,code:null==e?void 0:e.errorCode,message:null==e?void 0:e.errorInfo});throw console.error(`${this._name}.${t} fail:`,s),s}}))}_generateRequestData(e){const{groupID:t,markType:s,enableMark:o,userIDList:n=[]}=e,i=!0===o?1:2,r=[...n];r.length>500&&console.warn(`${this._name}._generateRequestData, the length of userIDList cannot exceed 500`);return{groupID:t,operationType:i,memberList:r.map((e=>({Member_Account:e,Marks:[s]})))}}_handleResult(e,t){const s=[],o=[];return e.length===t.length?(s.push(...t),{successUserIDList:s,failureUserIDList:o}):(t.forEach((t=>{e.find((e=>e.Member_Account===t))?s.push(t):o.push(t)})),{successUserIDList:s,failureUserIDList:o})}};var Zu=new class{init(e,t){console.log("AVChatRoomAction.init"),Hu.init(e,t),Wu.init(e,t),Yu.init(e,t),zu.init(e,t),Ju.init(e,t),Qu.init(e,t),Xu.init(e)}};var el=new class{constructor(){this._name="LiveHandler"}init(e){this._core=e;const{helper:t}=e;t.registerExperimentalAPI("startMessageLongPolling",this),t.registerExperimentalAPI("stopMessageLongPolling",this),console.log("LiveHandler.init")}startMessageLongPolling(e){const{common:t,utils:{isEmpty:s},OuterConstant:o}=this._core,{groupID:n,longPollingKey:i,longPollingSequence:r=1}=e;if(s(i))return console.warn(`${this._name}.startMessageLongPolling longPollingKey is empty.`),Promise.resolve({});Ku.hasPollingInstance(n)&&this.stopMessageLongPolling({groupID:n});const a=Ku.getJoinedLiveList();!t.isUnlimitedAVChatRoom()&&a.length>0&&this.stopMessageLongPolling({groupID:a[0]});const c={groupID:n,type:o.GRP_LIVE};return console.log(`${this._name}.startMessageLongPolling groupID:${n} longPollingKey:${i} longPollingSequence:${r}`),Ku.startMessageLongPolling({group:c,longPollingKey:i,startSequence:r})}stopMessageLongPolling(e){const{groupID:t}=e;return Ku.reset(t),console.log(`${this._name}.stopMessageLongPolling ok, groupID:${t}`),Promise.resolve({groupID:t})}};var tl=new class{constructor(){this.name="AVChatRoom"}install(e,t){this._core=e,Mu.init(e),Ku.init(e,t),Zu.init(e,t),el.init(e);const{notificationCenter:s,InnerEvent:o}=e,{InnerEventSubType:n}=s;s.subscribeInnerEvent(o.MESSAGE_PUSH,n.GROUP_SYSTEM_NOTIFICATION,this._onAVChatRoomSystemNotification,this),s.subscribeInnerEvent(o.LOGOUT,this._reset,this),s.subscribeInnerEvent(o.DESTROY,this._dispose,this)}_onAVChatRoomSystemNotification(e){Ku.onAVChatRoomSystemNotification(e)}_reset(){Ku.reset()}_dispose(){this._reset();const{notificationCenter:e,InnerEvent:t}=this._core,{InnerEventSubType:s}=e;e.unSubscribeInnerEvent(t.MESSAGE_PUSH,s.GROUP_SYSTEM_NOTIFICATION,this._onAVChatRoomSystemNotification,this),e.unSubscribeInnerEvent(t.LOGOUT,this._reset,this),e.unSubscribeInnerEvent(t.DESTROY,this._dispose,this)}};const sl="friend",ol=100,nl=2700,il=2710,rl=2711,al=2716,cl=2742,ul=30539,ll="Tag_SNS_IM_",dl={GROUP:`${ll}Group`,REMARK:`${ll}Remark`,ADDSOURCE:`${ll}AddSource`,ADDWORDING:`${ll}Wording`,ADDTIME:`${ll}AddTime`},pl="Update_Type_Add",hl="Update_Type_Delete",gl="add",_l="remove",ml="rename",vl=e=>void 0===e;function fl(e,t){return h(this,void 0,void 0,(function*(){return function(e){return Sl(e,"ResultItem",(e=>({to:e.To_Account,resultCode:e.ResultCode,resultInfo:e.ResultInfo})))}(yield t.common.buildAndSendPacket({servcmd:"sns.friend_update",data:e}))}))}function Il(e,t){return h(this,void 0,void 0,(function*(){return function(e){return Sl(e,"InfoItem",(e=>({userID:e.To_Account,relation:e.Relation,resultCode:e.ResultCode,resultInfo:e.ResultInfo})))}(yield t.common.buildAndSendPacket({servcmd:"sns.friend_check",data:e}))}))}function Sl(e,t="ResultItem",s=e=>({userID:e.To_Account,resultCode:e.ResultCode,resultInfo:e.ResultInfo})){const{[t]:o=[],ActionStatus:n,ErrorCode:i,ErrorInfo:r,ErrorDisplay:a}=e;return{resultList:o.map(s),actionStatus:n,errorCode:i,errorInfo:r,errorDisplay:a}}const El={[dl.REMARK]:(e,t)=>{e.remark=t},[dl.GROUP]:(e,t)=>{e.groupList=t?JSON.parse(JSON.stringify(t)):[]},[dl.ADDSOURCE]:(e,t)=>{e.source=t},[dl.ADDWORDING]:(e,t)=>{e.wording=t},[dl.ADDTIME]:(e,t)=>{e.addTime=t}};let Cl=class{constructor(e){var t;this.userID="",this.source="",this.wording="",this.remark="",this.addTime=0,this.groupList=[],this.friendCustomField=[];const{userID:s,tagValueList:o=[],core:n}=e,i=null===(t=n.user.userProfile)||void 0===t?void 0:t.createProfile(s,o);this.userID=s,this.profile=i,o.forEach((e=>{const{tag:t,value:s}=e;t.indexOf("Tag_Profile_Custom")>-1&&this.friendCustomField.push({key:t,value:s});const o=El[t];null==o||o(this,s)}))}update(e){const t=[];this.friendCustomField.forEach((e=>{t.push(e.key)})),e.forEach((e=>{const{tag:s,value:o}=e;s.indexOf("Tag_Profile_Custom")>-1&&(t.indexOf(s)>-1?this.friendCustomField.forEach((e=>{e.key===s&&(e.value=o)})):this.friendCustomField.push({key:s,value:o}));const n=El[s];null==n||n(this,o)}))}};var Ml=new class{constructor(){this._startIndex=0,this._standardSequence=0,this._customSequence=0}init(e){this._core=e;const{helper:t,constants:s}=e;t.registerApi({apiName:"getFriendList",context:this,methodName:"getFriendListFromCache"}),t.registerApi({apiName:"getFriendProfile",context:this}),t.registerApi({apiName:"addFriend",context:this}),t.registerApi({apiName:"deleteFriend",context:this}),t.registerApi({apiName:"updateFriend",context:this}),t.registerApi({apiName:"checkFriend",context:this}),t.registerWorkflowStep(s.WORKFLOW_NAME.SYNC_SERVER_INFO_AFTER_RE_ONLINE,s.WORKFLOW_STEP.FRIEND_RECOVER,this.syncFriendListFromServer,this)}getFriendListFromCache(){return h(this,void 0,void 0,(function*(){const{userStore:e}=this._core.appStore,t=[...e.getFriendMap().values()];return console.log(`${sl} getFriendListFromCache, data `,t),{code:0,data:t}}))}syncFriendListFromServer(){return h(this,void 0,void 0,(function*(){var e;try{console.log(`${sl} syncFriendListFromServer`);const t={From_Account:null===(e=this._core.store.get("login"))||void 0===e?void 0:e.userId,StartIndex:this._startIndex,StandardSequence:this._standardSequence,CustomSequence:this._customSequence},s=yield function(e,t){return h(this,void 0,void 0,(function*(){return function(e){const{UserDataItem:t=[],StandardSequence:s,CustomSequence:o,FriendNum:n,CompleteFlag:i,NextStartIndex:r,ActionStatus:a,ErrorCode:c,ErrorInfo:u,ErrorDisplay:l}=e;return{friendList:t.map((e=>{var t;return{userID:e.To_Account,tagValueList:null===(t=e.ValueItem)||void 0===t?void 0:t.map((e=>({tag:e.Tag,value:e.Value})))}})),standardSequence:s,customSequence:o,friendNumber:n,completeFlag:i,nextStartIndex:r,actionStatus:a,errorCode:c,errorInfo:u,errorDisplay:l}}(yield t.common.buildAndSendPacket({servcmd:"sns.friend_get",data:e}))}))}(t,this._core),{friendList:o,nextStartIndex:n,standardSequence:i,customSequence:r,completeFlag:a}=s;this._startIndex=n,this._standardSequence=i,this._customSequence=r,this._processFriendList(o),0===a?yield this.syncFriendListFromServer():(this._emitFriendListUpdated(),this._fetchFriendProfile()),console.log(`${sl} syncFriendListFromServer ok`)}catch(e){throw console.error(`${sl} syncFriendListFromServer error:`,e),e}}))}getFriendProfile(e){return h(this,void 0,void 0,(function*(){var t;try{console.log(`${sl} getFriendProfile params:`,e);let{userIDList:s}=e;s.length>ol&&(s=s.slice(0,ol));const{friendUserIdList:o,unFriendUserIdList:n}=this.partitionByIsFriend(s),i=this._createNonFriendErrorList(n);if(0===o.length)return{code:0,data:{friendList:[],failureUserIDList:i}};const r={From_Account:null===(t=this._core.store.get("login"))||void 0===t?void 0:t.userId,To_Account:o},a=(yield function(e,t){return h(this,void 0,void 0,(function*(){return function(e){const{InfoItem:t=[],ActionStatus:s,ErrorCode:o,ErrorInfo:n,ErrorDisplay:i}=e;return{friendProfileList:t.map((e=>{var t;return{userID:e.To_Account,resultCode:e.ResultCode,resultInfo:e.ResultInfo,relation:e.Relation,standardSequence:e.StandardSequence,customSequence:e.CustomSequence,profileItem:(null===(t=e.SnsProfileItem)||void 0===t?void 0:t.map((e=>({tag:e.Tag,value:e.Value}))))||[]}})),actionStatus:s,errorCode:o,errorInfo:n,errorDisplay:i}}(yield t.common.buildAndSendPacket({servcmd:"sns.friend_get_specified",data:e}))}))}(r,this._core))||{},{successProfiles:c,failedProfiles:u}=this._processFriendProfileResponse(a);return{code:0,data:{friendList:c,failureUserIDList:[...u,...i]}}}catch(e){throw console.error(`${sl} getFriendProfile error:`,e),e}}))}addFriend(e){return h(this,void 0,void 0,(function*(){var t;try{console.log(`${sl} addFriend options:`,e);const{helper:s,store:o}=this._core,{to:n,source:i,type:r,wording:a,remark:c,groupName:u}=e,l={From_Account:null===(t=o.get("login"))||void 0===t?void 0:t.userId,AddFriendItem:[{To_Account:n,AddSource:i,AddWording:a,GroupName:u,Remark:c}],AddType:r},d=yield function(e,t){return h(this,void 0,void 0,(function*(){return Sl(yield t.common.buildAndSendPacket({servcmd:"sns.friend_add",data:e}))}))}(l,this._core),{resultList:p=[]}=d,{userID:g,resultCode:_}=p[0];if(0===_)return console.log(`${sl} addFriend ok`),{code:0,data:{userID:g}};if(_===ul)return console.log(`${sl} addFriend wait for the other party to agree`),{code:0,data:{userID:g,code:_,message:"wait for the other party to agree"}};throw new s.ChatError({functionName:"addFriend",code:_})}catch(e){throw console.error(`${sl} addFriend error:`,e),e}}))}deleteFriend(e){return h(this,void 0,void 0,(function*(){var t;try{console.log(`${sl} deleteFriend options:`,e);const{store:s}=this._core;let{userIDList:o,type:n}=e;const i=null===(t=s.get("login"))||void 0===t?void 0:t.userId;o.length>1e3&&(console.warn(`${sl} deleteFriend the length of userIDList cannot exceed:`,1e3),o=o.slice(0,ol));const{friendUserIdList:r,unFriendUserIdList:a}=this.partitionByIsFriend(o);if(0===r.length)return{code:0,data:{friendList:[],failureUserIDList:this._createNonFriendErrorList(a)}};const c={From_Account:i,To_Account:r,DeleteType:n},u=yield function(e,t){return h(this,void 0,void 0,(function*(){return Sl(yield t.common.buildAndSendPacket({servcmd:"sns.friend_delete",data:e}))}))}(c,this._core),{successUserIDList:l,failureUserIDList:d}=this._processOperationResult({resultList:u.resultList,includeRelation:!1});return console.log(`${sl} deleteFriend ok`),{code:0,data:{successUserIDList:l,failureUserIDList:d}}}catch(e){throw console.error(`${sl} deleteFriend error:`,e),e}}))}updateFriend(e){return h(this,void 0,void 0,(function*(){var t;try{console.log(`${sl} updateFriend options:`,e);const{userID:s,remark:o,friendCustomField:n}=e,{helper:i,store:r,appStore:{userStore:a}}=this._core,c=null===(t=r.get("login"))||void 0===t?void 0:t.userId;if(!a.getFriendMap().has(s))throw new i.ChatError({functionName:"updateFriend",code:nl});const u={From_Account:c,UpdateItem:[{To_Account:s,SnsItem:this._buildSnsItemList(o,n)}]},l=yield fl(u,this._core),{resultList:d}=l,{to:p,resultCode:h,resultInfo:g}=d[0];if(vl(h)||0===h){return{code:0,data:this._updateLocalFriend({userID:p,remark:o,friendCustomField:n})}}throw new i.ChatError({functionName:"updateFriend",code:h,message:g})}catch(e){throw console.error(`${sl} updateFriend error:`,e),e}}))}checkFriend(e){return h(this,void 0,void 0,(function*(){var t;try{console.log(`${sl} checkFriend options:`,e);const{userIDList:s,type:o}=e,{OuterConstant:n,store:i}=this._core,r=null===(t=i.get("login"))||void 0===t?void 0:t.userId,a={From_Account:r,To_Account:s,CheckType:o===n.SNS_CHECK_TYPE_SINGLE?o:n.SNS_CHECK_TYPE_BOTH},c=yield Il(a,this._core),{successUserIDList:u=[],failureUserIDList:l=[]}=this._processOperationResult({resultList:c.resultList,includeRelation:!0});return{code:0,data:{successUserIDList:u,failureUserIDList:l}}}catch(e){throw console.error(`${sl} checkFriend error:`,e),e}}))}dispose(){this.reset();const{notificationCenter:e,InnerEvent:t}=this._core;e.unSubscribeInnerEvent(t.LOGOUT,this.reset,this)}reset(){const{userStore:e}=this._core.appStore;e.getFriendMap().clear(),this._startIndex=0,this._standardSequence=0,this._customSequence=0}updateFriendList(e){return h(this,void 0,void 0,(function*(){console.log(`${sl} updateFriendList data:`,e);const{userStore:t}=this._core.appStore,{addedFriendList:s=[],removedFriendList:o=[]}=e;s.length>0&&(s.forEach((e=>{const s=new Cl({userID:e,core:this._core});t.getFriendMap().set(e,s)})),yield this.getFriendProfile({userIDList:s}),this._emitFriendListUpdated()),o.length>0&&(o.forEach((e=>{t.getFriendMap().delete(e)})),this._emitFriendListUpdated())}))}updateFriendInfo(e){console.log(`${sl} updateFriendInfo data: `,e);const{appStore:{userStore:t,conversationStore:s},utils:{isEmpty:o}}=this._core,{userID:n,tagValueList:i}=e[0]||{},r=t.getFriend(n);if(o(i)||!r)return;const a=i.map((e=>({tag:e.BytesTag,value:e.BytesValue})));a.forEach((e=>{var t;const{tag:o,value:i}=e,c=null===(t=s.getConversation(`C2C${n}`))||void 0===t?void 0:t.remark;o===dl.REMARK&&i!==c&&s.updateConversation(`C2C${n}`,{remark:i}),r.update(a)})),this._emitFriendListUpdated()}_processFriendList(e){const{utils:{isEmpty:t},appStore:{userStore:s}}=this._core;t(e)||e.forEach((e=>{const{userID:t,tagValueList:o}=e;if(this._isInvalidFriend(t))return;const n=new Cl({userID:t,tagValueList:o,core:this._core});s.getFriendMap().set(t,n)}))}_isInvalidFriend(e){return"@TLS#NOT_FOUND"===e||""===e}_fetchFriendProfile(){return h(this,void 0,void 0,(function*(){try{console.log(`${sl} _fetchFriendProfile`);const{appStore:{userStore:e},user:{userProfile:t}}=this._core,s=[...e.getFriendMap().keys()],o=100,n=Math.ceil(s.length/o);for(let i=0;i<n;i++){const n=i*o,r=Math.min(n+o,s.length),a=s.slice(n,r),c=yield null==t?void 0:t.getUserProfile({userIDList:a});if(c&&c.data){c.data.forEach((t=>{const s=e.getFriend(t.userID);s&&(s.profile=t)}))}this._emitFriendListUpdated()}}catch(e){throw console.error(`${sl} _fetchFriendProfile error:`,e),e}}))}_emitFriendListUpdated(){const{notificationCenter:e,OuterEvent:t,appStore:{userStore:s}}=this._core,o=Array.from(s.getFriendMap().values());console.log(`${sl} _emitFriendListUpdated friendList:`,o),e.emitOuterEvent(t.FRIEND_LIST_UPDATED,{name:t.FRIEND_LIST_UPDATED,data:o})}_updateCustomField(e,t){if(!Array.isArray(e)||!Array.isArray(t))return!1;let s=!1;return t.forEach((({key:t,value:o})=>{const n=e.find((e=>e.key===t));n?n.value!==o&&(n.value=o,s=!0):(e.push({key:t,value:o}),s=!0)})),s}_updateLocalFriend(e){const{userStore:t}=this._core.appStore,{userID:s,remark:o,friendCustomField:n}=e,i=t.getFriend(s);if(i)return vl(o)||(i.remark=o),Array.isArray(n)&&n.length>0&&this._updateCustomField(i.friendCustomField,n),this._emitFriendListUpdated(),i}_processOperationResult(e){const{resultList:t,includeRelation:s=!1}=e,{isEmpty:o}=this._core.utils,n=[],i=[];return Array.isArray(t)&&!o(t)&&t.forEach((e=>{const{userID:t,relation:o,resultCode:r,resultInfo:a}=e;if(vl(r)||0===r){const e={userID:t};s&&(e.code=0,e.relation=o),n.push(e)}else i.push({userID:t,code:r,message:a})})),{successUserIDList:n,failureUserIDList:i}}_createNonFriendErrorList(e){return e.map((e=>({userID:e,code:nl,message:"The specified userID is not my friend"})))}_buildSnsItemList(e,t){const s=[];return vl(e)||s.push({Tag:dl.REMARK,Value:e}),Array.isArray(t)&&t.length>0&&t.forEach((e=>{s.push({tag:e.key,value:e.value})})),s}_processFriendProfileResponse(e){const{friendProfileList:t=[]}=e,{userStore:s}=this._core.appStore,o=[],n=[];return t.forEach((e=>{const{userID:t,resultCode:i,resultInfo:r,profileItem:a}=e;if(0===i){const e=new Cl({userID:t,tagValueList:a,core:this._core});o.push(e),s.getFriendMap().set(t,e)}else n.push({userID:t,code:i,message:r})})),console.log(`${sl} _processFriendProfileResponse successProfiles:`,o),{successProfiles:o,failedProfiles:n}}partitionByIsFriend(e){const t=[],s=[];return e.forEach((e=>{const{userStore:o}=this._core.appStore;o.getFriendMap().has(e)?t.push(e):s.push(e)})),console.log(`${sl} partitionByIsFriend, friendUserIdList: ${t}, unFriendUserIdList: ${s}`),{friendUserIdList:t,unFriendUserIdList:s}}isMyFriend(e){const{userStore:t}=this._core.appStore;return t.getFriendMap().has(e)}};var yl=new class{init(e){this.core=e}};function Tl(e){return h(this,void 0,void 0,(function*(){var t;const{store:s,common:o}=yl.core,n={From_Account:null===(t=s.get("login"))||void 0===t?void 0:t.userId,ResponseFriendItem:[{To_Account:e.userID,ResponseAction:e.type,Remark:e.remark}]};return Dl(yield o.buildAndSendPacket({servcmd:"sns.friend_response",data:n}))}))}function Al(e){return h(this,void 0,void 0,(function*(){var t;const{store:s,common:o}=yl.core,n={From_Account:null===(t=s.get("login"))||void 0===t?void 0:t.userId,ResponseFriendItem:[{To_Account:e.userID,ResponseAction:"Response_Action_Reject"}]};return Dl(yield o.buildAndSendPacket({servcmd:"sns.friend_response",data:n}))}))}function Ol(e){return h(this,void 0,void 0,(function*(){var t;const{store:s,common:o}=yl.core,n={From_Account:null===(t=s.get("login"))||void 0===t?void 0:t.userId,To_Account:[e.userID],PendencyType:e.type};return Dl(yield o.buildAndSendPacket({servcmd:"sns.pendency_delete",data:n}))}))}function Dl(e){const{ResultItem:t=[],ActionStatus:s,ErrorCode:o,ErrorInfo:n,ErrorDisplay:i}=e;return{resultList:t.map((e=>({userID:e.To_Account,resultCode:e.ResultCode,resultInfo:e.ResultInfo}))),actionStatus:s,errorCode:o,errorInfo:n,errorDisplay:i}}var Rl=new class{constructor(){this._friendApplicationMap=new Map,this._unreadCount=0,this._startTime=0,this._currentSequence=0}init(e){this._core=e;const{helper:t}=e;t.registerApi({apiName:"getFriendApplicationList",context:this,methodName:"getFriendApplicationListFromCache"}),t.registerApi({apiName:"acceptFriendApplication",context:this}),t.registerApi({apiName:"refuseFriendApplication",context:this}),t.registerApi({apiName:"deleteFriendApplication",context:this}),t.registerApi({apiName:"setFriendApplicationRead",context:this})}getFriendApplicationListFromCache(){return h(this,void 0,void 0,(function*(){const e=[...this._friendApplicationMap.values()];return console.log(`${sl} getFriendApplicationListFromCache friendApplicationList:`,e),{code:0,data:{friendApplicationList:e,unreadCount:this._unreadCount}}}))}syncFriendApplicationListFromServer(){return h(this,void 0,void 0,(function*(){const e="syncFriendApplicationListFromServer";console.log(`${sl} ${e}`);try{const e=yield function(e){return h(this,void 0,void 0,(function*(){var t;const{store:s,OuterConstant:o,common:n}=yl.core,i={From_Account:null===(t=s.get("login"))||void 0===t?void 0:t.userId,PendencyType:o.SNS_APPLICATION_TYPE_BOTH,MaxLimited:ol,StartTime:e.startTime,LastSequence:e.currentSequence};return function(e){const{PendencyItem:t=[],StartTime:s,UnreadPendencyCount:o,CurrentSequence:n,ActionStatus:i,ErrorCode:r,ErrorInfo:a,ErrorDisplay:c}=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:o,currentSequence:n,actionStatus:i,errorCode:r,errorInfo:a,errorDisplay:c}}(yield n.buildAndSendPacket({servcmd:"sns.pendency_get",data:i}))}))}({startTime:this._startTime,currentSequence:this._currentSequence}),{resultList:t,unreadCount:s,startTime:o,currentSequence:n}=e;this._startTime=o,this._currentSequence=n,this._unreadCount=s,this._friendApplicationMap.clear(),Array.isArray(t)&&t.forEach((e=>{const{userID:t,type:s}=e,o=this._createFriendApplication(e);this._friendApplicationMap.set(`${t}_${s}`,o)})),this._emitApplicationListUpdated()}catch(t){const s=new this._core.helper.ChatError({functionName:e,code:null==t?void 0:t.errorCode,message:null==t?void 0:t.errorInfo});throw console.error(`${sl} ${e} error:`,s),s}}))}acceptFriendApplication(e){return h(this,void 0,void 0,(function*(){return this._operationApplication({functionName:"acceptFriendApplication",options:e,protocolFunction:Tl})}))}refuseFriendApplication(e){return h(this,void 0,void 0,(function*(){return this._operationApplication({functionName:"refuseFriendApplication",options:e,protocolFunction:Al})}))}deleteFriendApplication(e){return h(this,void 0,void 0,(function*(){const{userID:t,type:s}=e;return this._checkApplicationExists(t,s,"deleteFriendApplication"),this._operationApplication({functionName:"deleteFriendApplication",options:e,protocolFunction:Ol})}))}_checkApplicationExists(e,t,s){if(!this._friendApplicationMap.has(`${e}_${t}`))throw new this._core.helper.ChatError({functionName:s,code:al})}_operationApplication(e){return h(this,void 0,void 0,(function*(){const{functionName:t,options:s,protocolFunction:o}=e;console.log(`${sl} ${t} options:`,s);try{const e=yield o(s),{resultList:n=[]}=e,{resultCode:i,resultInfo:r}=n[0];if(0===i)return console.log(`${sl} ${t} ok`),{code:0,data:{}};throw{errorCode:i,errorInfo:r}}catch(e){const s=new this._core.helper.ChatError({functionName:t,code:null==e?void 0:e.errorCode,message:null==e?void 0:e.errorInfo});throw console.error(`${sl} ${t} error:`,s),s}}))}setFriendApplicationRead(){return h(this,void 0,void 0,(function*(){const e="setFriendApplicationRead";console.log(`${sl} ${e}`);try{return yield function(){return h(this,void 0,void 0,(function*(){var e;const{store:t,common:s}=yl.core,o={From_Account:null===(e=t.get("login"))||void 0===e?void 0:e.userId,LatestPendencyTimeStamp:(n=Math.floor(Date.now()/1e3),i=0,Math.round(Number(n)*Math.pow(10,i))/Math.pow(10,i))};var n,i;return function(e){const{ActionStatus:t,ErrorCode:s,ErrorInfo:o,ErrorDisplay:n}=e;return{actionStatus:t,errorCode:s,errorInfo:o,errorDisplay:n}}(yield s.buildAndSendPacket({servcmd:"sns.pendency_report",data:o}))}))}(),this._unreadCount=0,this._emitApplicationListUpdated(),console.log(`${sl} ${e} ok`),{code:0,data:{}}}catch(t){const s=new this._core.helper.ChatError({functionName:e,code:null==t?void 0:t.errorCode,message:null==t?void 0:t.errorInfo});throw console.error(`${sl} ${e} error:`,s),s}}))}updateFriendApplicationList(e){const{from:t,addedApplicationList:s=[],removedApplicationList:o=[]}=e;console.log(`${sl} updateFriendApplicationList data:`,e);const{isEmpty:n}=this._core.utils;n(s)||this.onApplicationAdded(s,t),n(o)||this.onApplicationDeleted()}onApplicationAdded(e,t){var s;const{store:o,OuterConstant:n}=this._core,i=t===(null===(s=o.get("login"))||void 0===s?void 0:s.userId)?n.SNS_APPLICATION_SENT_BY_ME:n.SNS_APPLICATION_SENT_TO_ME;e.forEach((e=>{const t=`${e.userID}_${i}`;i!==n.SNS_APPLICATION_SENT_TO_ME||this._friendApplicationMap.has(t)||(this._unreadCount+=1),this._friendApplicationMap.set(t,this._createFriendApplication(Object.assign(Object.assign({},e),{type:i})))})),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(`${sl} _emitApplicationListUpdated`);const{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 Ll(){return h(this,void 0,void 0,(function*(){const{common:e}=yl.core,t={From_Account:e.getCurrentUserID(),LastSequence:0,NeedFriend:"Need_Friend_Type_Yes"};return function(e){return kl(e,(e=>({name:e.GroupName,userIDList:e.To_Account||[],count:e.FriendNumber})))}(yield e.buildAndSendPacket({servcmd:"sns.group_get",data:t}))}))}function Nl(e){return h(this,void 0,void 0,(function*(){const{name:t,userIDList:s}=e,{common:o}=yl.core,n={From_Account:o.getCurrentUserID(),GroupName:[t],To_Account:s};return function(e){return kl(e,(e=>({userID:e.To_Account,resultCode:e.ResultCode,resultInfo:e.ResultInfo})))}(yield o.buildAndSendPacket({servcmd:"sns.group_add",data:n}))}))}function bl(e){return h(this,void 0,void 0,(function*(){const{common:t}=yl.core,s={From_Account:t.getCurrentUserID(),GroupName:[e.name]};return function(e){return kl(e)}(yield t.buildAndSendPacket({servcmd:"sns.group_delete",data:s}))}))}function Gl(e){return h(this,void 0,void 0,(function*(){const{common:t}=yl.core,{name:s,userIDList:o}=e,n=Ul(o,pl),i={From_Account:t.getCurrentUserID(),GroupOldName:s,UpdateGroupItem:n};return function(e){return kl(e,(e=>({userID:e.To_Account,updateType:e.UpdateType,resultCode:e.ResultCode,resultInfo:e.ResultInfo})))}(yield t.buildAndSendPacket({servcmd:"sns.group_update",data:i}))}))}function wl(e){return h(this,void 0,void 0,(function*(){const{common:t}=yl.core,{name:s,userIDList:o}=e,n=Ul(o,hl),i={From_Account:t.getCurrentUserID(),GroupOldName:s,UpdateGroupItem:n};return function(e){return kl(e,(e=>({userID:e.To_Account,updateType:e.UpdateType,resultCode:e.ResultCode,resultInfo:e.ResultInfo})))}(yield t.buildAndSendPacket({servcmd:"sns.group_update",data:i}))}))}function Pl(e){return h(this,void 0,void 0,(function*(){const{common:t}=yl.core,{oldName:s,newName:o}=e,n={From_Account:t.getCurrentUserID(),GroupOldName:s,GroupNewName:o};return function(e){return kl(e)}(yield t.buildAndSendPacket({servcmd:"sns.group_update",data:n}))}))}function Ul(e,t){return e.filter((e=>Ml.isMyFriend(e))).map((e=>({To_Account:e,UpdateType:t})))}function kl(e,t){const{CurrentSequence:s,ActionStatus:o,ErrorCode:n,ErrorInfo:i,ErrorDisplay:r,ResultItem:a=[]}=e,c={currentSequence:s,actionStatus:o,errorCode:n,errorInfo:i,errorDisplay:r};return t&&a.length>0?Object.assign(Object.assign({},c),{resultList:a.map(t)}):c}class Fl{constructor(e){const{name:t="",userIDList:s=[]}=e;this.name=t,this.userIDList=s,this.count=s.length}addToUserIDList(e){-1===this.userIDList.indexOf(e)&&(this.userIDList.push(e),this.count=this.userIDList.length)}removeFromUserIDList(e){const t=this.userIDList.indexOf(e);t>-1&&(this.userIDList.splice(t,1),this.count=this.userIDList.length)}}var $l=new class{constructor(){this._friendGroupMap=new Map}init(e){this._core=e;const{helper:t}=e;t.registerApi({apiName:"getFriendGroupList",context:this,methodName:"getFriendGroupListFromCache"}),t.registerApi({apiName:"createFriendGroup",context:this}),t.registerApi({apiName:"deleteFriendGroup",context:this}),t.registerApi({apiName:"addToFriendGroup",context:this}),t.registerApi({apiName:"removeFromFriendGroup",context:this}),t.registerApi({apiName:"renameFriendGroup",context:this})}getFriendGroupListFromCache(){return h(this,void 0,void 0,(function*(){const e=[...this._friendGroupMap.values()];return console.log(`${sl} getFriendGroupListFromCache, data: `,e),{code:0,data:e}}))}syncFriendGroupListFromServer(){return h(this,void 0,void 0,(function*(){const e="syncFriendGroupListFromServer";console.log(`${sl} ${e}`);try{const t=yield Ll(),{resultList:s=[]}=t;this._core.helper.isEmpty(s)&&console.log(`${sl} ${e} ok. count: 0`),s.forEach((e=>{const t=new Fl(e);this._friendGroupMap.set(e.name,t)})),this._emitGroupListUpdated()}catch(t){this._handleError(e,t)}}))}createFriendGroup(e){return h(this,void 0,void 0,(function*(){const t="createFriendGroup";console.log(`${sl} ${t} params:`,e);try{const{name:s}=e;this._checkGroupExist(t,s);const o=yield Nl(e),{successUserIDList:n,failureUserIDList:i}=this._parseCreateGroupResponse(o),r=new Fl({name:s,userIDList:n});return this._friendGroupMap.set(s,r),this._emitGroupListUpdated(),{code:0,data:{friendGroup:r,failureUserIDList:i}}}catch(e){this._handleError(t,e)}}))}deleteFriendGroup(e){return h(this,void 0,void 0,(function*(){const t="deleteFriendGroup";console.log(`${sl} ${t} params:`,e);try{const{name:s}=e;this._checkGroupNotExist(t,s),yield bl(e);const o=this._friendGroupMap.get(s);return o&&(this._updateFriendGroup({name:s,userIDList:o.userIDList,action:_l}),this._friendGroupMap.delete(s)),this._emitGroupListUpdated(),{code:0,data:o}}catch(e){this._handleError(t,e)}}))}addToFriendGroup(e){return h(this,void 0,void 0,(function*(){return this._updateFriendGroupMember({functionName:"addToFriendGroup",params:e,protocolFunction:Gl})}))}removeFromFriendGroup(e){return h(this,void 0,void 0,(function*(){return this._updateFriendGroupMember({functionName:"removeFromFriendGroup",params:e,protocolFunction:wl})}))}renameFriendGroup(e){return h(this,void 0,void 0,(function*(){const t="renameFriendGroup";console.log(`${sl} ${t} params:`,e);try{const{oldName:s,newName:o}=e;this._checkGroupNotExist(t,s),this._checkGroupExist(t,o),yield Pl(e);const n=this._updateGroupNameInCache(s,o);return n&&this._updateFriendGroup({name:s,userIDList:n.userIDList,action:ml,newName:o}),this._emitGroupListUpdated(),{code:0,data:n}}catch(e){this._handleError(t,e)}}))}_updateFriendGroupMember(e){return h(this,void 0,void 0,(function*(){const{functionName:t,params:s,protocolFunction:o}=e;console.log(`${sl} ${t} params:`,s);try{const{name:e}=s;this._checkGroupNotExist(t,e);const n=yield o(s),{friendGroup:i,failureUserIDList:r}=this._parseUpdateFriendGroupResponse(e,n);return this._emitGroupListUpdated(),{code:0,data:{friendGroup:i,failureUserIDList:r}}}catch(e){this._handleError(t,e)}}))}_updateGroupNameInCache(e,t){const s=this._friendGroupMap.get(e);return s&&(s.name=t,this._friendGroupMap.delete(e),this._friendGroupMap.set(t,s)),s}_parseCreateGroupResponse(e){const{resultList:t=[]}=e,s=[],o=[];return t.forEach((({userID:e,resultCode:t,resultInfo:n})=>{vl(t)||0===t?s.push(e):o.push({userID:e,code:t,message:n})})),{successUserIDList:s,failureUserIDList:o}}_parseUpdateFriendGroupResponse(e,t){const{resultList:s=[]}=t,o=this._friendGroupMap.get(e),n=[],i=[],r=[];return s.forEach((t=>{0===t.resultCode?o&&(t.updateType===pl?this._addFriendToGroup(e,t.userID,o,i):t.updateType===hl&&this._removeFriendFromGroup(e,t.userID,o,r)):n.push({userID:t.userID,code:t.resultCode,message:t.resultInfo})})),{friendGroup:o,failureUserIDList:n}}_addFriendToGroup(e,t,s,o){s.addToUserIDList(t),o.push(t),this._updateFriendGroup({name:e,userIDList:o,action:gl})}_removeFriendFromGroup(e,t,s,o){s.removeFromUserIDList(t),o.push(t),this._updateFriendGroup({name:e,userIDList:o,action:_l})}_emitGroupListUpdated(){const{notificationCenter:e,OuterEvent:t}=this._core,s=[...this._friendGroupMap.values()];console.log(`${sl} _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:rl})}_checkGroupExist(e,t){if(this._friendGroupMap.has(t))throw new this._core.helper.ChatError({functionName:e,code:il})}_updateFriendGroup(e){const{name:t,userIDList:s,action:o,newName:n}=e,{userStore:i}=this._core.appStore;console.log(`${sl} updateFriendGroup`,{name:t,userIDList:s,action:o,newName:n}),t&&!this._core.utils.isEmpty(s)&&s.forEach((e=>{const s=i.getFriend(e);if(!s)return;const{groupList:r}=s;switch(o){case gl:-1===r.indexOf(t)&&(r.push(t),s.count=r.length);break;case _l:{const e=r.indexOf(t);e>-1&&(r.splice(e,1),s.count=r.length);break}case ml:{if(!n)return;const e=r.indexOf(t);-1!==e&&(r[e]=n);break}}}))}_handleError(e,t){const s=new this._core.helper.ChatError({functionName:e,code:null==t?void 0:t.errorCode,message:null==t?void 0:t.errorInfo});throw console.error(`${sl} ${e} error:`,s),s}reset(){this._friendGroupMap.clear()}dispose(){this.reset()}};function ql(e){return e&&0!==e.length?e.map((e=>({userID:e.To_Account,addBlackTimeStamp:e.AddBlackTimeStamp}))):[]}var xl=new class{constructor(){this._blacklistMap=new Map,this._retryCount=0,this._startIndex=0}init(e){this._core=e;const{helper:t,constants:s}=e;t.registerApi({apiName:"getBlacklist",context:this,methodName:"getBlacklistFromCache"}),t.registerApi({apiName:"addToBlacklist",context:this}),t.registerApi({apiName:"removeFromBlacklist",context:this}),t.registerWorkflowStep(s.WORKFLOW_NAME.SYNC_SERVER_INFO_AFTER_RE_ONLINE,s.WORKFLOW_STEP.BLACKLIST_RECOVER,this.syncBlacklistFromServer,this)}getBlacklistFromCache(){return h(this,void 0,void 0,(function*(){return console.log(`${sl} getBlacklistFromCache`),{code:0,data:Array.from(this._blacklistMap.keys())}}))}syncBlacklistFromServer(){return h(this,void 0,void 0,(function*(){try{console.log(`${sl} syncBlacklistFromServer`);const e={From_Account:this._core.common.getCurrentUserID(),MaxLimited:ol,StartIndex:this._startIndex},t=yield function(e,t){return h(this,void 0,void 0,(function*(){const{helper:s,channel:o}=t,n="sns.black_list_get",i=s.generateProtocolData({servcmd:n,data:e}),r=`${i.head.seq}${n}`,a=yield o.sendPacket(i,{requestId:r}),{BlackListItem:c=[],StartIndex:u=0}=a;return{blackList:ql(c),startIndex:u}}))}(e,this._core),{blackList:s=[],startIndex:o=0}=t;return this._startIndex=o,this._addBlacklistMap(s),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(`${sl} syncBlacklistFromServer error:`,e),e}}))}addToBlacklist(e){return h(this,void 0,void 0,(function*(){try{console.log(`${sl} addToBlacklist options:`,e);const t=this._preprocessBlacklist(e),s={From_Account:this._core.common.getCurrentUserID(),To_Account:t},o=yield function(e,t){return h(this,void 0,void 0,(function*(){const{helper:s,channel:o}=t,n="sns.black_list_add",i=s.generateProtocolData({servcmd:n,data:e}),r=`${i.head.seq}${n}`,a=yield o.sendPacket(i,{requestId:r}),{ResultItem:c=[]}=a;return{blackList:ql(c)}}))}(s,this._core),{blackList:n=[]}=o;return this._addBlacklistMap(n),this._emitBlackListUpdated(),{code:0,data:Array.from(this._blacklistMap.keys())}}catch(e){throw console.error(`${sl} addToBlacklist error:`,e),e}}))}removeFromBlacklist(e){return h(this,void 0,void 0,(function*(){try{console.log(`${sl} removeFromBlacklist options:`,e);const t={From_Account:this._core.common.getCurrentUserID(),To_Account:e.userIDList},s=yield function(e,t){return h(this,void 0,void 0,(function*(){const{helper:s,channel:o}=t,n="sns.black_list_delete",i=s.generateProtocolData({servcmd:n,data:e}),r=`${i.head.seq}${n}`,a=yield o.sendPacket(i,{requestId:r}),{ResultItem:c=[]}=a;return{blackList:ql(c)}}))}(t,this._core),{blackList:o=[]}=s;return this._deleteBlacklistMap(o),this._emitBlackListUpdated(),{code:0,data:Array.from(this._blacklistMap.keys())}}catch(e){throw console.error(`${sl} removeFromBlacklist error:`,e),e}}))}dispose(){this.reset()}reset(){this._retryCount=0,this._startIndex=0,this._blacklistMap.clear()}updateBlacklist(e){console.log(`${sl} updateBlacklist data:`,e);const{addedBlacklist:t=[],removedBlacklist:s=[]}=e;let o=!1;if(t.length>0){t.some((e=>!this._blacklistMap.has(e)))&&(o=!0,this._addBlacklistMap(t.map((e=>({userID:e})))))}if(s.length>0){s.some((e=>this._blacklistMap.has(e)))&&(o=!0,this._deleteBlacklistMap(s.map((e=>({userID:e})))))}o&&this._emitBlackListUpdated()}_addBlacklistMap(e){console.log(`${sl} _addBlacklistMap blackList:`,e),e.forEach((e=>{const{userID:t,addBlackTimeStamp:s=Date.now()}=e;t&&!this._blacklistMap.has(t)&&this._blacklistMap.set(t,{userID:t,addBlackTimeStamp:s})}))}_deleteBlacklistMap(e){console.log(`${sl} _deleteBlacklistMap blackList:`,e),e.forEach((e=>{const{userID:t}=e;t&&this._blacklistMap.has(t)&&this._blacklistMap.delete(t)}))}_preprocessBlacklist(e){let{userIDList:t}=e;const s=this._core.common.getCurrentUserID();if(1===t.length&&t[0]===s)throw new this._core.helper.ChatError({functionName:"addToBlacklist",code:cl});return t.includes(s)&&(t=e.userIDList.filter((e=>e!==s))),t}_emitBlackListUpdated(){const{notificationCenter:e,OuterEvent:t}=this._core,s=Array.from(this._blacklistMap.keys());console.log(`${sl} _emitBlackListUpdated blackList:`,s),e.emitOuterEvent(t.BLACKLIST_UPDATED,{name:t.BLACKLIST_UPDATED,data:s})}};const Vl={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=>{const{OuterConstant:t}=yl.core;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=>{const{OuterConstant:t}=yl.core;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=>{const{OuterConstant:t}=yl.core;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=>{const{OuterConstant:t}=yl.core;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}}},Bl={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 jl=new class{constructor(){this.name="Friend"}install(e){console.log(`${sl} install`),this._core=e;const{helper:t,notificationCenter:s,InnerEvent:o,constants:{WORKFLOW_NAME:n,WORKFLOW_STEP:i}}=e;yl.init(e),Ml.init(e),Rl.init(e),$l.init(e),xl.init(e),t.registerValidateConfig({auth:Bl,params:Vl}),t.registerWorkflowStep(n.SYNC_SERVER_INFO_AFTER_LOGIN,i.FRIEND_AND_BLACKLIST_SYNC,this.handleLoginSuccess,this),s.subscribeInnerEvent(o.LOGOUT,this.reset,this),s.subscribeInnerEvent(o.MESSAGE_PUSH,s.InnerEventSubType.FRIEND_LIST_MODIFIED,this.onFriendModified,this)}handleLoginSuccess(){console.log(`${sl} handleLoginSuccess`),xl.syncBlacklistFromServer(),Ml.syncFriendListFromServer(),Rl.syncFriendApplicationListFromServer(),$l.syncFriendGroupListFromServer()}onFriendModified(e){const{from:t,addedBlacklist:s,removedBlacklist:o,addedFriendList:n,removedFriendList:i,addedApplicationList:r,removedApplicationList:a,friendUpdateInfo:c,reportTime:u}=this._parseFriendListModification(null==e?void 0:e.FriendListMod[0]),{isEmpty:l}=this._core.utils;l(s)&&l(o)||xl.updateBlacklist({addedBlacklist:s,removedBlacklist:o}),l(n)&&l(i)||(Ml.updateFriendList({addedFriendList:n,removedFriendList:i}),Rl.updateFriendApplicationList({from:t,removedApplicationList:n})),l(c)||Ml.updateFriendInfo(c),l(r)&&l(a)||Rl.updateFriendApplicationList({from:t,addedApplicationList:r,removedApplicationList:a}),u&&Rl.onApplicationRead()}_parseFriendListModification(e){const{PushType:t,From_Account:s,To_Account:o,ReportTime:n,BlackListAdd_Account:i=[],BlackListDel_Account:r=[],FriendAdd_Account:a=[],FriendDel_Account:c=[],PendencyAdd:u=[],FrienPencydDel_Account:l=[],FriendUpInfo:d=[]}=e,p=d.map((e=>({userID:e.Friend_Account,tagValueList:[...e.SNS]})));return{pushType:t,from:s,to:o,reportTime:n,addedBlacklist:i,removedBlacklist:r,addedFriendList:a,removedFriendList:c,addedApplicationList:u.map((e=>({userID:e.PendencyAdd_Account,source:e.AddSource,time:e.AddTime,wording:e.AddWording,nick:e.ProfileImNick}))),friendUpdateInfo:p,removedApplicationList:l}}reset(){console.log(`${sl} reset`),xl.reset(),Ml.reset(),Rl.reset(),$l.reset()}dispose(){console.log(`${sl} dispose`);const{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),xl.dispose(),Ml.dispose(),Rl.dispose(),$l.dispose()}};const Kl=new class{init(e){this.core=e}},Hl="Follow",Wl="FOLLOW",Yl=3122,zl={NONE:0,FOLLOWERS:1,FOLLOWING:2,MUTUAL:3};function Jl(e,t){return h(this,void 0,void 0,(function*(){var s;const{common:o,store:n}=Kl.core,i={FollowType:e,From_Account:null===(s=n.get("login"))||void 0===s?void 0:s.userId,StartCursor:t,WantNum:sd()};return function(e){const{FollowItem:t=[],NextCursor:s,ActionStatus:o,ErrorCode:n,ErrorInfo:i,ErrorDisplay:r}=e;return{resultList:t.map((e=>({userID:e.To_Account,followTime:e.FollowTime,profileItem:e.ProfileItem,profileSequence:e.ProfileSequence}))),nextPageToken:s,actionStatus:o,errorCode:n,errorInfo:i,errorDisplay:r}}(yield o.buildAndSendPacket({servcmd:"follow.follow_get",data:i}))}))}function Ql(e){return h(this,void 0,void 0,(function*(){return Jl(zl.FOLLOWERS,e)}))}function Xl(e){return h(this,void 0,void 0,(function*(){return Jl(zl.MUTUAL,e)}))}function Zl(e){return h(this,void 0,void 0,(function*(){return Jl(zl.FOLLOWING,e)}))}function ed(e){return h(this,void 0,void 0,(function*(){var t;const{common:s,store:o}=Kl.core,n={From_Account:null===(t=o.get("login"))||void 0===t?void 0:t.userId,FollowItem:e.map((e=>({To_Account:e})))};return function(e){const{ResultItem:t=[],ActionStatus:s,ErrorCode:o,ErrorInfo:n,ErrorDisplay:i}=e;return{resultList:t.map((e=>({userID:e.To_Account,resultCode:e.ResultCode,resultInfo:e.ResultInfo}))),actionStatus:s,errorCode:o,errorInfo:n,errorDisplay:i}}(yield s.buildAndSendPacket({servcmd:"follow.follow_add",data:n}))}))}function td(e){return h(this,void 0,void 0,(function*(){var t;const{common:s,store:o}=Kl.core,n={From_Account:null===(t=o.get("login"))||void 0===t?void 0:t.userId,To_Account:e};return function(e){const{ResultItem:t=[],ActionStatus:s,ErrorCode:o,ErrorInfo:n,ErrorDisplay:i}=e;return{resultList:t.map((e=>({userID:e.To_Account,resultCode:e.ResultCode,resultInfo:e.ResultInfo}))),actionStatus:s,errorCode:o,errorInfo:n,errorDisplay:i}}(yield s.buildAndSendPacket({servcmd:"follow.follow_delete",data:n}))}))}function sd(){const e=Kl.core.store.get("cloudConfig")||{},t=null==e?void 0:e.follow_req_count;if(void 0!==t){const e=Number(t);return e>1e3?1e3:e}return 500}const od={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}]},nd={getMyFollowersList:!0,getMyFollowingsList:!0,getMutualFollowersList:!0,followUser:!0,unfollowUser:!0,checkFollow:!0,getUserFollowInfo:!0};var id=new class{constructor(){this.name="Follow"}install(e){this._core=e;const{helper:t,notificationCenter:s,InnerEvent:o}=e;Kl.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:nd,params:od}),s.subscribeInnerEvent(o.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:Zl,nextCursor:e})}))}getMyFollowersList(){return h(this,arguments,void 0,(function*(e=""){return this._getFollowList({functionName:"getMyFollowersList",protocolFunction:Ql,nextCursor:e})}))}getMutualFollowersList(){return h(this,arguments,void 0,(function*(e=""){return this._getFollowList({functionName:"getMutualFollowersList",protocolFunction:Xl,nextCursor:e})}))}_getFollowList(e){return h(this,void 0,void 0,(function*(){const{functionName:t,protocolFunction:s,nextCursor:o=""}=e;console.log(`${Hl} ${t} nextCursor:`,o);try{this._checkBusinessCapabilityBits(t);const e=yield s(o),{resultList:n=[],nextPageToken:i=""}=e,r=this._parseFollowItems(n);return console.log(`${Hl}.${t} nextCursor: ${o} from remote.`),{code:0,data:{resultList:r,nextCursor:i}}}catch(e){console.error(`${Hl}.${t} fail:`,e),this._handleError(t,e)}}))}followUser(e){return h(this,void 0,void 0,(function*(){return this._handleUserFollowRelation({functionName:"followUser",userIDList:e,protocolFunction:ed})}))}unfollowUser(e){return h(this,void 0,void 0,(function*(){return this._handleUserFollowRelation({functionName:"unfollowUser",userIDList:e,protocolFunction:td})}))}_handleUserFollowRelation(e){return h(this,void 0,void 0,(function*(){const{functionName:t,userIDList:s,protocolFunction:o}=e;try{const e=this._sliceUserIDList(s,20);this._checkBusinessCapabilityBits(t);const{resultList:n=[]}=yield o(e);return{code:0,data:n}}catch(e){this._handleError(t,e)}}))}getUserFollowInfo(e){return h(this,void 0,void 0,(function*(){const t="getUserFollowInfo";console.log(`${Hl} ${t} userIDList:`,e);try{this._checkBusinessCapabilityBits(t);const s=e||[this._core.common.getCurrentUserID()];console.log(`${Hl} ${t} userIDList: ${s}`);const o=yield function(e){return h(this,void 0,void 0,(function*(){var t;const{common:s,store:o}=Kl.core,n={From_Account:null===(t=o.get("login"))||void 0===t?void 0:t.userId,To_Account:e};return function(e){const{FollowInfo:t=[],ActionStatus:s,ErrorCode:o,ErrorInfo:n,ErrorDisplay:i}=e;return{followInfoList:t.map((e=>({userID:e.To_Account,resultCode:e.ResultCode,resultInfo:e.ResultInfo,followerCount:e.FollowerCount,followingCount:e.FollowingCount,mutualFollowingCount:e.MutualFollowingCount}))),actionStatus:s,errorCode:o,errorInfo:n,errorDisplay:i}}(yield s.buildAndSendPacket({servcmd:"follow.follow_get_info",data:n}))}))}(e),{followInfoList:n=[]}=o,i=[];return n.forEach((e=>{const{followerCount:t,followingCount:s,mutualFollowingCount:o}=e;i.push({followerCount:t,followingCount:s,mutualFollowingCount:o})})),{code:0,data:i}}catch(e){this._handleError(t,e)}}))}checkFollowType(e){return h(this,void 0,void 0,(function*(){const t="checkFollowType";console.log(`${Hl} ${t} userIDList:`,e);try{this._checkBusinessCapabilityBits(t),e.length>100&&(e=e.slice(0,100),console.warn(`${Hl} ${t} the length of userIDList cannot exceed 100`));const s=yield function(e){return h(this,void 0,void 0,(function*(){var t;const{common:s,store:o}=Kl.core,n={From_Account:null===(t=o.get("login"))||void 0===t?void 0:t.userId,To_Account:e};return function(e){const{ResultItem:t=[],ActionStatus:s,ErrorCode:o,ErrorInfo:n,ErrorDisplay:i}=e;return{resultList:t.map((e=>({userID:e.To_Account,followType:e.FollowType,resultCode:e.ResultCode,resultInfo:e.ResultInfo}))),actionStatus:s,errorCode:o,errorInfo:n,errorDisplay:i}}(yield s.buildAndSendPacket({servcmd:"follow.follow_check",data:n}))}))}(e),{resultList:o=[]}=s;return{code:0,data:o.map((({userID:e,followType:t})=>({userID:e,followType:t})))}}catch(e){this._handleError(t,e)}}))}onFollowListUpdated(e){console.log(`${Hl} onFollowListUpdated`,e);const{FollowChangeList:t=[]}=e;t.forEach((e=>this._processFollowChangeItem(e)))}_processFollowChangeItem(e){const{From_Account:t,FollowDiffList:s=[]}=e,o=p(e,["From_Account","FollowDiffList"]),n={userID:t,avatar:o.FaceUrl,nick:o.NickName};s.forEach((e=>{const t=this._updateFollowRelation(e,n);this._notifyFollowChanges(t)}))}_updateFollowRelation(e,t){const{IsAdd:s,FollowType:o=0}=e,n=this._initFollowInfo(),i=n[o];return i.isAdd=1===s,i.userInfoList.push(i.isAdd?t:t.userID),n}_notifyFollowChanges(e){const{OuterEvent:t}=this._core,s={[zl.FOLLOWERS]:t.MY_FOLLOWERS_LIST_UPDATED,[zl.FOLLOWING]:t.MY_FOLLOWING_LIST_UPDATED,[zl.MUTUAL]:t.MUTUAL_FOLLOWERS_LIST_UPDATED};Object.entries(e).forEach((([e,t])=>{const o=Number(e);t.userInfoList.length>0&&s[o]&&this._emitFollowUpdated(s[o],t)}))}_initFollowInfo(){const e={};return Object.values(zl).forEach((t=>{t!==zl.NONE&&(e[t]={userInfoList:[],isAdd:!1})})),e}_emitFollowUpdated(e,t){console.log(`${Hl} _emitFollowUpdated`);const{notificationCenter:s}=this._core;s.emitOuterEvent(e,{name:e,data:t})}_sliceUserIDList(e,t){return e.slice(0,t)}_checkBusinessCapabilityBits(e){const{helper:t,store:s}=this._core;if(!(s.get("commercialConfig")||new Map).get(Wl))throw new t.ChatError({functionName:e,code:Yl,replacement1:e})}_handleError(e,t){const s=new this._core.helper.ChatError({functionName:e,code:null==t?void 0:t.errorCode,message:null==t?void 0:t.errorInfo});throw console.error(`${Hl} ${e} fail:`,s),s}_parseFollowItems(e){return e.map((e=>{var t;const{userID:s,followTime:o,profileItem:n=[]}=e,i=[];n.forEach((e=>{i.push({tag:e.Tag,value:e.Value})}));const r=null===(t=this._core.user.userProfile)||void 0===t?void 0:t.createProfile(s,i);return{userID:s,followTime:o,nick:null==r?void 0:r.nick,avatar:null==r?void 0:r.avatar,allowType:null==r?void 0:r.allowType,adminForbidType:null==r?void 0:r.adminForbidType}}))}};const rd=new class{init(e){this.core=e}};const ad="message",cd="user",ud={OR:"or",AND:"and"},ld=20,dd=20,pd=20,hd={required:!1,rules:["array"],allowEmpty:!0,customValidator:e=>!e||(!!(Array.isArray(e)&&e.length<=5)||"keywordList should be an array and length <= 5")},gd={required:!1,rules:["string"],allowEmpty:!0,customValidator:e=>!e||(!![ud.OR,ud.AND].includes(e)||"keywordListMatchType should be OR or AND")},_d={required:!1,rules:["number"],allowEmpty:!0,customValidator:e=>"number"==typeof e&&e>=1&&e<=100||"count must be a number between 1 and 100"},md={required:!1,rules:["string"],allowEmpty:!0},vd={required:!1,rules:["array"],allowEmpty:!0,customValidator:e=>{const{OuterConstant:t}=rd.core;if(!Array.isArray(e))return"groupTypeList should be an array";const s=[t.GRP_PUBLIC,t.GRP_COMMUNITY,t.GRP_WORK,t.GRP_MEETING];let o=!1;for(let t=0;t<e.length;t++)if(-1===s.indexOf(e[t])){o=!0;break}return!o||"groupTypeList should be supported group type"}},fd={required:!1,rules:["array"],allowEmpty:!0,customValidator:e=>{const{OuterConstant:t}=rd.core,s=[t.MSG_TEXT,t.MSG_IMAGE,t.MSG_AUDIO,t.MSG_FILE,t.MSG_VIDEO,t.MSG_LOCATION,t.MSG_CUSTOM,t.MSG_MERGER];let o=!1;for(let t=0;t<e.length;t++)if(-1===s.indexOf(e[t])){o=!0;break}return!o||"messageTypeList should be supported message type"}},Id={required:!1,rules:["string"],allowEmpty:!0,customValidator:e=>{const{OuterConstant:t}=rd.core;return!(!(null==e?void 0:e.startsWith(t.CONV_C2C))&&!(null==e?void 0:e.startsWith(t.CONV_GROUP))&&e!==t.CONV_SYSTEM)||"conversationID is invalid"}},Sd=e=>({required:!1,rules:["number"],allowEmpty:!0,customValidator:t=>"number"==typeof t&&t>=0||`${e} should be a number >= 0';`}),Ed={required:!1,rules:["string"],allowEmpty:!0,customValidator:e=>{const{OuterConstant:t}=rd.core;return!![t.GENDER_FEMALE,t.GENDER_MALE].includes(e)||"gender is invalid"}},Cd={searchCloudMessages:{keywordList:hd,keywordListMatchType:gd,cursor:md,senderUserIDList:{required:!1,rules:["array"],allowEmpty:!0,customValidator:e=>!!(Array.isArray(e)&&e.length<=5)||"senderUserIDList should be an array and length <= 5"},messageTypeList:fd,conversationID:Id,timePosition:Sd("timePosition"),timePeriod:Sd("timePeriod")},searchCloudUsers:{keywordList:hd,keywordListMatchType:gd,cursor:md,count:_d,miniBirthday:Sd("miniBirthday"),maxBirthday:Sd("maxBirthday"),gender:Ed},searchCloudGroupMembers:{keywordList:hd,keywordListMatchType:gd,cursor:md,count:_d,groupTypeList:vd,groupIDList:{required:!1,rules:["array"],allowEmpty:!0}},searchCloudGroups:{keywordList:hd,keywordListMatchType:gd,cursor:md,count:_d,groupTypeList:vd}},Md={searchCloudMessages:!0,searchCloudUsers:!0,searchCloudGroupMembers:!0,searchCloudGroups:!0};var yd=new class{constructor(){this.name="CloudSearch"}install(e){this._core=e,rd.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:Md,params:Cd})}searchCloudMessages(e){return h(this,void 0,void 0,(function*(){try{const{OuterConstant:t,helper:s,ssoLog:o}=this._core,n=o.createSSOLogData({method:"searchCloudMessages"}),{conversationID:i,timePeriod:r,timePosition:a}=e,c=p(e,["conversationID","timePeriod","timePosition"]),u=Object.assign({count:100},c);i&&(i.startsWith(t.CONV_C2C)?u.account=i.replace(t.CONV_C2C,""):i.startsWith(t.CONV_GROUP)&&(u.groupID=i.replace(t.CONV_GROUP,""))),this._setTimeRangeParams(u,{timePeriod:r,timePosition:a});const l=yield function(e){return h(this,void 0,void 0,(function*(){const{count:t,keywordList:s,keywordListMatchType:o,senderUserIDList:n,messageTypeList:i,endTime:r,startTime:a,cursor:c,account:u,groupID:l}=e,d={Count:t,KeywordList:s,MatchType:o,SendUserIDList:n,MsgTypeList:i,EndTime:r,StartTime:a,Cursor:c,PeerAccount:u,GroupID:l};return rd.core.common.buildAndSendPacket({servcmd:"message_search.query",data:d})}))}(u);if(!l)return{code:0,data:{}};const{ErrorCode:d,ErrorInfo:g,TotalCount:_,Cursor:m="",ConversationMsgs:v=[]}=l;if(0!==d)throw{errorCode:d,errorInfo:g};const f=`keywordList:${e.keywordList} keywordListMatchType:${e.keywordListMatchType} cursor:${e.cursor} res: totalCount:${_}`;n.setLogInfo({message:f}).end();const I=v.map((o=>{const{MsgList:n,Count:i,GroupID:r,UserID:a}=o,c=r?`${t.CONV_GROUP}${r}`:`${t.CONV_C2C}${a}`;if(this._isSearchingAllConversations(e)&&i>1)return{conversationID:c,messageCount:i,messageList:[]};const u=n.map((e=>s.isEmpty(r)?function(e,t){const s=t.OuterConstant.CONV_C2C,o=t.message.messageHelper.parseServerPushMessage(e),n=t.message.messageFactory.createMessage(Object.assign(Object.assign({},o),{conversationType:s,flow:"in"}));return n.setElement(o.elements),n}(e,this._core):function(e,t){const s=t.OuterConstant.CONV_GROUP,o=t.message.messageHelper.parseServerGroupMessage(e),n=t.message.messageFactory.createMessage(Object.assign(Object.assign({},o),{conversationType:s,flow:"in"}));return n.setElement(o.elements),n}(e,this._core)));return{conversationID:c,messageCount:i,messageList:u}}));return{code:0,data:{searchResultList:I,cursor:m,totalCount:_}}}catch(e){const{errorCode:t,errorInfo:s}=e||{};this._handleError({errorCode:t,errorInfo:s,searchType:ad,functionName:"searchCloudMessages"})}}))}searchCloudUsers(e){return h(this,void 0,void 0,(function*(){var t;try{const s=this._core.ssoLog.createSSOLogData({method:"searchCloudUsers"}),{keywordListMatchType:o,count:n=dd}=e,i=p(e,["keywordListMatchType","count"]),r=Object.assign({count:n,keywordListMatchType:o===ud.AND?1:0},i);this._setBirthdayRangeParams(r,e);const a=yield function(e){return h(this,void 0,void 0,(function*(){const{count:t,keywordList:s,keywordListMatchType:o,miniBirthday:n,maxBirthday:i,cursor:r,gender:a}=e,c={Count:t,Keywords:s,KeywordMatchType:o,Cursor:r,UserBirthStart:n,UserBirthEnd:i,Gender:a};return rd.core.common.buildAndSendPacket({servcmd:"user_search.query",data:c})}))}(r);if(!a)return{error:0,data:{}};const{ErrorCode:c,ErrorInfo:u,TotalCount:l,Cursor:d="",Users:g=[]}=a;if(0!==c)throw{errorCode:c,errorInfo:u};const _=`keywordList:${e.keywordList} keywordListMatchType:${e.keywordListMatchType} cursor:${e.cursor} count:${e.count} res: totalCount:${l}`;s.setLogInfo({message:_}).end();const m=[];for(let e=0,s=g.length;e<s;e++){const{UserID:s,ProfileItems:o}=g[e];if(s===this._core.OuterConstant.USER_NOT_FOUND||""===s)continue;const n=o.map((e=>({tag:e.Tag,value:e.StrValue}))),i=null===(t=this._core.user.userProfile)||void 0===t?void 0:t.createProfile(s,n);m.push(i)}return{code:0,data:{searchResultList:m,cursor:d,totalCount:l}}}catch(e){const{errorCode:t,errorInfo:s}=e||{};this._handleError({errorCode:t,errorInfo:s,searchType:cd,functionName:"searchCloudUsers"})}}))}searchCloudGroupMembers(e){return h(this,void 0,void 0,(function*(){try{const t=this._core.ssoLog.createSSOLogData({method:"searchCloudGroupMembers"}),{count:s=pd,keywordListMatchType:o}=e,n=p(e,["count","keywordListMatchType"]),i=Object.assign({count:s,keywordListMatchType:o===ud.AND?1:0},n),r=yield function(e){return h(this,void 0,void 0,(function*(){const{count:t,keywordList:s,keywordListMatchType:o,groupTypeList:n,cursor:i,groupIDList:r}=e,a={Count:t,Keywords:s,KeywordMatchType:o,Cursor:i,GroupType:n,GroupIdList:r};return rd.core.common.buildAndSendPacket({servcmd:"group_member_search.query",data:a})}))}(i);if(!r)return{code:0,data:{}};const{ErrorCode:a,ErrorInfo:c,GroupMembers:u=[],Cursor:l,TotalCount:d}=r;if(0!==a)throw{errorCode:a,errorInfo:c};const g=`keywordList:${e.keywordList} keywordListMatchType:${e.keywordListMatchType} cursor:${e.cursor} count:${e.count} res: totalCount:${d}`;t.setLogInfo({message:g}).end();const _=new Map;return u.forEach((e=>{const{GroupID:t,GroupName:s,GroupType:o,GroupFaceUrl:n,GroupMemberUserName:i,GroupMemberUserID:r,GroupMemberNameCard:a,GroupMemberAvatar:c=""}=e,u={groupID:t,name:s,type:o,avatar:n},l={userID:r,nick:i,nameCard:a,avatar:c};if(_.has(t)){const e=_.get(t);e.memberList.push(l),_.set(t,e)}else _.set(t,{groupInfo:u,memberList:[l]})})),{code:0,data:{searchResultList:[..._.values()],cursor:l,totalCount:d}}}catch(e){const{errorCode:t,errorInfo:s}=e||{};this._handleError({errorCode:t,errorInfo:s,searchType:cd,functionName:"searchCloudGroupMembers"})}}))}searchCloudGroups(e){return h(this,void 0,void 0,(function*(){try{const t=this._core.ssoLog.createSSOLogData({method:"searchCloudGroups"}),{count:s=ld,keywordListMatchType:o}=e,n=p(e,["count","keywordListMatchType"]),i=Object.assign({count:s,keywordListMatchType:o===ud.AND?1:0},n),r=yield function(e){return h(this,void 0,void 0,(function*(){const{count:t,keywordList:s,keywordListMatchType:o,groupTypeList:n,cursor:i}=e,r={Count:t,Keywords:s,KeywordMatchType:o,Cursor:i,GroupType:n};return rd.core.common.buildAndSendPacket({servcmd:"group_search.query",data:r})}))}(i);if(!r)return{code:0,data:{}};const{ErrorCode:a,ErrorInfo:c,Groups:u,Cursor:l,TotalCount:d}=r;if(0!==a)throw{errorCode:a,errorInfo:c};const g=`keywordList:${e.keywordList} keywordListMatchType:${e.keywordListMatchType} cursor:${e.cursor} count:${e.count} res: totalCount:${d}`;t.setLogInfo({message:g}).end();return{code:0,data:{searchResultList:(null==u?void 0:u.map((e=>function(e){const{GroupFaceUrl:t,GroupID:s,GroupIntroduction:o,GroupMemberNum:n,GroupName:i,GroupOwnerTinyID:r,GroupOwnerUserID:a,GroupOwnerUserName:c,GroupType:u,GroupAddOption:l,GroupInviteOption:d}=e;return{avatar:t,groupID:s,introduction:o,memberCount:n,name:i,ownerTinyID:r,ownerID:a,ownerNick:c,type:u,joinOption:l,inviteOption:d}}(e))))||[],cursor:l,totalCount:d}}}catch(e){const{errorCode:t,errorInfo:s}=e||{};this._handleError({errorCode:t,errorInfo:s,searchType:cd,functionName:"searchCloudGroups"})}}))}_setTimeRangeParams(e,{timePeriod:t,timePosition:s}){t&&t>0&&(e.startTime=s&&s>0?s-t:this._core.helper.timeManager.getServerTimeSeconds()-t),e.startTime&&e.startTime<0&&(e.startTime=void 0),s&&s>0&&(e.endTime=s)}_handleError({errorCode:e,errorMessage:t,searchType:s,functionName:o}){const{ssoLog:n,helper:i}=this._core;let r=e;60020===e?r="SearchUnable":s!==ad&&27003===e?r="SearchParamsError":s!==ad&&60018===e&&(r="SearchOverLimit");const a=new i.ChatError({code:r,message:t});throw n.getSSOLogData(o).setError(a).end(),a}_isSearchingAllConversations(e){return this._core.helper.isEmpty(e.conversationID)}_setBirthdayRangeParams(e,t){const{miniBirthday:s,maxBirthday:o}=t;void 0!==s&&(e.miniBirthday=s,void 0===o&&(e.maxBirthday=4294967295)),void 0!==o&&(e.maxBirthday=o)}};var Td=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)}};const Ad=new class{init(e){this.core=e}},Od="CONV_GROUP",Dd=2500,Rd=2503,Ld=1,Nd=2,bd="NOT_STARTED",Gd="FETCHING",wd="FINISHED",Pd="FAILED",Ud=0,kd=1,Fd=1,$d=2,qd=3,xd=1,Vd=2;function Bd(e){const{helper:t,constants:s}=Ad.core;if(!t.checkBusinessCapabilityBits(Od))throw new t.ChatError({functionName:e,code:s.ERROR_CODE.NO_USE,replacement1:e})}function Kd(){const{notificationCenter:e,OuterEvent:t}=Ad.core;e.emitOuterEvent(t.CONVERSATION_GROUP_LIST_UPDATED,{name:t.CONVERSATION_GROUP_LIST_UPDATED,data:[...Td.getConversationGroupMap().values()]})}function Hd(e){const{utils:{isUndefined:t},constants:{OuterConstant:s}}=Ad.core,{Type:o,To_Account:n,GroupId:i,ToGroupId:r=i,Peer_Account:a}=e;let c="";return o===Ld?t(a)?t(n)||(c=`${s.CONV_C2C}${n}`):c=`${s.CONV_C2C}${a}`:o===Nd&&(c=`${s.CONV_GROUP}${r}`),c}function Wd(e){const t=[],{OuterConstant:s,common:{isC2CConv:o,isGroupConv:n}}=Ad.core,{conversationIDList:i,failureConversationIDList:r,additionalData:a={}}=e;return i.forEach((e=>{Yd(e,r),o(e)?t.push(Object.assign({ContactItem:{Type:Ld,To_Account:e.replace(s.CONV_C2C,"")}},a)):n(e)&&t.push(Object.assign({ContactItem:{Type:Nd,ToGroupId:e.replace(s.CONV_GROUP,"")}},a))})),t}function Yd(e,t){const{appStore:{conversationStore:s},common:{isC2CConv:o,isGroupConv:n}}=Ad.core;s.getConversation(e)?o(e)||n(e)||t.push({conversationID:e,code:Rd}):t.push({conversationID:e,code:Dd})}function zd(e){const{utils:{isString:t}}=Ad.core,s=[];if(!t(e))return s;const o=e.length;if(0===o)return s;for(let t=o-1;t>=0;t--)"1"===e[t]&&s.push(Math.pow(2,o-t-1));return s}function Jd(e){null==e||e.forEach(((t,s)=>{const{appStore:o}=Ad.core,{conversationID:n,data:i}=t,r=s===e.length-1;o.conversationStore.updateConversation(n,i,{emit:r})}))}function Qd(e){const{conversationInfoList:t,fromAccount:s}=e,o={From_Account:s,MarkItem:t};return Ad.core.common.buildAndSendPacket({servcmd:"recentcontact.mark_contact",data:o})}function Xd(e){const{fromAccount:t,groupName:s,conversationInfoList:o}=e,n={From_Account:t,UpdateType:1,UpdateGroup:{UpdateGroupType:Vd,OldGroupName:s,ContactUpdateItem:o}};return Ad.core.common.buildAndSendPacket({servcmd:"recentcontact.update_contact_group",data:n})}var Zd=new class{init(e){const{helper:{registerApi:t}}=e;this._core=e,t({apiName:"createConversationGroup",context:this})}createConversationGroup(e){return h(this,void 0,void 0,(function*(){const{utils:{isPlainObject:t,isArray:s},appStore:o,ssoLog:n}=this._core;Bd("createConversationGroup");const i=n.createSSOLogData({method:"createConversationGroup"});i.setLogInfo({message:JSON.stringify(e)});const{groupName:r,conversationIDList:a}=e,c=[],u=this._generateConversationInfo(a,c);if(c.length===a.length)return{code:0,data:{successConversationIDList:[],failureConversationIDList:c}};try{const e=yield function(e){const{common:{buildAndSendPacket:t,getCurrentUserID:s}}=Ad.core,{item:o,groupName:n}=e;return t({servcmd:"recentcontact.create_contact_group",data:{From_Account:s(),GroupContactItem:[{GroupName:n,ContactItem:o}]}})}({groupName:r,item:u});if(e){i.end();const{GroupResultItem:n=[]}=e,{GroupItem:a,ResultItem:u}=(null==n?void 0:n[0])||{},l=[];if(t(a)){const{GroupName:e,GroupId:t}=a;Td.setConversationGroup(t,e),Kd()}if(s(u)){const e=[];u.forEach((t=>{const{ContactItem:s,ResultCode:n,ResultInfo:i}=t,a=Hd(s);if(0===n){const t=o.conversationStore.getConversation(a);if(t&&!t.conversationGroupList.includes(r)){const s=t.conversationGroupList.slice();s.push(r),e.push({conversationID:a,data:{conversationGroupList:s}})}}else c.push({conversationID:a,code:n,message:i})})),e.length>0&&(Jd(e),Kd())}return{code:0,data:{successConversationIDList:l,failureConversationIDList:c}}}}catch(e){const{errorCode:t,errorInfo:s}=e,o=new this._core.helper.ChatError({functionName:"createConversationGroup",code:t,message:s});throw i.setError(o).end(),o}}))}_generateConversationInfo(e,t,s={}){const o=[],{OuterConstant:n,common:{isC2CConv:i,isGroupConv:r}}=this._core;return e.forEach((e=>{Yd(e,t),i(e)?o.push(Object.assign({Type:Ld,To_Account:e.replace(n.CONV_C2C,"")},s)):r(e)&&o.push(Object.assign({Type:Nd,ToGroupId:e.replace(n.CONV_GROUP,"")},s))})),o}};var ep=new class{constructor(){this._fetchConversationGroupStatus=bd}init(e){const{helper:{registerApi:t,registerWorkflowStep:s},constants:{WORKFLOW_NAME:o,WORKFLOW_STEP:n}}=e;this._core=e,t({apiName:"getConversationGroupList",context:this}),s(o.SYNC_SERVER_INFO_AFTER_LOGIN,n.CONVERSATION_GROUP_LIST_SYNC,this._syncConversationGroupList,this),s(o.SYNC_SERVER_INFO_AFTER_LOGIN,n.CONVERSATION_GROUP_UPDATE,this._updateConversation,this)}getConversationGroupList(){return h(this,void 0,void 0,(function*(){return Bd("getConversationGroupList"),this._fetchConversationGroupStatus===Pd&&(yield this._fetchConversationGroupList(0)),{code:0,data:[...Td.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*(e,t=[]){const{common:{getCurrentUserID:s},utils:{isArray:o}}=this._core;this._fetchConversationGroupStatus=Gd;try{const n=s(),i=yield function(e){const{fromAccount:t,startIndex:s}=e,o={From_Account:t,StartIndex:s};return Ad.core.common.buildAndSendPacket({servcmd:"recentcontact.get_contact_group",data:o})}({fromAccount:n,startIndex:e});if(i){const{CompleteFlag:e,ContactItem:s=[],NextStartIndex:n=0,GroupItem:r=[]}=i;if(o(r)&&r.forEach((e=>{const{GroupName:t,GroupId:s}=e;Td.setConversationGroup(s,t)})),t.push(...s),e===Ud)return this._fetchConversationGroupList(n);if(e===kd)return this._fetchConversationGroupStatus=wd,t}}catch(e){this._fetchConversationGroupStatus=Pd,console.error(e)}}))}_updateConversation(e){var t;const{constants:{WORKFLOW_STEP:s}}=this._core,o=(null===(t=null==e?void 0:e.result)||void 0===t?void 0:t[s.CONVERSATION_GROUP_LIST_SYNC])||[];Jd(this._generateConversationUpdateFields(o)),Kd()}_generateConversationUpdateFields(e){const{utils:{isArray:t},appStore:s}=this._core,o=[];if(t(e)){let n;e.forEach((e=>{const i=[],{StandardMark:r,CustomMark:a="",ContactGroupId:c}=e;t(c)&&c.forEach((e=>{Td.getConversationGroupMap().has(e)&&i.push(Td.getConversationGroup(e))}));const u=Hd(e);n=s.conversationStore.getConversation(u),n&&o.push({conversationID:u,data:{markList:zd(r),customData:a,conversationGroupList:[...i]}})}))}return o}reset(){this._fetchConversationGroupStatus=bd}dispose(){this.reset()}};var tp=new class{init(e){const{notificationCenter:t,helper:{registerApi:s},InnerEvent:{MESSAGE_PUSH:o},InnerEventSubType:{CONVERSATION_MARK_UPDATED:n,CONVERSATION_GROUP_ADD:i,CONVERSATION_GROUP_DELETED:r,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(o,i,this._handleConversationGroupAdd,this),t.subscribeInnerEvent(o,r,this._handleConversationGroupDeleted,this),t.subscribeInnerEvent(o,a,this._handleConversationGroupUpdated,this),t.subscribeInnerEvent(o,n,this._handleConversationMarkUpdated,this)}renameConversationGroup(e){return h(this,void 0,void 0,(function*(){Bd("renameConversationGroup");const{common:{getCurrentUserID:t},ssoLog:s}=this._core,{oldName:o,newName:n}=e,i=s.createSSOLogData({method:"renameConversationGroup"});i.setLogInfo({message:`oldName:${o} newName:${n}`});try{const e=yield function(e){const{fromAccount:t,oldName:s,newName:o}=e,n={From_Account:t,UpdateType:1,UpdateGroup:{UpdateGroupType:xd,OldGroupName:s,NewGroupName:o}};return Ad.core.common.buildAndSendPacket({servcmd:"recentcontact.update_contact_group",data:n})}({fromAccount:t(),oldName:o,newName:n});if(e){i.end();const{UpdateGroupResult:t}=e,{GroupId:s}=t;Td.setConversationGroup(s,n),Kd(),this._updateLocalConversationGroupName({oldName:o,newName:n})}}catch(e){const{errorCode:t,errorInfo:s}=e,o=new this._core.helper.ChatError({functionName:"renameConversationGroup",code:t,message:s});throw i.setError(o).end(),o}}))}deleteConversationGroup(e){return h(this,void 0,void 0,(function*(){Bd("deleteConversationGroup");const{common:{getCurrentUserID:t},ssoLog:s}=this._core,o=s.createSSOLogData({method:"deleteConversationGroup"});o.setLogInfo({message:`groupName:${e}`});try{const s=yield function(e){const{fromAccount:t,groupName:s}=e,o={From_Account:t,GroupName:[s]};return Ad.core.common.buildAndSendPacket({servcmd:"recentcontact.del_contact_group",data:o})}({fromAccount:t(),groupName:e});if(s){const{GroupItem:t}=s;let o=!1;null==t||t.forEach((e=>{const{GroupId:t}=e,s=Td.getConversationGroupMap();s.has(t)&&(s.delete(t),o=!0)})),o&&Kd(),this._deleteLocalConversationGroupName([e])}}catch(e){const{errorCode:t,errorInfo:s}=e,n=new this._core.helper.ChatError({functionName:"deleteConversationGroup",code:t,message:s});throw o.setError(n).end(),n}}))}markConversation(e){return h(this,void 0,void 0,(function*(){Bd("markConversation");const{utils:{isNumber:t},common:{getCurrentUserID:s},ssoLog:o,appStore:n}=this._core,{conversationIDList:i,markType:r,enableMark:a}=e,c=this._getFlagBit(r),u=[],l=[];let d,p;const h=o.createSSOLogData({method:"markConversation"});h.setLogInfo({message:JSON.stringify(e)}),!0===a&&t(c)?d=[c]:p=[c];const g=Wd({conversationIDList:i,failureConversationIDList:u,additionalData:{SetMark:d,ClearMark:p,OptType:Fd}});if(u.length===i.length)return{code:0,data:{successConversationIDList:[],failureConversationIDList:u}};try{const e=yield Qd({conversationInfoList:g,fromAccount:s()});if(e){h.end();const{ResultItem:t}=e,s=[];t.forEach((e=>{const{ContactItem:t,ResultCode:o,ResultInfo:i}=e,c=Hd(t);if(0===o){l.push(c);const e=n.conversationStore.getConversation(c);if(e){const t=e.markList.indexOf(r),o=!1===a&&-1!==t;if(!0===a&&-1===t)s.push({conversationID:c,data:{markList:[...e.markList,r]}});else if(o){const o=e.markList.slice();o.splice(t,1),s.push({conversationID:c,data:{markList:o}})}}}else u.push({conversationID:c,code:o,message:i})})),Jd(s)}return{code:0,data:{successConversationIDList:l,failureConversationIDList:u}}}catch(e){const{errorCode:t,errorInfo:s}=e,o=new this._core.helper.ChatError({functionName:"markConversation",code:t,message:s});throw h.setError(o).end(),o}}))}setConversationCustomData(e){return h(this,void 0,void 0,(function*(){Bd("setConversationCustomData");const{common:{getCurrentUserID:t},ssoLog:s,appStore:o}=this._core,{conversationIDList:n,customData:i}=e,r=[],a=[],c=s.createSSOLogData({method:"setConversationCustomData"});c.setLogInfo({message:JSON.stringify(e)});const u=Wd({conversationIDList:n,failureConversationIDList:r,additionalData:{CustomMark:i,OptType:$d}});if(r.length===n.length)return{code:0,data:{successConversationIDList:[],failureConversationIDList:r}};try{const e=yield Qd({fromAccount:t(),conversationInfoList:u});if(e){c.end();const{ResultItem:t}=e,s=[];null==t||t.forEach((e=>{const{ContactItem:t,ResultCode:n,ResultInfo:c}=e;if(0===n){const e=Hd(t);a.push(e);const n=o.conversationStore.getConversation(e);n&&n.customData!==i&&s.push({conversationID:e,data:{customData:i}})}else r.push({conversationID:conversationID,code:n,message:c})})),Jd(s)}return{code:0,data:{successConversationIDList:a,failureConversationIDList:r}}}catch(e){const{errorCode:t,errorInfo:s}=e,o=new this._core.helper.ChatError({functionName:"setConversationCustomData",code:t,message:s});throw c.setError(o).end(),o}}))}deleteConversationsFromGroup(e){return h(this,void 0,void 0,(function*(){Bd("deleteConversationsFromGroup");const{common:{getCurrentUserID:t},ssoLog:s,appStore:o}=this._core,n=s.createSSOLogData({method:"deleteConversationsFromGroup"});n.setLogInfo({message:JSON.stringify(e)});const{conversationIDList:i,groupName:r}=e,a=[],c=[],u=Wd({conversationIDList:i,failureConversationIDList:a,additionalData:{ContactOptType:2}});if(a.length===i.length)return{code:0,data:{successConversationIDList:[],failureConversationIDList:a}};try{const e=yield Xd({fromAccount:t(),groupName:r,conversationInfoList:u});if(e){n.end();const t=[],{UpdateGroupResult:{ContactResultItem:s}}=e;null==s||s.forEach((e=>{const s=Hd(e.ContactItem);if(0===e.ResultCode){const e=o.conversationStore.getConversation(s);if(e){const o=e.conversationGroupList.indexOf(r);if(-1!==o){const n=e.conversationGroupList.slice();n.splice(o,1),c.push(s),t.push({conversationID:s,data:{conversationGroupList:n}})}}}else a.push({conversationID:s,code:e.ResultCode,message:e.ResultInfo})})),t.length>0&&(Kd(),Jd(t))}return{code:0,data:{successConversationIDList:c,failureConversationIDList:a}}}catch(e){const{errorCode:t,errorInfo:s}=e,o=new this._core.helper.ChatError({functionName:"deleteConversationsFromGroup",code:t,message:s});throw n.setError(o).end(),o}}))}addConversationsToGroup(e){return h(this,void 0,void 0,(function*(){Bd("deleteConversationsFromGroup");const{common:{getCurrentUserID:t},ssoLog:s,appStore:o}=this._core,n=s.createSSOLogData({method:"addConversationsToGroup"});n.setLogInfo({message:JSON.stringify(e)});const{conversationIDList:i,groupName:r}=e,a=[],c=[],u=Wd({conversationIDList:i,failureConversationIDList:a,additionalData:{ContactOptType:1}});if(a.length===i.length)return{code:0,data:{successConversationIDList:[],failureConversationIDList:a}};try{const e=yield Xd({fromAccount:t(),groupName:r,conversationInfoList:u});if(e){n.end();const t=[],{UpdateGroupResult:{ContactResultItem:s}}=e;null==s||s.forEach((e=>{const s=Hd(e.ContactItem);if(0===e.ResultCode){const e=o.conversationStore.getConversation(s);if(e){if(-1===e.conversationGroupList.indexOf(r)){const o=e.conversationGroupList.slice();o.push(r),c.push(s),t.push({conversationID:s,data:{conversationGroupList:o}})}}}else a.push({conversationID:s,code:e.ResultCode,message:e.ResultInfo})})),t.length>0&&(Kd(),Jd(t))}return{code:0,data:{successConversationIDList:c,failureConversationIDList:a}}}catch(e){const{errorCode:t,errorInfo:s}=e,o=new this._core.helper.ChatError({functionName:"deleteConversationsFromGroup",code:t,message:s});throw n.setError(o).end(),o}}))}_updateLocalConversationGroupName(e){const{appStore:t}=this._core,{oldName:s,newName:o}=e;let n=[];const i=[];let r=-1;Array.from(t.conversationStore.getConversationMap().values()).forEach((e=>{if(n=e.conversationGroupList,r=n.indexOf(s),-1!==r){const t=n.slice();t.splice(r,1,o),i.push({conversationID:e.conversationID,data:{conversationGroupList:t}})}})),Jd(i)}_deleteLocalConversationGroupName(e){const{utils:{isEmpty:t},appStore:s}=this._core;if(t(e))return;const o=[];Array.from(s.conversationStore.getConversationMap().values()).forEach((t=>{const{conversationID:s,conversationGroupList:n}=t,i=n.filter((t=>!e.includes(t)));i.length<n.length&&o.push({conversationID:s,data:{conversationGroupList:i}})})),Jd(o)}_getFlagBit(e){const t=e.toString(2),s=t.length;for(let e=s-1;e>=0;e--)if("1"===t[e])return s-e-1}_handleConversationGroupAdd(e){var t;const{utils:{isArray:s},appStore:o}=this._core;null===(t=null==e?void 0:e.RecentContactMod)||void 0===t||t.forEach((e=>{const{RecentContactCreateContactGroup:{MsgContactGroupContactItem:t}}=e;let n=!1;null==t||t.forEach((e=>{const{MsgGroupItem:t,MsgRecentContactItem:i}=e,{GroupId:r,GroupName:a}=t,c=[];Td.getConversationGroup(r)!==a&&(Td.setConversationGroup(r,a),n=!0),s(i)&&i.forEach((e=>{var t;const s=Hd(e),n=o.conversationStore.getConversation(s);if(n&&!(null===(t=n.conversationGroupList)||void 0===t?void 0:t.includes(a))){const e=n.conversationGroupList.slice();e.push(a),c.push({conversationID:s,data:{conversationGroupList:e}})}})),n&&Kd(),Jd(c)}))}))}_handleConversationGroupDeleted(e){var t;const{utils:{isArray:s}}=this._core;null===(t=null==e?void 0:e.RecentContactMod)||void 0===t||t.forEach((e=>{const{MsgGroupItem:t}=(null==e?void 0:e.RecentContactDelContactGroup)||{};if(s(t)){let e=!1;const s=[];t.forEach((t=>{const{GroupId:o,GroupName:n}=t,i=Td.getConversationGroupMap();i.has(o)&&(i.delete(o),e=!0,s.push(n))})),e&&Kd(),s.length>0&&this._deleteLocalConversationGroupName(s)}}))}_handleConversationGroupUpdated(e){var t;null===(t=e.RecentContactMod)||void 0===t||t.forEach((e=>{const{RecentContactUpdateContactGroup:{MsgUpdateGroup:{GroupId:t,GroupName:s,OldGroupName:o,RecentContactUpdateGroupItem:n,UpdateGroupType:i}}}=e;1===i?this._handleGroupNameUpdated({groupID:t,newName:s,oldName:o}):2===i&&this._handleGroupAddOrDeleteFromConversation({groupInfoList:n,groupName:o})}))}_handleConversationMarkUpdated(e){var t;const{appStore:s}=this._core;null===(t=null==e?void 0:e.RecentContactMod)||void 0===t||t.forEach((e=>{const{RecentContactMarkContact:{RecentContactMarkContactItem:t}}=e,o=[];null==t||t.forEach((e=>{const{RecentContactItem:t,CustomMark:n,StandardMark:i,OptType:r}=e,a=Hd(t),c=s.conversationStore.getConversation(a);c&&(r===Fd?this._updateStandMark({conversation:c,standardMark:i,updateConversationList:o}):r===$d?this._updateCustomMark({conversation:c,customMark:n,updateConversationList:o}):r===qd&&(this._updateStandMark({conversation:c,standardMark:i,updateConversationList:o}),this._updateCustomMark({conversation:c,customMark:n,updateConversationList:o})))})),Jd(o)}))}_updateStandMark(e){const{conversation:t,standardMark:s,updateConversationList:o}=e,n=zd(s);(function(e,t){if(e===t)return!0;if(!e||!t)return!1;if(e.length!==t.length)return!1;e.sort(),t.sort();for(let s=0,o=e.length;s<o;s++)if(e[s]!==t[s])return!1;return!0})(t.markList,n)||o.push({conversationID:t.conversationID,data:{markList:n}})}_updateCustomMark(e){const{conversation:t,customMark:s,updateConversationList:o}=e;t.customData!==s&&void 0!==s&&(t.customData=s,o.push({conversationID:t.conversationID,data:{customData:s}}))}_handleGroupNameUpdated(e){const{groupID:t,oldName:s,newName:o}=e;Td.getConversationGroup(t)!==o&&(Td.setConversationGroup(t,o),Kd(),this._updateLocalConversationGroupName({oldName:s,newName:o}))}_handleGroupAddOrDeleteFromConversation({groupInfoList:e,groupName:t}){const{appStore:s}=this._core,o=[];e.forEach((e=>{const{RecentContactItem:n,ContactOptType:i}=e,r=Hd(n),a=s.conversationStore.getConversation(r),c=a.conversationGroupList.indexOf(t);if(a){const e=a.conversationGroupList.slice();1===i&&-1===c?(e.push(t),o.push({conversationID:r,data:{conversationGroupList:e}})):2===i&&-1!==c&&(e.splice(c,1),o.push({conversationID:r,data:{conversationGroupList:e}}))}})),Jd(o)}dispose(){const{notificationCenter:e,InnerEvent:{MESSAGE_PUSH:t},InnerEventSubType:{CONVERSATION_MARK_UPDATED:s,CONVERSATION_GROUP_ADD:o,CONVERSATION_GROUP_DELETED:n,CONVERSATION_GROUP_UPDATED:i}}=this._core;e.unSubscribeInnerEvent(t,o,this._handleConversationGroupAdd,this),e.unSubscribeInnerEvent(t,n,this._handleConversationGroupDeleted,this),e.unSubscribeInnerEvent(t,i,this._handleConversationGroupUpdated,this),e.unSubscribeInnerEvent(t,s,this._handleConversationMarkUpdated,this)}};const sp={required:!0,rules:["string"],allowEmpty:!1},op={required:!0,rules:["array"],allowEmpty:!1},np={createConversationGroup:{groupName:sp,conversationIDList:{required:!0,rules:["array"],allowEmpty:!1}},renameConversationGroup:{oldName:sp,newName:Object.assign(Object.assign({},sp),{customValidator:e=>!(e.length>32)||"newName length cannot longer than 32"})},deleteConversationGroup:[{required:!0,rules:["string"],allowEmpty:!1}],addConversationsToGroup:{conversationIDList:op,groupName:sp},deleteConversationsFromGroup:{conversationIDList:op,groupName:sp},markConversation:{conversationIDList:op,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:op,customData:{required:!1,rules:["string"],allowEmpty:!0,customValidator:e=>"string"!=typeof e?"customData must be string":!(e.length>256)||"customData length cannot longer than 256"}}},ip={createConversationGroup:!0,deleteConversationGroup:!0,renameConversationGroup:!0,getConversationGroupList:!0,addConversationsToGroup:!0,deleteConversationsFromGroup:!0,markConversation:!0,setConversationCustomData:!0};var rp=new class{constructor(){this.name="ConversationGroup"}install(e){this._core=e,Ad.init(e),Td.init(e),Zd.init(e),ep.init(e),tp.init(e),e.helper.registerValidateConfig({auth:ip,params:np}),e.notificationCenter.subscribeInnerEvent(e.InnerEvent.LOGOUT,this.reset,this),e.notificationCenter.subscribeInnerEvent(e.InnerEvent.DESTROY,this.dispose,this)}dispose(){const{notificationCenter:e,InnerEvent:t}=this._core;e.unSubscribeInnerEvent(t.LOGOUT,this.reset,this),e.unSubscribeInnerEvent(t.DESTROY,this.dispose,this),tp.dispose(),ep.dispose()}reset(){ep.reset()}};const ap=new class{init(e){this.core=e}},cp="@TOPIC#_",up=7,lp=8,dp=17,pp=18,hp=20,gp=300,_p=0,mp=3600,vp=3021,fp=["topicID","topicName","avatar","introduction","notification","unreadCount","muteAllMembers","customData","nextMessageSeq","selfInfo","lastMessage"],Ip=e=>{const{core:{common:{getMessagePreviewText:t}}}=ap;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 Sp{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=Ip(),this.selfInfo={muteTime:0,readedSequence:0,messageRemindType:"",excludedUnreadSequenceList:void 0},this._init(e)}_init(e){for(const t in e)fp.includes(t)&&("lastMessage"===t?this[t]=Ip(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=Ip(e)}updateGroupAtInfoList(e){const{core:{common:{updateGroupAtInfo:t}}}=ap;t(e,this.groupAtInfoList)}updateTopic(e){const{core:{utils:{isUndefined:t},common:{deepMerge:s}}}=ap;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){const{core:{common:{deepMerge:t}}}=ap;return t(this.selfInfo,e,[],[""])>0}reduceUnreadCount(){return this.unreadCount>=1&&(this.unreadCount-=1,!0)}isLastMessageRevoked(e){var t;return e===(null===(t=this.lastMessage)||void 0===t?void 0:t.lastSequence)}setLastMessageRevoked(e){this.lastMessage.isRevoked=e}setLastMessageRevoker(e){this.lastMessage.revoker=e}clearGroupAtInfoList(){this.groupAtInfoList.length=0}}var Ep=new class{constructor(){this._name="TopicDataHandler",this._topicMap=new Map,this._topicRequestInfo=new Map}init(e){this._core=e;const{helper:t,constants:s,notificationCenter:o,InnerEvent:{LOGOUT:n,DESTROY:i}}=e;t.registerWorkflowStep(s.WORKFLOW_NAME.SYNC_SERVER_INFO_AFTER_RE_ONLINE,s.WORKFLOW_STEP.TOPIC_REQUEST_INFO_RESET,this._resetTopicRequestInfo,this),o.subscribeInnerEvent(n,this._reset,this),o.subscribeInnerEvent(i,this._dispose,this),console.log(`${this._name}.init`)}_hasTopic(e,t){var s;return!!(null===(s=this._topicMap.get(e))||void 0===s?void 0:s.get(t))}_setTopic(e,t,s){var o;null===(o=this._topicMap.get(e))||void 0===o||o.set(t,s)}_deleteTopic(e,t){var s;null===(s=this._topicMap.get(e))||void 0===s||s.delete(t)}getTopic(e,t){var s;return null===(s=this._topicMap.get(e))||void 0===s?void 0:s.get(t)}updateTopic(e){e.forEach((e=>{const{groupID:t,topicID:s}=e;let o=null;this._topicMap.has(t)||this._topicMap.set(t,new Map),this._hasTopic(t,s)?(o=this.getTopic(t,s),null==o||o.updateTopic(e)):(this._getLastMessage(e),o=new Sp(e),this._setTopic(t,s,o));const n=this.computeUnreadCount(o);null==o||o.updateUnreadCount(n)}))}_getLastMessage(e){const{utils:{isEmpty:t,isUndefined:s,isArray:o}}=this._core;if(!s(e.lastMsg)){let s=null,n="";o(e.lastMsg.elements)?(s=e.lastMsg.elements[0].content,n=e.lastMsg.elements[0].type):(s=e.lastMsg.elements.content,n=e.lastMsg.elements.type);const i={payload:s,type:n,time:e.lastMsg.time,sequence:e.lastMsg.sequence,from:e.lastMsg.from,nick:e.lastMsg.nick,avatar:e.lastMsg.avatar,version:e.lastMsg.messageVersion,cloudCustomData:e.lastMsg.cloudCustomData,isRevoked:2===e.lastMsg.isPlaceMessage,revoker:t(e.lastMsg.revokerInfo)?null:e.lastMsg.revokerInfo.revoker};e.lastMessage=i}}computeUnreadCount(e){const{excludedUnreadSequenceList:t=[],readedSequence:s}=e.selfInfo;let o=e.nextMessageSeq-e.selfInfo.readedSequence-1;if(t.length>0){let n=0;t.forEach((t=>{t>s&&t<=e.nextMessageSeq-1&&(n+=1)})),n>=1&&(o-=n)}return o>0?o:0}updateTopicAtInfo(e){0!==e.length&&e.forEach((e=>{const{utils:{isEmpty:t}}=this._core,{groupAtInfoList:s}=e;t(s)||this.updateGroupAtInfoList(s)}))}updateGroupAtInfoList(e,t=!1){if(0===e.length)return;const{common:{getCurrentUserID:s},utils:{isUndefined:o,isEmpty:n}}=this._core,i=s();let r=null;e.forEach((e=>{var s;const{groupID:n,topicID:a,from:c}=e;c!==i&&(r=this.getTopic(n,a),r&&r.updateGroupAtInfoList(e),o(r)&&t&&(this.updateTopic([{groupID:n,topicID:a}]),null===(s=this.getTopic(n,a))||void 0===s||s.updateGroupAtInfoList(e)))})),n(r)||this.emitTopicUpdate(r)}getTopicList(e,t=[]){const s=this._topicMap.get(e),o=[];return s&&o.push(...s.values()),t.length>0?o.filter((e=>t.includes(e.topicID))):o}deleteTopicList(e,t=[]){this._topicMap.has(e)&&(t.forEach((t=>{this._hasTopic(e,t)&&this._deleteTopic(e,t)})),console.log(`${this._name}.deleteTopicList groupID:${e} topicID:${t.join(",")}`))}clearGroupAtInfoList(e,t){const{utils:{isEmpty:s}}=this._core,o=this.getTopic(e,t);s(null==o?void 0:o.groupAtInfoList)||(null==o||o.clearGroupAtInfoList(),console.log(`${this._name}.clearGroupAtInfoList topicID:${t}`))}markMessageAsRead(e,t){const{message:{messageDataHandler:s},OuterConstant:{CONV_GROUP:o}}=this._core,n=(null==s?void 0:s.getLocalMessageList(`${o}${e}`))||[];if(0===n.length)return;const{length:i}=n;for(let e=i-1;e>=0;e--){const s=n[e];if(!(t&&s.sequence>t)){if("in"===s.flow&&s.isRead)break;s.setIsRead(!0)}}}updateUnreadCount(e,t){const{message:{messageDataHandler:s},OuterConstant:{CONV_GROUP:o}}=this._core;let n=!1;const i=this.getTopic(e,t);if(!i)return;const r=(null==s?void 0:s.getLocalMessageList(`${o}${t}`))||[],a=i.unreadCount,c=null==r?void 0:r.filter((e=>!e.isRead&&!e._onlineOnlyFlag&&!e.isDeleted)).length;console.log(`${this._name}._updateUnreadCount topicID:${t} currentUnreadCount:${a} newUnreadCount:${c}`),a!==c&&(i.updateUnreadCount(c),n=!0),n&&this.emitTopicUpdate(i)}updateSelfInfo(e){const{groupID:t,topicID:s,selfInfo:o}=e,n=this.getTopic(t,s);if(n){const e=n.updateSelfInfo(o);console.log(`${this._name}.updateSelfInfo topicID:${s} info:${JSON.stringify(o)} isUpdated:${e}`),e&&this.emitTopicUpdate(n)}}getTopicRequestInfo(e){return this._topicRequestInfo.get(e)||{}}setTopicRequestInfo(e,t){return this._topicRequestInfo.set(e,t)}emitTopicUpdate(e){const{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();const{notificationCenter:e,InnerEvent:t}=this._core;e.unSubscribeInnerEvent(t.LOGOUT,this._reset,this),e.unSubscribeInnerEvent(t.DESTROY,this._dispose,this)}};const Cp=(e="")=>{const{core:{OuterConstant:t}}=ap;return e.replace(t.CONV_GROUP,"")},Mp=(e="")=>e.split(cp)[0];var yp=new class{constructor(){this._name="TopicMessageHandler"}init(e){this._core=e;const{helper:t,notificationCenter:s,constants:{WORKFLOW_NAME:o,WORKFLOW_STEP:n},InnerEvent:{MESSAGE_PUSH:i,TOPIC_NEW_MESSAGE:r,TOPIC_MESSAGE_DELETED:a,TOPIC_MESSAGE_REVOKED:c,TOPIC_MESSAGE_MODIFIED:u,DESTROY:l}}=e,{InnerEventSubType:{TOPIC_AT_TIPS:d,TOPIC_LATEST_MESSAGE:p}}=s;t.registerWorkflowStep(o.SYNC_SERVER_INFO_AFTER_LOGIN,n.UPDATE_TOPIC_AFTER_UNREAD_SYNC_FINISHED,this._handleUnreadSyncFinished,this),t.registerWorkflowStep(o.RECEIVE_GROUP_NEW_MESSAGE,n.UPDATE_TOPIC_BY_RECEIVE_NEW_MESSAGE,this._handleNewMessage,this),s.subscribeInnerEvent(r,this._handleNewMessage,this),s.subscribeInnerEvent(a,this._handleMessageDeleted,this),s.subscribeInnerEvent(c,this._handleMessageRevoked,this),s.subscribeInnerEvent(u,this._handleMessageModified,this),s.subscribeInnerEvent(i,d,this._handleTopicAtTips,this),s.subscribeInnerEvent(i,p,this._handleLatestMessage,this),s.subscribeInnerEvent(l,this._dispose,this),console.log(`${this._name}.init`)}_handleUnreadSyncFinished(e){var t;const{constants:{WORKFLOW_STEP:s}}=this._core,{groupTipList:o=[]}=e.result[s.UNREAD_MESSAGE_SYNC]||{};for(let e=0;e<o.length;e++){const s=o[e];12===s.Event&&(null===(t=s.GroupTips[0].MsgBody)||void 0===t?void 0:t.TopicId)&&this._handleTopicAtTips(s)}}_handleNewMessage(e){const{conversationUpdateFieldList:t=[]}=e.result||{};if(0===t.length)return;const{common:{isTopic:s}}=this._core;if(!s(t[0].conversationID))return;const{common:{getCurrentUserID:o}}=this._core;t.forEach((e=>{const{conversationID:t="",lastMessage:s}=e,n=Cp(t),i=Mp(n),r=Ep.getTopic(i,n);if(r){const{from:e,sequence:t}=s,n=t+1,i=e===o();if(n>r.nextMessageSeq){r.updateNextMessageSeq(n),r.updateLastMessage(s),r.updateReadSequence(t,i);const e=i?0:Ep.computeUnreadCount(r);r.updateUnreadCount(e),this._emitTopicUpdate(r)}}}))}_handleMessageDeleted(e){const t=Cp(e),s=Mp(t),o=Ep.getTopic(s,t);if(console.log(`${this._name}._handleMessageDeleted, topicID:${t} hasTopic:${!!o}`),!o)return;const{message:{messageDataHandler:n},utils:{isEmpty:i}}=this._core,r=(null==n?void 0:n.getLocalMessageList(e))||[];let a={};for(let e=(r.length||0)-1;e>=0;e--)if(!r[e].isDeleted){a=r[e];break}let c=!1;o.lastMessage.lastSequence!==a.sequence&&(i(a)&&(a={}),o.updateLastMessage(a),c=!0),c&&(this._emitTopicUpdate(o),console.log(`${this._name}._handleMessageDeleted, topicID:${t} with lastMessage:${o.lastMessage}`))}_handleMessageRevoked(e){const{messageList:t=[]}=e;if(console.log(`${this._name}._handleMessageRevoked messageList:${t.length}`),0===t.length)return;let s=null,o=!1;t.forEach((e=>{const{to:t,sequence:n,revoker:i}=e,r=Mp(t);if(s=Ep.getTopic(r,t),s){s.reduceUnreadCount()&&(o=!0),s.isLastMessageRevoked(n)&&(s.setLastMessageRevoked(!0),s.setLastMessageRevoker(i),o=!0);const{excludedUnreadSequenceList:e=[]}=s.selfInfo;e.push(n),s.updateSelfInfo({excludedUnreadSequenceList:e})}})),o&&this._emitTopicUpdate(s)}_handleMessageModified(e){const{conversationID:t,messageList:s}=e,o=Cp(t),n=Mp(o),i=Ep.getTopic(n,o);if(console.log(`${this._name}._handleMessageModified topicID:${o} hasTopic:${!!i}`),!i)return;const{lastMessage:r}=i;if(r){const e=(null==s?void 0:s[0])||{};if(this._shouldUpdateLastMessage(r,e)){const{common:{getMessagePreviewText:t}}=this._core,{time:s,sequence:o,elements:n,cloudCustomData:a,messageVersion:c}=e;r.type=n[0].type,r.payload=n[0].content,r.messageForShow=t(r.type,r.payload),r.cloudCustomData=a,r.version=c,r.lastSequence=o,r.lastTime=s,this._emitTopicUpdate(i)}}}_shouldUpdateLastMessage(e,t){if(null===e.payload)return!0;const{sequence:s,messageVersion:o}=t;return e.lastSequence===s&&e.version!==o}_emitTopicUpdate(e){const{notificationCenter:t,OuterEvent:s}=this._core;t.emitOuterEvent(s.TOPIC_UPDATED,{name:s.TOPIC_UPDATED,data:e})}_handleTopicAtTips(e){const{GroupTips:t=[]}=e,s=[];let o=!1;t.forEach((e=>{const{GroupAtTips:t,MsgBody:n,MsgRandom:i,ClientSeq:r}=e;let a={};t?a=this._convertAtInfo(t):n&&(a=this._convertAtInfo(n),o=!0),a.__random=i,a.__sequence=r,s.push(a)})),Ep.updateGroupAtInfoList(s,o)}_convertAtInfo(e){const{From_Account:t,GroupId:s,TopicId:o,MsgSeq:n,GroupAtType:i}=e;return{groupID:s,topicID:o,from:t,sequence:n,groupAtType:i}}_handleLatestMessage(e){const{utils:{isEmpty:t},message:{messageHelper:s,messageFactory:o}}=this._core,{NewMsg:n,NoUnreadSeqList:i}=e||{};if(!t(n)){const{GroupInfo:{TopicId:e}}=n,t=s.parseServerGroupMessage(n),r=o.createMessage(t);r.setElement(t.elements),this._updateUnreadCountAndLastMessage({topicID:e,message:r,excludedUnreadSequenceList:i})}}_updateUnreadCountAndLastMessage(e){const{utils:{isUndefined:t}}=this._core,{topicID:s,message:o,excludedUnreadSequenceList:n}=e,i=Mp(s),r=Ep.getTopic(i,s);if(r){let e=r.selfInfo.excludedUnreadSequenceList||[];if(t(n)||(e=n),o._isExcludedFromUnreadCount&&e.push(o.sequence),r.updateSelfInfo({excludedUnreadSequenceList:e}),console.log(`${this._name}._updateUnreadCountAndLastMessage latest message sequence:${o.sequence} lastMessage sequence:${r.lastMessage.lastSequence}`),o.sequence>r.lastMessage.lastSequence){const e=o.sequence+1;r.updateLastMessage(o),r.updateNextMessageSeq(e);const t=Ep.computeUnreadCount(r);r.updateUnreadCount(t),this._emitTopicUpdate(r)}}}_dispose(){const{notificationCenter:e,InnerEvent:{MESSAGE_PUSH:t,TOPIC_NEW_MESSAGE:s,TOPIC_MESSAGE_DELETED:o,TOPIC_MESSAGE_REVOKED:n,TOPIC_MESSAGE_MODIFIED:i,DESTROY:r}}=this._core,{InnerEventSubType:{TOPIC_AT_TIPS:a,TOPIC_LATEST_MESSAGE:c}}=e;e.unSubscribeInnerEvent(s,this._handleNewMessage,this),e.unSubscribeInnerEvent(o,this._handleMessageDeleted,this),e.unSubscribeInnerEvent(n,this._handleMessageRevoked,this),e.unSubscribeInnerEvent(i,this._handleMessageModified,this),e.unSubscribeInnerEvent(t,a,this._handleTopicAtTips,this),e.unSubscribeInnerEvent(t,c,this._handleLatestMessage,this),e.unSubscribeInnerEvent(r,this._dispose,this)}};var Tp=new class{constructor(){this._name="TopicOperationHandler"}init(e){this._core=e;const{notificationCenter:t,InnerEvent:{MESSAGE_PUSH:s,DESTROY:o}}=e,{InnerEventSubType:{TOPIC_TIPS_NOTIFICATION:n,TOPIC_SYSTEM_NOTIFICATION:i,TOPIC_MESSAGE_READ_SYNC:r}}=t;t.subscribeInnerEvent(s,n,this._handleTopicTips,this),t.subscribeInnerEvent(s,i,this._handleTopicNotices,this),t.subscribeInnerEvent(s,r,this._handleTopicMessageReadSynced,this),t.subscribeInnerEvent(o,this._dispose,this),console.log(`${this._name}.init`)}_handleTopicTips(e){const{GroupTips:t=[]}=e;for(let e=0;e<t.length;e++){const s=t[e];s.MsgBody.OpType!==up?s.MsgBody.OpType!==lp?this._emitTopicTips(s):this._handleTopicProfileUpdated(s):this._handleMuteTimeUpdated(s)}}_handleMuteTimeUpdated(e){const{common:{getCurrentUserID:t}}=this._core,{GroupInfo:{GroupId:s,TopicId:o},MsgBody:{MsgMemberInfo:n=[]}}=e;for(let e=0;e<n.length;e++){const{User_Account:i,ShutupTime:r}=n[e];if(i===t()&&r>=0){Ep.updateSelfInfo({groupID:s,topicID:o,selfInfo:{muteTime:r}});break}}}_handleTopicProfileUpdated(e){const{GroupInfo:{GroupId:t,TopicId:s},MsgBody:{MsgTopicNewInfo:{CustomString:o,ShutupAll:n,TopicFaceUrl:i,TopicIntroduction:r,TopicName:a,TopicNotification:c}}}=e,u=Ep.getTopic(t,s);u&&(u.updateTopic({groupID:t,topicID:s,customData:o,muteAllMembers:n,avatar:i,introduction:r,topicName:a,notification:c}),Ep.emitTopicUpdate(u))}_handleTopicNotices(e){const{GroupTips:t=[]}=e;for(let e=0;e<t.length;e++){const s=t[e],{MsgBody:{ReportType:o,TopicIdArray:n,MsgFlag:i},GroupInfo:{GroupId:r,TopicId:a}}=s;o===dp?this._handleTopicCreated({groupID:r,topicID:a}):o===pp?this._handleTopicDeleted({groupID:r,topicIDList:n}):o===hp?this._handleMessageRemindTypeUpdated({groupID:r,topicID:a,messageRemindType:i}):this._emitTopicNotices(s)}}_handleTopicCreated(e){const{OuterEvent:t,notificationCenter:s}=this._core;Ep.setTopicRequestInfo(e.groupID,{}),s.emitOuterEvent(t.TOPIC_CREATED,{name:t.TOPIC_CREATED,data:e})}_handleTopicDeleted(e){const{OuterEvent:t,notificationCenter:s}=this._core,{groupID:o,topicIDList:n=[]}=e;Ep.deleteTopicList(o,n),s.emitOuterEvent(t.TOPIC_DELETED,{name:t.TOPIC_DELETED,data:e})}_handleMessageRemindTypeUpdated(e){const{groupID:t,topicID:s,messageRemindType:o}=e;Ep.updateSelfInfo({groupID:t,topicID:s,selfInfo:{messageRemindType:o}})}_handleTopicMessageReadSynced(e){const{GroupTips:t}=e,{utils:{isUndefined:s}}=this._core;t.forEach((e=>{const{GroupReadInfoArray:t}=e.MsgBody;s(t)||t.forEach((e=>{const{GroupId:t,TopicId:s,LastReadMsgSeq:o}=e;console.log(`${this._name}._handleTopicMessageReadSynced topicID:${s} lastReadSequence:${o}`),Ep.updateSelfInfo({groupID:t,topicID:s,selfInfo:{readedSequence:o}}),Ep.clearGroupAtInfoList(t,s),Ep.markMessageAsRead(s,o),Ep.updateUnreadCount(t,s)}))}))}_emitTopicTips(e){const{message:{messageHelper:t,messageFactory:s},OuterConstant:o,OuterEvent:n,notificationCenter:i}=this._core;e.MsgBody.MsgType=o.MSG_GRP_TIP;const r=t.parseServerGroupMessage(e);r.flow="in",r.conversationType=o.CONV_GROUP;const a=s.createMessage(r);a.setElement(r.elements),a.isSystemMessage=!0,i.emitOuterEvent(n.MESSAGE_RECEIVED,{name:n.MESSAGE_RECEIVED,data:[a]})}_emitTopicNotices(e){const{message:{messageHelper:t,messageFactory:s},OuterConstant:o,OuterEvent:n,notificationCenter:i}=this._core;e.MsgBody.MsgType=o.MSG_GRP_SYS_NOTICE;const r=t.parseServerGroupMessage(e);r.flow="in",r.conversationType=o.CONV_SYSTEM,r.conversationID=o.CONV_SYSTEM;const a=s.createMessage(r);a.setElement(r.elements),a.isSystemMessage=!0,i.emitOuterEvent(n.MESSAGE_RECEIVED,{name:n.MESSAGE_RECEIVED,data:[a]})}_dispose(){const{notificationCenter:e,InnerEvent:{MESSAGE_PUSH:t,DESTROY:s}}=this._core,{InnerEventSubType:{TOPIC_TIPS_NOTIFICATION:o,TOPIC_SYSTEM_NOTIFICATION:n,TOPIC_MESSAGE_READ_SYNC:i}}=e;e.unSubscribeInnerEvent(t,o,this._handleTopicTips,this),e.unSubscribeInnerEvent(t,n,this._handleTopicNotices,this),e.unSubscribeInnerEvent(t,i,this._handleTopicMessageReadSynced,this),e.unSubscribeInnerEvent(s,this._dispose,this)}};var Ap=new class{constructor(){this._name="GetJoinedCommunityHandler"}init(e){this._core=e;const{helper:t}=e;t.registerApi({apiName:"getJoinedCommunityList",context:this})}getJoinedCommunityList(){return h(this,void 0,void 0,(function*(){const{apiMap:{getGroupList:e}}=this._core,t=(yield e(!0)).filter((e=>!0===e.isSupportTopic));return console.log(`${this._name}.getJoinedCommunityList ok, count:${t.length}`),{code:0,data:{groupList:t}}}))}};var Op=new class{constructor(){this._name="CreateTopicHandler"}init(e){this._core=e;const{helper:t}=e;t.registerApi({apiName:"createTopicInCommunity",context:this})}createTopicInCommunity(e){return h(this,void 0,void 0,(function*(){const t="createTopicInCommunity",{utils:{isUndefined:s},common:{isTopic:o},helper:{ChatError:n}}=this._core,{topicID:i}=e;if(!s(i)&&!o(i)){const e=new n({functionName:t,code:vp});throw console.error(`${this._name}.${t} fail:`,e),e}try{const s=yield function(e,t){return h(this,void 0,void 0,(function*(){const{groupID:s,topicID:o,topicName:n,avatar:i,notification:r,introduction:a,customData:c}=e,u={GroupId:s,TopicId:o,TopicName:n,FaceUrl:i,Notification:r,Introduction:a,CustomString:c};return t.common.buildAndSendPacket({servcmd:"million_group_open_http_svc.create_topic",data:u})}))}(e,this._core),{TopicId:o=""}=s||{};return console.log(`${this._name}.${t} ok, topicID:${o}`),Ep.updateTopic([Object.assign(Object.assign({},e),{topicID:o})]),{code:0,data:{topicID:o}}}catch(e){throw console.error(`${this._name}.${t} failed, error:`,e),e}}))}};var Dp=new class{constructor(){this._name="DeleteTopicHandler"}init(e){this._core=e;const{helper:t}=e;t.registerApi({apiName:"deleteTopicFromCommunity",context:this})}deleteTopicFromCommunity(e){return h(this,void 0,void 0,(function*(){const t="deleteTopicFromCommunity",{groupID:s,topicIDList:o=[]}=e;try{const n=yield function(e,t){return h(this,void 0,void 0,(function*(){const{groupID:s,topicIDList:o}=e,n={GroupId:s,TopicIdList:o};return t.common.buildAndSendPacket({servcmd:"million_group_open_http_svc.destroy_topic",data:n})}))}({groupID:s,topicIDList:o},this._core),{DestroyResultItem:i=[]}=n||{},r=[],a=[],c=[];return i.forEach((e=>{const{TopicId:t,ErrorCode:s,ErrorInfo:o}=e;0===s?(r.push({topicID:t}),c.push(t)):a.push({topicID:t,code:s,message:o})})),c.length>0&&Ep.deleteTopicList(e.groupID,c),console.log(`${this._name}.${t} ok, groupID:${s} success:${r.length} fail:${a.length}`),{code:0,data:{successTopicList:r,failureTopicList:a}}}catch(e){throw console.error(`${this._name}.${t} failed, error:`,e),e}}))}};var Rp=new class{constructor(){this._name="GetTopicHandler",this._getCloudConfig=e=>{const{store:t}=this._core;return(t.get("cloudConfig")||{})[e]}}init(e){this._core=e;const{helper:t}=e;t.registerApi({apiName:"getTopicList",context:this})}getTopicList(e){return h(this,void 0,void 0,(function*(){const{groupID:t,topicIDList:s=[]}=e,o=0===s.length;if(this._isFetchingFromCache(t,o)){const e=Ep.getTopicList(t,s);if(o||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},o)}))}_isFetchingFromCache(e,t){const{hasFetchedAllTopics:s=!1,time:o=0}=Ep.getTopicRequestInfo(e);return!(!s&&(t||s))&&Date.now()-o<this._getCacheDuration()}_getCacheDuration(){const{utils:{isUndefined:e}}=this._core;let t=this._getCloudConfig("topic_cache_time");return!e(t)&&(t=parseInt(t,10),t>=_p&&t<=mp)?1e3*t:1e3*gp}_getTopicListFromServer(e,t){return h(this,void 0,void 0,(function*(){const s="_getTopicListFromServer",{utils:{isEmpty:o}}=this._core,{groupID:n}=e;try{const i=yield function(e,t){return h(this,void 0,void 0,(function*(){const{groupID:s,topicIDList:o}=e,n={GroupId:s,TopicIdList:o,MemberInfoFilter:["NoUnreadSeqList"]};return t.common.buildAndSendPacket({servcmd:"million_group_open_http_svc.get_topic",data:n})}))}(e,this._core),{TopicAndSelfInfo:r=[]}=i||{},a=[],c=[],u=[];this._convertTopicInfoList(r).forEach((e=>{const{topic:t,selfInfo:s,code:o,message:n}=e,{topicID:i}=t;0===o?(a.push(Object.assign(Object.assign({},t),{selfInfo:s})),c.push(i)):u.push({topicID:i,code:o,message:n})})),Ep.updateTopic(a),Ep.updateTopicAtInfo(a),console.log(`${this._name}.${s} groupID:${n} from remote, success count:${c.length}, fail count:${u.length}`);let l=[];return o(c)||(Ep.setTopicRequestInfo(n,{hasFetchedAllTopics:t,time:Date.now()}),l=Ep.getTopicList(n,c)),{code:0,data:{successTopicList:l,failureTopicList:u}}}catch(e){throw console.error(`${this._name}.${s} failed, error:`,e),e}}))}_convertTopicInfoList(e){const t=[];return e.forEach((e=>{const{TopicInfo:s={},SelfInfo:o={},ErrorCode:n,ErrorInfo:i}=e;t.push({code:n,message:i,topic:this._convertTopicInfo(s),selfInfo:this._convertSelfInfo(o)})})),t}_convertTopicInfo(e){const{utils:{isEmpty:t}}=this._core;if(t(e))return{};const{CreateTime:s,CustomString:o,FaceUrl:n,GroupId:i,LastMsgTime:r,NextMsgSeq:a,Introduction:c,Notification:u,ShutUpAllFlag:l,TopicId:d,TopicName:p,LastMsg:h,AtInfoList:g}=e;return{createTime:s,customData:o,avatar:n,groupID:i,lastMessageTime:r,nextMessageSeq:a,introduction:c,notification:u,muteAllMembers:l,topicID:d,topicName:p,lastMsg:this._convertLastMsg(h),groupAtInfoList:this._convertAtInfoList({groupID:i,topicID:d,atInfoList:g})}}_convertLastMsg(e){const{utils:{isUndefined:t},OuterConstant:s}=this._core;if(t(e))return;4===e.Event&&(e.MsgBody.MsgType=s.MSG_GRP_TIP);const{message:{messageHelper:o}}=this._core,n=o.parseServerGroupMessage(e),{From_AccountHeadurl:i,From_AccountNick:r,LastMsgSeq:a}=e;return Object.assign(Object.assign({},n),{avatar:i,nick:r,sequence:a})}_convertAtInfoList(e){const{groupID:t,topicID:s,atInfoList:o=[]}=e;if(0===o.length)return[];const n=[];return o.forEach((e=>{const{AtFlagList:o,AtMsgSeq:i,From_Account:r}=e;n.push({groupID:t,topicID:s,groupAtType:o,sequence:i,from:r})})),n}_convertSelfInfo(e){const{utils:{isEmpty:t}}=this._core;if(t(e))return{};const{InheritGroupReceiveOption:s,MsgFlag:o,MsgSeq:n,NoUnreadSeqList:i,ShutUpTime:r}=e;return{inheritGroupReceiveOption:s,messageRemindType:o,readedSequence:n,excludedUnreadSequenceList:i,muteTime:r}}};var Lp=new class{constructor(){this._name="UpdateTopicHandler"}init(e){this._core=e;const{helper:t}=e;t.registerApi({apiName:"updateTopicProfile",context:this})}updateTopicProfile(e){return h(this,void 0,void 0,(function*(){const t="updateTopicProfile",{utils:{isUndefined:s}}=this._core,{groupID:o,topicID:n,muteAllMembers:i}=e;s(e.muteAllMembers)||(e.muteAllMembers=!0===i?"On":"Off");try{return yield function(e,t){return h(this,void 0,void 0,(function*(){const{groupID:s,topicID:o,topicName:n,avatar:i,notification:r,introduction:a,customData:c,muteAllMembers:u}=e,l={GroupId:s,TopicId:o,TopicName:n,FaceUrl:i,Notification:r,Introduction:a,CustomString:c,ShutUpAllMember:u};return t.common.buildAndSendPacket({servcmd:"million_group_open_http_svc.modify_topic",data:l})}))}(e,this._core),console.log(`${this._name}.${t} ok, topicID:${n}`),Ep.updateTopic([e]),{code:0,data:{topic:Ep.getTopic(o,n)}}}catch(e){throw console.error(`${this._name}.${t} failed, topicID:${n} error:`,e),e}}))}};var Np=new class{constructor(){this._name="MessageReadHandler"}init(e){this._core=e;const{helper:t,common:{isTopic:s}}=e;t.registerApi({apiName:"setMessageRead",context:this,matcher:e=>s(e[0].conversationID)})}setMessageRead(e){return h(this,void 0,void 0,(function*(){const{utils:{isEmpty:t},ssoLog:s,helper:{ChatError:o}}=this._core,{conversationID:n}=e,i={code:0,data:{}},r=Cp(n),a=Mp(r),c=Ep.getTopic(a,r);if(console.log(`${this._name}.setMessageRead topicID:${r} unreadCount:${(null==c?void 0:c.unreadCount)||0}`),!c)return i;if(t(c.groupAtInfoList)||this._deleteTopicAtTips(a,r),0===c.unreadCount)return i;const u=this._getLocalMessageMaxSequence(c),l=s.createSSOLogData({method:"setMessageRead"});l.setLogInfo({message:`conversationID:${n}`,moreMessage:`lastMessageSequence:${u}`});try{yield this._setTopicMessageRead(a,r,u),l.end()}catch(e){const{errorCode:t,errorInfo:s}=e,n=new o({functionName:"setMessageRead",code:t,message:s});throw l.setError(n).end(),n}return i}))}_deleteTopicAtTips(e,t){return h(this,void 0,void 0,(function*(){console.log(`${this._name}._deleteTopicAtTips groupID:${e} topicID:${t}`);const s=Ep.getTopic(e,t);if(!s)return;const o=(null==s?void 0:s.groupAtInfoList)||[];if(0!==o.length)try{const{common:{getCurrentUserID:s},OuterConstant:{CONV_AT_ALL:n}}=this._core;let i=[...o];if(i=o.filter((e=>!e.atTypeArray.includes(n))),0===i.length)return void Ep.clearGroupAtInfoList(e,t);const r=i.map((e=>({From_Account:e.from,To_Account:s(),MsgSeq:e.__sequence,MsgRandom:e.__random,GroupId:e.groupID})));yield function(e,t){return h(this,void 0,void 0,(function*(){const{messageListToDelete:s}=e,o={DelMsgList:s};return t.common.buildAndSendPacket({servcmd:"openim.deletemsg",data:o})}))}({messageListToDelete:r},this._core),console.log(`${this._name}._deleteTopicAtTips ok. count:${o.length}`),Ep.clearGroupAtInfoList(e,t)}catch(e){console.error(`${this._name}._deleteTopicAtTips fail:`,e)}}))}_getLocalMessageMaxSequence(e){var t;const{message:{messageDataHandler:s},OuterConstant:{CONV_GROUP:o}}=this._core,{topicID:n}=e,i=s.getLocalMessageList(`${o}${n}`),r=Math.max(...i.map((e=>e.sequence)));let a=(null===(t=null==e?void 0:e.lastMessage)||void 0===t?void 0:t.lastSequence)||0;return r>a&&(console.log(`${this._name}._getLocalMessageMaxSequence update lastMessageSequence from ${a} to ${r}`),a=r),a}_setTopicMessageRead(e,t,s){return h(this,void 0,void 0,(function*(){try{yield function(e,t){return h(this,void 0,void 0,(function*(){const{groupID:s,topicID:o,lastMessageSequence:n}=e,i={GroupId:s,TopicId:o,MsgReadedSeq:n};return t.common.buildAndSendPacket({servcmd:"million_group_open_http_svc.msg_read_report",data:i})}))}({groupID:e,topicID:t,lastMessageSequence:s},this._core),console.log(`${this._name}._setTopicMessageRead ok, lastReadSequence:${s}`),Ep.updateSelfInfo({groupID:e,topicID:t,selfInfo:{readedSequence:s}}),Ep.markMessageAsRead(t,s),Ep.updateUnreadCount(e,t)}catch(e){throw console.error(`${this._name}._setTopicMessageRead fail:`,e),e}}))}};var bp=new class{init(e){console.log("TopicAction.init"),Ap.init(e),Op.init(e),Dp.init(e),Rp.init(e),Lp.init(e),Np.init(e)}};const Gp={required:!0,rules:["string"],allowEmpty:!1},wp={createTopicInCommunity:{groupID:Gp,topicName:Gp},deleteTopicFromCommunity:{groupID:Gp,topicIDList:{required:!1,rules:["array"],allowEmpty:!0}},getTopicList:{groupID:Gp,topicIDList:{required:!1,rules:["array"],allowEmpty:!0}},updateTopicProfile:{groupID:Gp,topicID:Gp}},Pp={getJoinedCommunityList:!0,createTopicInCommunity:!0,deleteTopicFromCommunity:!0,getTopicList:!0,updateTopicProfile:!0};var Up=new class{constructor(){this.name="Topic"}install(e){ap.init(e),Ep.init(e),yp.init(e),Tp.init(e),bp.init(e),e.helper.registerValidateConfig({auth:Pp,params:wp})}};function kp(e,t){return Math.round(Number(e)*Math.pow(10,t))/Math.pow(10,t)}const Fp="qualityStat",$p="im-ssolog-quality-stat";var qp;!function(e){e[e.ONLINE=8]="ONLINE"}(qp||(qp={}));const xp="networkRTT",Vp="messageE2EDelay",Bp="sendMessageC2C",jp="sendMessageGroup",Kp="sendMessageGroupAV",Hp="sendMessageRichMedia",Wp="cosUpload",Yp="messageReceivedGroup",zp="messageReceivedGroupAVPush",Jp="messageReceivedGroupAVPull",Qp={[xp]:2,[Vp]:3,[Bp]:4,[jp]:5,[Kp]:6,[Hp]:7,[Yp]:8,[zp]:9,[Jp]:10,[Wp]:11},Xp=[Bp,jp,Kp,Hp,Wp],Zp=[Yp,zp,Jp],eh=[xp,Vp,Bp,jp,Kp,Hp,Wp,Yp,zp,Jp],th={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},sh="quality_stat";var oh=new class{constructor(){this._messageStatsMap=new Map,this._userSideErrorCodes=new Set(Object.values(th))}init(e){this._core=e,Object.values(Xp).forEach((e=>{this._messageStatsMap.set(e,{totalCount:0,successCount:0,failedCountOfUserSide:0,costSum:0,costCount:0,fileSizeSum:0})}))}dispatchSendStats(e){const{name:t,message:s,error:o,startTs:n}=e,{SEND_MESSAGE_STAT:i}=this._core.constants;switch(t){case i.TOTAL_COUNT:this._handleTotalCount(s);break;case i.SUCCESS_COUNT:this._handleSuccessCount(s);break;case i.FAILED_COUNT:this._handleFailedCount(s,o);break;case i.SEND_COST:this._handleSendCost(s,n)}}getStatResult(e){const t=this._messageStatsMap.get(e);if(!t||0===t.totalCount)return null;const{totalCount:s,successCount:o,failedCountOfUserSide:n}=t,i=kp(o/s*100,2),r=o+n,a=kp(r/s*100,2),c=this._calcAverageValue(t,e);return this._resetStat(e),{total_count:s,success_count_business:o,percent_business:i,success_count_platform:r,percent_platform:a,average_value:c}}_handleTotalCount(e){const t=this._getSendMessageSpecifiedKey(e),s=t&&this._messageStatsMap.get(t);s&&s.totalCount++}_handleSuccessCount(e){const t=this._getSendMessageSpecifiedKey(e),s=t&&this._messageStatsMap.get(t);s&&s.successCount++}_handleFailedCount(e,t){var s;const o=null!==(s=null==t?void 0:t.code)&&void 0!==s?s:null==t?void 0:t.errorCode;if(this._isUserSideError(o)){const t=this._getSendMessageSpecifiedKey(e),s=t&&this._messageStatsMap.get(t);s&&s.failedCountOfUserSide++}}_handleSendCost(e,t){const s=this._getSendMessageSpecifiedKey(e),o=s&&this._messageStatsMap.get(s);o&&(o.costSum+=Date.now()-t,o.costCount++)}_isUserSideError(e){return this._userSideErrorCodes.has(e)||e>=120001&&e<=13e4||e>=10100&&e<=10200}_getSendMessageSpecifiedKey(e){const{MSG_IMAGE:t,MSG_AUDIO:s,MSG_VIDEO:o,MSG_FILE:n,CONV_C2C:i,CONV_GROUP:r,GRP_AVCHATROOM:a}=this._core.OuterConstant;if([t,s,o,n].includes(e.type))return Hp;if(e.conversationType===i)return Bp;if(e.conversationType===r){const{groupStore:t}=this._core.appStore,s=t.getGroup(e.to);if(!s)return;const{type:o}=s;return o===a?Kp:jp}}_calcAverageValue(e,t){return 0===e.costCount?0:t===Wp?Math.round(1e3*e.fileSizeSum/e.costSum):Math.round(e.costSum/e.costCount)}_resetStat(e){const t=this._messageStatsMap.get(e);t&&(t.totalCount=0,t.successCount=0,t.failedCountOfUserSide=0,t.costSum=0,t.costCount=0,t.fileSizeSum=0)}};var nh=new class{constructor(){this._lastCycleStats=new Map,this._currentCycleStats=new Map}init(e){this._core=e;const{OuterEvent:t,notificationCenter:s}=e;this._initStatsMap(),s.subscribeOuterEvent(t.MESSAGE_RECEIVED,this._onMessageReceived,this)}addMessageSequence(e){const t=this._getReceivedMessageSpecifiedKey(e),{utils:{isUndefined:s},OuterConstant:{CONV_GROUP:o}}=this._core;if(s(t)||!this._currentCycleStats.has(t))return void console.warn(`${Fp}.addMessageSequence invalid key:`,t);const{conversationID:n,sequence:i}=e,r=n.replace(o,""),a=this._lastCycleStats.get(t);if(0===a.size||!a.has(r))return void this._addToCurrentCycle(t,r,i);const c=a.get(r);i>c.minSeq&&i<c.maxSeq?this._insertToLastCycle(i,c):this._addToCurrentCycle(t,r,i)}getStatResult(e){const t=this._lastCycleStats.get(e);if(!t||0===t.size)return this._transferCycleDataOptimized(e),null;let s=0,o=0;return t.forEach((e=>{const{sortedSequences:t,minSeq:n,maxSeq:i}=e;t.length>0&&(o+=t.length,s+=i-n+1)})),0===s?null:(this._transferCycleDataOptimized(e),{total_count:s,success_count_business:o,percent_business:kp(o/s*100,2)})}reset(){this._lastCycleStats.clear(),this._currentCycleStats.clear()}dispose(){const{notificationCenter:e,OuterEvent:{MESSAGE_RECEIVED:t}}=this._core;e.unSubscribeOuterEvent(t,this._onMessageReceived,this),this.reset()}_initStatsMap(){Object.values(Zp).forEach((e=>{this._lastCycleStats.set(e,new Map),this._currentCycleStats.set(e,new Map)}))}_onMessageReceived(e){const{data:t=[]}=e;t.forEach((e=>{this.addMessageSequence(e)}))}_transferCycleDataOptimized(e){const t=this._currentCycleStats.get(e);if(!t)return;const s=new Map;t.forEach(((e,t)=>{const o=e.dirty?[...e.sortedSequences].sort(((e,t)=>e-t)):e.sortedSequences;s.set(t,{sortedSequences:o,minSeq:e.minSeq,maxSeq:e.maxSeq,dirty:!1})})),this._lastCycleStats.set(e,s),this._currentCycleStats.set(e,new Map)}_getReceivedMessageSpecifiedKey(e){const{OuterConstant:{CONV_GROUP:t,GRP_AVCHATROOM:s}}=this._core;if(e.conversationType===t&&!0!==(null==e?void 0:e._onlineOnlyFlag)){const{groupStore:t}=this._core.appStore,o=t.getGroup(e.to);if(!o)return null;const{type:n}=o;return n===s?Jp:Yp}}_insertToLastCycle(e,t){t.dirty&&(t.sortedSequences.sort(((e,t)=>e-t)),t.dirty=!1);const s=this._findInsertPos(t.sortedSequences,e);t.sortedSequences.splice(s,0,e),t.minSeq=Math.min(t.minSeq,e),t.maxSeq=Math.max(t.maxSeq,e)}_findInsertPos(e,t){let s=0,o=e.length-1;for(;s<=o;){const n=Math.floor((s+o)/2);if(e[n]===t)return n;e[n]<t?s=n+1:o=n-1}return s}_addToCurrentCycle(e,t,s){let o=this._currentCycleStats.get(e).get(t);o?(o.sortedSequences.push(s),o.minSeq=Math.min(o.minSeq,s),o.maxSeq=Math.max(o.maxSeq,s),o.dirty=!0):(o={sortedSequences:[s],minSeq:s,maxSeq:s,dirty:!1},this._currentCycleStats.get(e).set(t,o))}};var ih=new class{constructor(){this._totalDelay=0,this._totalCount=0,this._countLessThan1s=0,this._countLessThan3s=0}init(e){this._core=e;const{OuterEvent:{MESSAGE_RECEIVED:t},notificationCenter:s}=e;s.subscribeOuterEvent(t,this._onMessageReceived,this)}addMessageDelay(e){const{timeManager:t}=this._core.common,s=t.getServerTimeSeconds()-e;s>0&&(this._totalDelay+=s,this._totalCount++,s<=1?this._countLessThan1s++:s<=3&&this._countLessThan3s++)}getStatResult(){if(0===this._totalCount)return null;const e={total_count:this._totalCount,success_count_business:this._countLessThan1s,success_count_platform:this._countLessThan3s,percent_business:this._calculatePercentage(this._countLessThan1s,this._totalCount),percent_platform:this._calculatePercentage(this._countLessThan3s,this._totalCount),average_value:this._calculateAverageDelay(this._totalCount)};return this.reset(),e}reset(){this._totalDelay=0,this._totalCount=0,this._countLessThan1s=0,this._countLessThan3s=0}dispose(){const{notificationCenter:e,OuterEvent:{MESSAGE_RECEIVED:t}}=this._core;e.unSubscribeOuterEvent(t,this._onMessageReceived,this),this.reset()}_onMessageReceived(e){const{data:t=[]}=e,{OuterConstant:{MSG_GRP_TIP:s,MSG_GRP_SYS_NOTICE:o}}=this._core,n=[s,o];t.forEach((e=>{!n.includes(e.type)&&e.clientTime>0&&this.addMessageDelay(e.clientTime)}))}_calculateAverageDelay(e){return 0===e?0:kp(this._totalDelay/e,1)}_calculatePercentage(e,t){return kp(e/t*100,2)}};var rh=new class{init(e){this.core=e}};var ah=new class{constructor(){this.name="MessageQualityStat",this._reportIndex=0,this._wholePeriod=!1,this._pendingReports=[],this._failedLogsCache=new Map}install(e){this._core=e;const{helper:t,notificationCenter:s,InnerEvent:{QUALITY_STAT:o,LOGOUT:n,DESTROY:i},constants:{WORKFLOW_NAME:r,WORKFLOW_STEP:a}}=e;rh.init(e),oh.init(e),nh.init(e),ih.init(e),t.registerWorkflowStep(r.SYNC_SERVER_INFO_AFTER_LOGIN,a.QUALITY_REPORT,this.handleLoginSuccess,this),s.subscribeInnerEvent(o,this._handleQualityStat,this),s.subscribeInnerEvent(n,this._reset,this),s.subscribeInnerEvent(i,this._dispose,this)}handleLoginSuccess(){console.log(`${Fp}.handleLoginSuccess`);const{store:e,helper:t,utils:{isUndefined:s}}=this._core,o=e.get("cloudConfig")||{},{q_rpt_interval:n}=o,i=s(n)?12e4:Number(n);t.taskScheduler.addTask({id:sh,intervalMs:i,callback:this.report,context:this})}report(){this._wholePeriod=!0;const e=[...eh.map((e=>{const t=this._buildQualityReportItem(e);return t?Object.assign(Object.assign({},t),{report_index:this._reportIndex,whole_period:this._wholePeriod}):null})).filter(Boolean),...this._pendingReports];this._pendingReports=[],this._needSkipReport()||this._uploadQualityReports(e)}_handleQualityStat(e){const{constants:{QUALITY_METRICS:t}}=this._core,{label:s,data:o}=e;s===t.MESSAGE_SEND_SUCCESS_RATE&&oh.dispatchSendStats(o)}_needSkipReport(){return this._isSDKAppIDInBlacklist()&&!this._isTinyIDInWhitelist()}_isSDKAppIDInBlacklist(){const{store:e,utils:t}=this._core,s=e.get("cloudConfig")||{},o=e.get("instance")||{},{sdkAppId:n}=o,{q_rpt_sdkappid_bl:i=[]}=s;if(t.isEmpty(i))return;return i.split(",").map((e=>Number(e))).includes(n)}_isTinyIDInWhitelist(){const{store:e,utils:t}=this._core,s=e.get("cloudConfig")||{},o=e.get("login")||{},n=Number(o.tinyID),{q_rpt_tinyid_wl:i=[]}=s;if(!t.isEmpty(i))return i.split(",").includes(n)}_buildQualityReportItem(e){const t=this._getStatResultByKey(e);if(null===t)return null;const s={quality_type:Qp[e],timestamp:Date.now(),network_type:qp.ONLINE,extension:""};return Object.assign(Object.assign({},s),t)}_getStatResultByKey(e){switch(e){case Vp:return ih.getStatResult();case Bp:case jp:case Kp:case Hp:case Wp:return oh.getStatResult(e);case Yp:case zp:case Jp:return nh.getStatResult(e);default:return null}}_uploadQualityReports(e){return h(this,void 0,void 0,(function*(){try{const t={header:this._core.common.getCommonHead(),quality:e};yield function(e){const{common:t,channel:s}=rh.core,o="imopenstat.tim_web_report_v2",n=t.generateSSOLogProtocolData({servcmd:o,data:e}),i=`${n.head.seq}${o}`;s.sendPacket(n,{requestId:i})}(t),this._reportIndex++,this._wholePeriod=!1}catch(t){console.warn("doReport failed. error:",t),this._pendingReports=this._pendingReports.concat(e),this._cacheFailedLogs()}}))}_cacheFailedLogs(){const e=this._pendingReports,t=`${Fp}._cacheFailedLogs`;let s=[...this._failedLogsCache.get($p)||[],...e];s.length>10&&(s=s.slice(s.length-10),console.log(`${t} logs overflow, keeping last 10 items`)),this._failedLogsCache.set($p,s),console.log(`${t} count: ${s.length}`),this._pendingReports=[]}_reset(){const{helper:e}=this._core;e.taskScheduler.removeTask(sh)}_dispose(){const{notificationCenter:e,InnerEvent:{QUALITY_STAT:t,LOGOUT:s,DESTROY:o}}=this._core;e.unSubscribeInnerEvent(t,this._handleQualityStat,this),e.unSubscribeInnerEvent(s,this._reset,this),e.unSubscribeInnerEvent(o,this._dispose,this),this._reset(),ih.dispose(),nh.dispose()}};const ch=1,uh=300;var lh=new class{constructor(){this.name="OfflineMessageSynchronizer",this._lastMessageSequenceMapOnDisconnect=new Map}install(e){this._core=e;const{common:{workflowManager:t},constants:{WORKFLOW_NAME:s,WORKFLOW_STEP:o,InnerEvent:n}}=e;t.registerWorkflowStep(s.SYNC_SERVER_INFO_AFTER_RE_ONLINE,o.HISTORY_MESSAGE_RECOVER,this._syncOfflineMessage,this),e.notificationCenter.subscribeInnerEvent(n.SOCKET_DISCONNECTED,this._updateLastMessageSequenceMapOnDisconnect,this)}_syncOfflineMessage(e){const{conversationList:t}=(null==e?void 0:e.result)||{},{OuterConstant:s,utils:{isArray:o}}=this._core;if(o(t)){const e=t.filter((e=>e.type===s.CONV_GROUP&&e.groupProfile.type!==s.GRP_AVCHATROOM));return this._recoverGroupHistoryMessage(e)}}_recoverGroupHistoryMessage(e){return h(this,void 0,void 0,(function*(){const{OuterConstant:t}=this._core,s=[],o=[];return yield Promise.all(null==e?void 0:e.map((e=>h(this,void 0,void 0,(function*(){const{groupProfile:{groupID:n}={},lastMessage:{lastSequence:i}={}}=e,r=`${t.CONV_GROUP}${n}`;let a=this._getLocalLastMessageSequence(r);this._shouldRecoverHistory({localLastMessageSequence:a,serverLastMessageSequence:i})&&(yield this._recoverHistoryForConversation({conversationID:r,localLastMessageSequence:a,serverLastMessageSequence:i,groupTipList:o})),s.push(r.replace(t.CONV_GROUP,""))}))))),{recoverRevokeNoticeGroupIDList:s,groupTipList:o}}))}_recoverHistoryForConversation(e){return h(this,arguments,void 0,(function*({conversationID:e,localLastMessageSequence:t,serverLastMessageSequence:s,groupTipList:o}){try{const{utils:{isArray:n,isObject:i,isEmpty:r},OuterEvent:a,OuterConstant:c,notificationCenter:u,message:l,appStore:d,common:{getMessagePreviewText:p}}=this._core,h=s-t,g=Math.min(20,h),_={},m=yield l.messageHistory.getGroupRoamingMessagesByAnchor({conversationID:e,sequence:t+g,direction:c.Direction.FORWARD,count:g}),{nextReqMessageIDFromServer:v,hasNoMoreHistoryMessage:f,messageList:I,serverGroupTipList:S}=m;n(S)&&o.push(...S);const E=f&&v<0,C=[];if(n(I)&&(I.forEach((e=>{l.messageReceiver.groupMessageReceiver.updateMessageProfile(e),e.from===c.CONV_SYSTEM&&(e.isSystemMessage=!1);l.messageDataHandler.storeConversationMessage(e)&&!r(e.payload)&&(C.push(e),e._isExcludedFromLastMessage||(_.lastMessage=Object.assign({},e)))})),C.length>0&&u.emitOuterEvent(a.MESSAGE_RECEIVED,{name:a.MESSAGE_RECEIVED,data:C})),!E&&I.length>0){const t=I[I.length-1].sequence;yield this._recoverHistoryForConversation({conversationID:e,localLastMessageSequence:t,serverLastMessageSequence:s,groupTipList:o})}i(_.lastMessage)&&(_.lastMessage.messageForShow=p(_.lastMessage.type,_.lastMessage.payload),d.conversationStore.updateConversation(e,_))}catch(t){console.debug("Recovery failed for conversation:",e,t)}}))}_updateLastMessageSequenceMapOnDisconnect(){const{message:e}=this._core,t=e.messageDataHandler.getContinuousMessagesByConversation();for(const[e,s]of t){if(e.startsWith("C2C"))continue;const t=Array.from(s.values());if((null==t?void 0:t.length)>0){const s=t[t.length-1].sequence;this._lastMessageSequenceMapOnDisconnect.set(e,s)}}}_getLocalLastMessageSequence(e){const{message:t}=this._core;if(this._lastMessageSequenceMapOnDisconnect.has(e))return this._lastMessageSequenceMapOnDisconnect.get(e);const s=t.messageDataHandler.getLocalMessageList(e),o=s[s.length-1];return null==o?void 0:o.sequence}_shouldRecoverHistory(e){const{localLastMessageSequence:t,serverLastMessageSequence:s}=e;if("number"!=typeof t||"number"!=typeof s)return!1;const o=s-t;return 0!==s&&t>0&&(o>=ch&&o<uh)}};let dh=_s.STANDARD,ph=[];dh=_s.PROFESSIONAL,ph=[Mo,Co,Oo,Uo,$o,ah,lh,Ii,Cr,oa,Cu,tl,yd,gn,jl,id,rp,Up];var hh=Object.freeze({__proto__:null,ChatError:Fs,WorkflowManager:zs,buildAndSendPacket:to,get builtInPlugins(){return ph},checkBusinessCapabilityBits:Ys,deepMerge:ao,getCurrentUserID:io,getErrorMessage:ks,getMessagePreviewText:co,isC2CConv:e=>_(e)&&e.slice(0,3)===rs.CONV_C2C,isCommunity:Qs,isGroupConv:e=>_(e)&&e.slice(0,5)===rs.CONV_GROUP,isTopic:Xs,isUnlimitedAVChatRoom:function(){var e;return!!(null===(e=Vt.store.get("instance"))||void 0===e?void 0:e.unlimitedAVChatRoom)},liteChatInstanceMap:Js,registerInterceptor:Hs,registerValidateConfig:Ws,requireAuth:$s,get sdkEdition(){return dh},updateGroupAtInfo:(e,t)=>{const{CONV_AT_ME:s,CONV_AT_ALL:o,CONV_AT_ALL_AT_ME:n}=hs;if(function(e,t){const{CONV_AT_ME:s,CONV_AT_ALL:o,CONV_AT_ALL_AT_ME:n}=hs,{groupID:i,sequence:r}=e;let a=!1;if(!Qs({groupID:i}))return a;return t.forEach((t=>{t.messageSequence===r&&(t.atTypeArray.includes(s)&&e.groupAtType.includes(o)&&(t.atTypeArray=[n]),t.atTypeArray.includes(o)&&e.groupAtType.includes(s)&&(t.atTypeArray=[n],t.__random=e.__random,t.__sequence=e.__sequence),a=!0)})),a}(e,t))return;let i=[...e.groupAtType];i.includes(s)&&i.includes(o)&&(i=[n]);const r={from:e.from,groupID:e.groupID,topicID:e.topicID,messageSequence:e.sequence,atTypeArray:i,__random:e.__random,__sequence:e.__sequence};t.push(r)},validateAndExecute:Ks,validateParameters:qs});class gh{constructor(){this._builtInPlugins=new Set,this._externalPlugins=new Set}static getInstance(){return gh._instance||(gh._instance=new gh),gh._instance}static setInstance(e){gh._instance=e}installBuiltInPlugin(e){e&&this._installPlugin(e,this._builtInPlugins)}installExternalPlugin(e){e&&this._installPlugin(e,this._externalPlugins)}clear(){this._builtInPlugins=new Set,this._externalPlugins=new Set}_installPlugin(e,t){let s=[];s=v(e)?e:[e];const o=s.findIndex((e=>"AVChatRoom"===(null==e?void 0:e.name))),n=o>-1?s.splice(o,1):[];s.forEach((e=>{this._isPluginInstalled(e.name)||(e&&Bt(e.install)?(t.add(e.name),Bt(e.getInstalledSubPlugins)?e.install(Sh.getInstance().exposeApiForPlugin(),n):e.install(Sh.getInstance().exposeApiForPlugin()),Bt(e.handleLoginSuccess)&&this._isLoggedIn()&&e.handleLoginSuccess()):Bt(e)?(t.add(e.name),e(Sh.getInstance().exposeApiForPlugin()),Bt(e.handleLoginSuccess)&&this._isLoggedIn()&&e.handleLoginSuccess()):console.warn('A plugin must either be a function or an object with an "install" function.'))}))}_isPluginInstalled(e){return this._builtInPlugins.has(e)||this._externalPlugins.has(e)}_isLoggedIn(){var e;return!0===(null===(e=Vt.store.get("login"))||void 0===e?void 0:e.isLoggedIn)}}var _h=new class{constructor(){this._conversationMap=new Map}getConversationMap(){return this._conversationMap}getConversation(e){return this._conversationMap.get(e)}updateConversation(e,t,s={emit:!0,needSort:!1}){const{emit:o,needSort:n}=s,i=this._conversationMap.get(e);i&&!me(t)&&(Object.keys(t).forEach((e=>{i[e]=t[e]})),o&&Vt.notificationCenter.emitInnerEvent(zt.CONVERSATION_UPDATED,{needSort:n}))}deleteConversation(e){this._conversationMap.has(e)&&(this._conversationMap.delete(e),Vt.notificationCenter.emitInnerEvent(zt.CONVERSATION_UPDATED))}};var mh=new class{constructor(){this._groupMap=new Map}getGroupMap(){return this._groupMap}getGroup(e){return this._groupMap.get(e)}updateGroup(e,t){const s=this._groupMap.get(e);s&&!me(t)&&Object.keys(t).forEach((e=>{s[e]=t[e]}))}};var vh=new class{constructor(){this._messagesByConversation=new Map}updateMessage(e,t,s){var o;const{operation:n,updateUnreadCount:i=!0}=s,r=p(s,["operation","updateUnreadCount"]),a=[];for(const s of t){const t=null===(o=this._messagesByConversation.get(e))||void 0===o?void 0:o.get(s);if(!t)return!1;Object.keys(r).forEach((e=>{t[e]=r[e]})),a.push(t)}return this._emitMessageStoreOperationEvent(n,{conversationID:e,messageList:a,updateUnreadCount:i}),a}getMessagesByConversation(e){var t;return[...(null===(t=this._messagesByConversation.get(e))||void 0===t?void 0:t.values())||[]]}getMessages(){return this._messagesByConversation}_emitMessageStoreOperationEvent(e,t){const{conversationID:s}=t;Xs(s)?Vt.notificationCenter.emitInnerEvent(os[e],t):Vt.notificationCenter.emitInnerEvent(e,t)}};var fh=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)}},Ih=Object.freeze({__proto__:null,conversationStore:_h,groupStore:mh,messageStore:vh,userStore:fh});class Sh{static getInstance(){return Sh._instance||(Sh._instance=new Sh),Sh._instance}static setInstance(e){Sh._instance=e}constructor(){this._experimentalApiMap={statTUIKeyFeatures:this.statKeyFeatureUsage.bind(this)},this._apiHandlersMap={},this._apiMap={on:Vt.notificationCenter.subscribeOuterEvent.bind(Vt.notificationCenter),off:Vt.notificationCenter.unSubscribeOuterEvent.bind(Vt.notificationCenter),destroy:this.destroy.bind(this),callExperimentalAPI:this.callExperimentalAPI.bind(this),use:gh.getInstance().installExternalPlugin.bind(gh.getInstance()),registerPlugin:this.registerPlugin.bind(this),setLogLevel:this.setLogLevel.bind(this)}}registerPlugin(e){console.log("registerPlugin",e)}statKeyFeatureUsage(e){console.log("statTUIKeyFeatures",e)}setLogLevel(e){console.log("setLogLevel",e),Vt&&"function"==typeof Vt.setLogLevel&&(null==Vt||Vt.setLogLevel(e))}getApiMap(){return this._apiMap}setApiMap(e){this._apiMap=e}registerApi(e){const{apiName:t,context:s,methodName:o=t,matcher:n}=e;this._apiHandlersMap[t]||(this._apiHandlersMap[t]=[]),this._apiHandlersMap[t].push({context:s,methodName:o,matcher:n}),this._apiMap[t]&&1!==this._apiHandlersMap[t].length||(this._apiMap[t]=(...e)=>{Ks(o,e);const s=this._apiHandlersMap[t];for(const t of s)if(!t.matcher||t.matcher(e))return t.context[t.methodName].bind(t.context)(...e)})}registerExperimentalAPI(e,t,s){const o=s||e;this._experimentalApiMap[e]=t[o].bind(t)}destroy(){return h(this,void 0,void 0,(function*(){var e,t;try{(null===(e=Vt.store.get("login"))||void 0===e?void 0:e.isLogin)&&(yield this._apiMap.logout()),Vt.notificationCenter.emitInnerEvent(zt.DESTROY)}catch(e){console.debug("destroy error: ",e)}finally{Vt.notificationCenter.emitOuterEvent(Wt.SDK_DESTROY,{SDKAppID:null===(t=Vt.store.get("instance"))||void 0===t?void 0:t.sdkAppId}),Js.clear(),gh.getInstance().clear(),zs.getInstance().destroy(),Vt.destroy()}}))}exposeApiForClient(){return this._apiMap}exposeApiForPlugin(){return Object.assign(Object.assign({InnerEvent:zt,InnerEventSubType:Vt.notificationCenter.InnerEventSubType,OuterEvent:Wt,OuterConstant:hs,SignalingEvent:Jt,helper:Object.assign(Object.assign(Object.assign({},Vt.utils),Vt.common),{registerApi:this.registerApi.bind(this),registerExperimentalAPI:this.registerExperimentalAPI.bind(this),registerInterceptor:Hs,registerValidateConfig:Ws,checkBusinessCapabilityBits:Ys,registerWorkflowStep:zs.getInstance().registerWorkflowStep.bind(zs.getInstance()),ChatError:Fs}),apiMap:this._apiMap},Vt),{constants:Object.assign(Object.assign({},Es),Vt.constants),common:Object.assign(Object.assign(Object.assign({},hh),Vt.common),{workflowManager:zs.getInstance()}),utils:Vt.utils,appStore:Ih})}callExperimentalAPI(e,t){return this._experimentalApiMap[e]?this._experimentalApiMap[e](t):Promise.reject(new Fs({code:gs.INVALID_OPERATION}))}}class Eh{constructor(){this._latestLoginAt=0,this._latestSendOnlinePresenceRequestTime=0,this._helloInterval=120}init(){const{notificationCenter:e,store:t}=Vt;t.set("login",{isReady:!1}),Sh.getInstance().registerApi({apiName:"login",context:this}),Sh.getInstance().registerApi({apiName:"logout",context:this}),Sh.getInstance().registerApi({apiName:"getLoginUser",context:this}),Sh.getInstance().registerApi({apiName:"isReady",context:this}),e.subscribeInnerEvent(zt.RECONNECTED,this._reLogin,this),Vt.notificationCenter.subscribeInnerEvent(zt.DESTROY,this._dispose,this)}login(e){return h(this,void 0,void 0,(function*(){const t=this._getUiPlatform(),{sdkEdition:s}=Vt.store.get("instance")||{},o=Vt.ssoLog.createSSOLogData({method:"login",eventType:4,uiPlatform:t,message:s});try{if(this._isLoginIn())return this._createRepeatLoginResponse();if(this._isLoginFrequencyExceeded())throw new Fs({functionName:"login",code:gs.REPEAT_LOGIN});const t=yield this._performLogin(e);return this._validateAfterLogin(t),this._handleLoginSuccess(t),yield this._ensureAsyncComplete(),this._updateAndEmitSDKReady(),this._latestLoginAt=0,{code:0,data:t}}catch(e){const{errorCode:t}=e;t!==gs.REPEAT_LOGIN&&(this._latestLoginAt=0);const s=new Fs({functionName:"login",code:t});throw o.setError(s).end(!0),s}}))}_getUiPlatform(){var e;const{store:t}=Vt,s=null===(e=t.get("instance"))||void 0===e?void 0:e.scene;if("string"==typeof s){const e=Number(s);return isNaN(e)?void 0:e}}_reLogin(){return h(this,void 0,void 0,(function*(){var e;try{if(!this._isLoginIn())return;const t=Vt.ssoLog.createSSOLogData({method:"reLogin"}),s=yield Us();if(s){const{instanceID:o,customStatus:n}=s;Vt.store.set("login",{statusInstanceId:o}),zs.getInstance().executeWorkflow(ms.SYNC_SERVER_INFO_AFTER_RE_ONLINE,{customStatus:n,statusType:ns.USER_STATUS_ONLINE});const i=`socketId:${null===(e=Vt.channel.getSocketAdapter())||void 0===e?void 0:e.getId()} instanceId:${o}`;t.setLogInfo({message:i}).end(!0)}}catch(e){console.warn(e)}}))}logout(){return h(this,arguments,void 0,(function*(e=Cs.USER_INITIATED){const t=Vt.ssoLog.createSSOLogData({method:"logout"});t.setLogInfo({moreMessage:`identifier:${io()}`});try{yield this._performLogout(e),t.end(!0),Vt.ssoLog.uploadSSOLogData()}catch(e){const{errorCode:t}=e,s=new Fs({functionName:"logout",code:t});this._handleLogoutError(s)}finally{this._handleLogoutCompleted()}return{code:0,data:{}}}))}getLoginUser(){return this._isLoginIn()?io():""}isReady(){var e;return null===(e=Vt.store.get("login"))||void 0===e?void 0:e.isReady}_updateAndEmitSDKReady(){Vt.store.set("login",{isReady:!0}),setTimeout((()=>{Vt.notificationCenter.emitOuterEvent(Wt.SDK_READY,{name:Wt.SDK_READY})}),1)}_updateAndEmitSDKNotReady(){Vt.store.set("login",{isReady:!1}),Vt.notificationCenter.emitOuterEvent(Wt.SDK_NOT_READY,{name:Wt.SDK_NOT_READY})}_validateAfterLogin(e){var t,s;const o="login";if(!e)throw new Fs({functionName:o,message:"login response is empty"});const{tinyID:n,a2Key:i}=e||{},r=Vt.ssoLog.getSSOLogData(o);if(!n){const e=new Fs({functionName:o,code:gs.NO_TINYID});throw null===(t=null==r?void 0:r.setError)||void 0===t||t.call(r,e).end(),e}if(!i){const e=new Fs({functionName:o,code:gs.NO_A2KEY});throw null===(s=null==r?void 0:r.setError)||void 0===s||s.call(r,e).end(),e}}_createRepeatLoginResponse(){var e;return{code:0,data:{actionStatus:"OK",errorCode:0,errorInfo:ks({code:"RepeatLogin",replacement1:null===(e=Vt.store.get("login"))||void 0===e?void 0:e.userId}),repeatLogin:!0}}}_performLogin(e){return h(this,void 0,void 0,(function*(){const{userID:t,userSig:s}=e;return Vt.store.set("login",{userId:t,userSig:s}),this._latestLoginAt=Date.now(),Us()}))}_ensureAsyncComplete(){return h(this,void 0,void 0,(function*(){yield new Promise((e=>{setTimeout((()=>e(null)),1)}))}))}_handleLoginSuccess(e){const{timeManager:t}=Vt.common,{helloInterval:s,timeStamp:o,customStatus:n,purchaseBits:i}=e,r=1e3*o;t.calculateTimeOffsetWithServer(this._latestLoginAt,r),this._helloInterval=s||120,this._updateLoginStore(e),Vt.user.userStatus.setCustomStatus(n),zs.getInstance().executeWorkflow(ms.SYNC_SERVER_INFO_AFTER_LOGIN,{purchaseBits:i}),Vt.common.taskScheduler.addTask({id:As,intervalMs:1e3*this._helloInterval,callback:this._sendOnlinePresenceRequest,context:this}),this._logLoginSuccess(e)}_performLogout(e){return function(e){return h(this,void 0,void 0,(function*(){const{logoutReason:t}=e,s="im_open_status.wslogout",o=Vt.common.generateProtocolData({servcmd:s,data:{wslogout_type:t,isWebUniapp:0}}),n=`${o.head.seq}${s}`;return yield Vt.channel.sendPacket(o,{requestId:n})}))}({logoutReason:e})}_handleLogoutError(e){Vt.ssoLog.getSSOLogData("logout").setError(e).end(),console.error(`logout ${e}`)}_handleLogoutCompleted(){this._updateAndEmitSDKNotReady(),this._reset(),zs.getInstance().reset(),Vt.notificationCenter.emitInnerEvent("logout")}_updateLoginStore(e){const{a2Key:t,tinyID:s,instanceID:o,authKey:n}=e;Vt.store.set("login",{a2Key:t,tinyID:s,statusInstanceId:o,authKey:n,isLoggedIn:!0})}_logLoginSuccess(e){var t;const s=Vt.ssoLog.getSSOLogData("login"),{helloInterval:o,instanceID:n,timeStamp:i,customStatus:r}=e,a=null===(t=Vt.channel.getSocketAdapter())||void 0===t?void 0:t.getId(),c=Vt.common.timeManager.getTimeOffsetWithServer(),{appId:u,href:l}=Vt.store.get("instance")||{},d=`login._logLoginSuccess socketID:${a} scene: helloInterval:${o} instanceID:${n}\n timeStamp:${i} offset:${c} customStatus:${r} href: ${l} appId: ${u}`;console.log(`login ok. ${d}`),s.updateLogCreatedAtByTimeOffset(),s.setLogInfo({moreMessage:d}).end()}_sendOnlinePresenceRequest(){return h(this,void 0,void 0,(function*(){this._latestSendOnlinePresenceRequestTime=Date.now();try{yield function(){const e="im_open_status.wshello",t=Vt.common.generateProtocolData({servcmd:e,data:{isWebUniapp:0}}),s=`${t.head.seq}${e}`;return Vt.channel.sendPacket(t,{requestId:s})}()}catch(e){console.warn("Login._sendOnlinePresenceRequest error:",e)}}))}_isLoginIn(){var e;return!0===(null===(e=Vt.store.get("login"))||void 0===e?void 0:e.isLoggedIn)}_isLoginFrequencyExceeded(){return Date.now()-this._latestLoginAt<=15e3}_reset(){console.log("Login reset"),Vt.common.taskScheduler.removeTask(As),this._helloInterval=120,this._latestSendOnlinePresenceRequestTime=0,this._latestLoginAt=0,Vt.store.clear("login"),Vt.store.set("login",{isReady:!1})}_dispose(){console.log("Login dispose"),this._reset();const{notificationCenter:e}=Vt;e.unSubscribeInnerEvent(zt.RECONNECTED,this._reLogin,this),e.unSubscribeInnerEvent(zt.DESTROY,this._dispose,this)}}const Ch={login:{userID:{required:!0,rules:["string"],allowEmpty:!1},userSig:{required:!0,rules:["string"],allowEmpty:!1}}},Mh={logout:!0};class yh{constructor(){this.loginAction=new Eh,this.kickedOutHandler=new Ps,this.loginAction.init(),this.kickedOutHandler.init(),Ws({auth:Mh,params:Ch})}}var Th,Ah,Oh;!function(e){e.CONV_C2C="C2C",e.CONV_GROUP="GROUP",e.CONV_TOPIC="TOPIC",e.CONV_SYSTEM="@TIM#SYSTEM"}(Th||(Th={})),function(e){e.MSG_PRIORITY_HIGH="High",e.MSG_PRIORITY_NORMAL="Normal",e.MSG_PRIORITY_LOW="Low",e.MSG_PRIORITY_LOWEST="Lowest"}(Ah||(Ah={})),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"}(Oh||(Oh={}));const Dh={1:Ah.MSG_PRIORITY_HIGH,2:Ah.MSG_PRIORITY_NORMAL,3:Ah.MSG_PRIORITY_LOW,4:Ah.MSG_PRIORITY_LOWEST},Rh=0,Lh=1;var Nh;!function(e){e.IN="in",e.OUT="out"}(Nh||(Nh={}));const bh=2,Gh={};function wh(e){if(!e)return 0;if(void 0===Gh[e]){const t=new Date,s=`3${t.getHours()}`.slice(-2),o=`0${t.getMinutes()}`.slice(-2),n=`0${t.getSeconds()}`.slice(-2);Gh[e]=parseInt([s,o,n,"0001"].join(""),10),console.log(`autoIncrementIndex start index:${Gh[e]}`)}else Gh[e]+=1;return Gh[e]}class Ph{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=Ah.MSG_PRIORITY_NORMAL,this._relayFlag=!1;const{clientTime:t=Vt.common.timeManager.getServerTimeSeconds()||0,senderTinyID:s,currentUser:o,needReadReceipt:n,isSupportExtension:i,customModerationConfigurationId:r,to:a,from:c,nick:u="",avatar:l="",time:d,messageControlInfo:p,tinyID:h,cloudCustomData:g="",messageLifeTime:_,messageVersion:m=0,conversationType:v,sequence:f,checkResult:I=0,isPlaceMessage:S=0,messageFlagBits:E,receiverList:C,isSystemMessage:M=!1,status:y=Zt.SUCCESS,revokeReason:T="",conversationSubType:A,clientSequence:O,protocol:D="JSON",revokerInfo:R={userID:"",nick:"",avatar:""},readReceiptInfo:L={readCount:void 0,unreadCount:void 0,isPeerRead:void 0,timestamp:0},random:N,groupProfile:b,atUserList:G,flow:w,isRead:P=!1}=e;var U;this.clientTime=t,this.senderTinyID=s||h,this.needReadReceipt=!0===n||1===n,this.isSupportExtension=!0===i||1===i,this._cmConfigID=r,this.to=a,this.nick=u,this.avatar=l,this.protocol=D,this.random=void 0===N?(U=U||99999999,Math.round(Math.random()*U)):N,this.time=d||Math.ceil(Date.now()/1e3),this._isExcludedFromLastMessage=!!(null==p?void 0:p.excludedFromLastMessage),this._isExcludedFromUnreadCount=!!(null==p?void 0:p.excludedFromUnreadCount),this.isModified=!!m,this.cloudCustomData=g,this.messageLifeTime=_,this.from=c||null,this.sequence=f||0,this.conversationType=v||Th.CONV_C2C,this.hasRiskContent=I>1,this.version=m,this.isPlaceMessage=S,this.isRevoked=2===S||8===E,this.isSystemMessage=M,this.readReceiptInfo=L,this.revokeReason=T,this.revokerInfo=R,this._receiverList=C,this.conversationSubType=A,this.revoker=(null==R?void 0:R.revoker)||"",this.clientSequence=O||f||0,this.status=y,this.atUserList=G||[],this.flow=w,this.isRead=P,this.reInitialize(o),this._initC2CReadReceiptInfo(e),this._extractGroupInfo(b)}getElements(){return this._elements}isOnlineMessage(){return 0===this.messageLifeTime}setElement(e){Array.isArray(e)?this._elements=e:this._elements=[e],this._updatePayloadAndType()}transformElementsToServerFormat(){return this._elements?Array.isArray(this._elements)?this._elements.map((e=>e.transformToServerFormat())):this._elements.transformToServerFormat():null}setRelayFlag(e){this._relayFlag=e}validateBeforeSend(){var e,t,s;return this._relayFlag?{isValid:!0}:(null===(e=this._elements)||void 0===e?void 0:e.length)>0?null===(s=null===(t=this._elements[0])||void 0===t?void 0:t.validateBeforeSend)||void 0===s?void 0:s.call(t):{isValid:!1}}_updatePayloadAndType(){this._elements[0]&&(this.payload=this._elements[0].content,this.type=this._elements[0].type)}_initC2CReadReceiptInfo(e){const{readReceiptSentByPeer:t,timestamp:s=0}=e;this.conversationType===Th.CONV_C2C&&!0===this.needReadReceipt&&(this.readReceiptInfo.isPeerRead=1===t,this.readReceiptInfo.timestamp=s)}_extractGroupInfo(e){if(!e)return;const{From_AccountNick:t,From_AccountHeadurl:s,MsgFrom_AccountExtraInfo:o}=e,{NameCard:n}=o||{};"string"==typeof t&&(this.nick=t),"string"==typeof s&&(this.avatar=s),"string"==typeof n&&(this.nameCard=n)}reInitialize(e){e===this.from&&(this.isRead=!0),this._initSequence(e),this._concatConversationID(e),this.generateMessageID()}_concatConversationID(e){let t="";const s=this.conversationType;s!==Th.CONV_SYSTEM?(t=s===Th.CONV_C2C?e===this.from?this.to:this.from:this.to,this.conversationID=t?`${s}${t}`:null):this.conversationID=Th.CONV_SYSTEM}_initSequence(e){0===this.clientSequence&&e&&(this.clientSequence=wh(e)),0===this.sequence&&this.conversationType===Th.CONV_C2C&&(this.sequence=this.clientSequence)}generateMessageID(){this.from===Th.CONV_SYSTEM&&(this.senderTinyID="144115198244471703"),this.ID=`${this.senderTinyID}-${this.clientTime}-${this.random}`}setIsRead(e){this.isRead=e}}class Uh{static parseServerPushElement(e){const{MsgContent:t={}}=e,{Data:s,Ext:o,Desc:n}=t;return new Uh({data:s,description:n,extension:o})}constructor(e){this.type=Oh.MSG_CUSTOM;const{data:t="",description:s="",extension:o=""}=e;this.content={data:t,description:s,extension:o}}transformToServerFormat(e){const{isMergerMessage:t=!1}=e||{},s=t?this.payload:this.content,{data:o,description:n,extension:i}=s;return{MsgType:this.type,MsgContent:{Data:o,Ext:i,Desc:n}}}validateBeforeSend(){const{isEmpty:e}=Vt.utils,t=[this.content.data,this.content.description,this.content.extension].some((t=>!e(t)));return{isValid:t,error:t?null:{message:"content can not be empty"}}}}class kh{static parseServerPushElement(e){const{MsgContent:t={Text:""}}=e,{Text:s}=t;return new kh({text:s})}constructor(e){this.type=Xt.MSG_TEXT,this.content={text:e.text||""}}validateBeforeSend(){var e,t;return(null===(t=null===(e=this.content)||void 0===e?void 0:e.text)||void 0===t?void 0:t.length)>0?{isValid:!0}:{isValid:!1,error:{message:"content can not be empty"}}}transformToServerFormat(e){const{isMergerMessage:t=!1}=e||{},s=t?this.payload:this.content,{text:o}=s;return{MsgType:this.type,MsgContent:{Text:o}}}}var Fh=new class{constructor(){this._elementClassMap={[Oh.MSG_CUSTOM]:Uh,[Oh.MSG_TEXT]:kh}}init(){Sh.getInstance().registerApi({apiName:"createCustomMessage",context:this}),Sh.getInstance().registerApi({apiName:"createTextMessage",context:this})}registerElementClass(e,t){var s;void 0!==(s=t).prototype&&"constructor"in s.prototype&&(this._elementClassMap[e]=t)}getElementClass(e){return this._elementClassMap[e]}createMessage(e){const{from:t,flow:s=Nh.OUT}=e,{userId:o}=Vt.store.get("login")||{};this._isSendByCurrentInstance({from:t,flow:s,currentUser:o})?this._updateWithSenderInfo(e):this._isMultiEndpointSyncMessage({from:t,flow:s,currentUser:o})&&(e.flow=Nh.OUT);const n=Object.assign(Object.assign({},e),{currentUser:o});return new Ph(n)}createCustomMessage(e){const t=io(),s=this.createMessage(Object.assign(Object.assign({},e),{from:t})),o=this._elementClassMap[Oh.MSG_CUSTOM];if(!s)return null;if(o){const t=new o(e.payload);s.setElement(t)}return s}createTextMessage(e){var t;if(!e)return null;const s="string"==typeof e.payload?e.payload:(null===(t=null==e?void 0:e.payload)||void 0===t?void 0:t.text)||"",o=new kh({text:s}),n=io(),i=Vt.message.messageFactory.createMessage(Object.assign(Object.assign({},e),{from:n}));return i.setElement(o),i}_updateWithSenderInfo(e){const{nick:t,avatar:s}=e,{userId:o,tinyID:n}=Vt.store.get("login")||{},i=fh.getUserProfile(o);return e.nick=t||(null==i?void 0:i.nick)||"",e.avatar=s||(null==i?void 0:i.avatar)||"",e.tinyID=e.tinyID||n||"",e.from=o,e.status=Zt.UNSENT,e.flow=Nh.OUT,e}_isMultiEndpointSyncMessage(e){const{from:t,flow:s,currentUser:o}=e;return t===o&&s===Nh.IN}_isSendByCurrentInstance(e){const{from:t,flow:s,currentUser:o}=e;return t===o&&s===Nh.OUT}};const $h={PushFlag:0,Title:"",Desc:"",Ext:"",ApnsInfo:{Sound:"",BadgeMode:0,IsVoipPush:void 0,Image:"",InterruptionLevel:"active",ContentAvailable:0},AndroidInfo:{Sound:"",XiaoMiChannelID:"",OPPOChannelID:"",GoogleChannelID:"",VIVOClassification:1,VIVOCategory:"",HuaWeiCategory:"",OPPOCategory:"",HuaWeiImage:"",HonorImage:"",GoogleImage:"",HonorImportance:"",MeizuNotifyType:void 0}},qh={HonorImportance:{range:["LOW","NORMAL"],defaultValue:void 0},MeizuNotifyType:{range:[0,1],defaultValue:void 0}},xh={enableIOSBackgroundNotification:{range:[!0,!1],defaultValue:!1},interruptionLevel:{range:["passive","active","time-sensitive","critical"],defaultValue:"active"}};function Vh(e,t){return Object.keys(t).forEach((s=>{const{range:o,defaultValue:n}=t[s];e[s]=o.includes(e[s])?e[s]:n})),e}function Bh(e){const t=e.lastIndexOf(".");return-1===t?e:e.slice(0,t)}function jh(e){const{androidInfo:t={},androidOPPOChannelID:s=""}=e,o=t.OPPOChannelID||s,n=Vh(t,qh),{sound:i="",FCMChannelID:r=""}=n,a=p(n,["sound","FCMChannelID"]);return Object.assign(Object.assign({},a),{Sound:Bh(i),OPPOChannelID:o,GoogleChannelID:r})}function Kh(e){const{apnsInfo:t={},ignoreIOSBadge:s=!1,disableVoipPush:o}=e,n=Vh(t,xh),{ignoreIOSBadge:i,disableVoipPush:r,enableIOSBackgroundNotification:a}=n,c=p(n,["ignoreIOSBadge","disableVoipPush","enableIOSBackgroundNotification"]),u=!0===i||!0===s?1:0;let l;return g(o)||(l=!1===o?1:0),g(r)||(l=!1===r?1:0),Object.assign(Object.assign({},c),{BadgeMode:u,IsVoipPush:l,ContentAvailable:a?1:0})}function Hh(e){return Vt.utils.isPlainObject(e)?{PushFlag:!0===e.disablePush?1:0,Title:e.title||"",Desc:e.description||"",Ext:e.extension||"",ApnsInfo:Kh(e),AndroidInfo:jh(e)}:$h}function Wh(e){const{From_AccountHeadurl:t,From_AccountNick:s,IsNeedReadReceipt:o,IsPeerRead:n,IsSyncMsg:i,MsgBody:r,MsgClientTime:a,MsgLifeTime:c,MsgRandom:u,MsgSeq:l,MsgTimeStamp:d,SendMsgControl:p,SupportMessageExtension:h,TinyId:g,MsgCheckResult:_,CloudCustomData:m,MsgVersion:v,MsgFlagBits:f,RevokerInfo:I}=e;let S,{From_Account:E,To_Account:C}=e;if(1===i){const e=C;C=E,E=e}if(I){const{Reason:e,Revoker_Account:t,Revoker_FromUin:s}=I;S={reason:e,revoker:t,revokerFromUin:s,userID:t}}return{from:E,avatar:t,nick:s,needReadReceipt:1===o,isSyncMessage:i,clientTime:a,messageLifeTime:c,random:u,sequence:l,time:d,messageControlInfo:{excludedFromLastMessage:1===(null==p?void 0:p.NoLastMsg),excludedFromUnreadCount:1===(null==p?void 0:p.NoUnread)},isSupportExtension:h,to:C,tinyID:g,checkResult:_,cloudCustomData:m,revokerInfo:S,messageVersion:v,messageFlagBits:f,readReceiptSentByPeer:n,elements:Qh(r)}}function Yh(e){const{From_Account:t,MsgBody:s,MsgClientTime:o,MsgRandom:n,MsgSeq:i,MsgTimeStamp:r,To_Account:a,MsgVersion:c,CloudCustomData:u}=e;return{from:t,clientTime:o,random:n,sequence:i,time:r,to:a,elements:Qh(s),messageVersion:c,cloudCustomData:u}}function zh(e){const{ClientSeq:t,From_Account:s,GroupInfo:o,MsgBody:n,MsgClientTime:i,MsgRandom:r,MsgSeq:a,MsgTimeStamp:c,SendMsgControl:u,SupportMessageExtension:l,TinyId:d,CloudCustomData:p,MsgVersion:h,MsgCheckResult:g,NeedReadReceipt:_,IsPlaceMsg:m,RevokerInfo:v,GroupAtInfo:f}=e;let I,S=Ah.MSG_PRIORITY_NORMAL;if(Object.keys(Dh).includes(String(e.MsgPriority))&&(S=Dh[e.MsgPriority]),v){const{Reason:e,Revoker_Account:t,Revoker_FromUin:s}=v;I={reason:e,revoker:t,revokerFromUin:s,userID:t}}const E=function(e){const t=[];Array.isArray(e)&&e.forEach((e=>{e.GroupAtAllFlag===Rh?t.push(e.GroupAt_Account):e.GroupAtAllFlag===Lh&&t.push(hs.MSG_AT_ALL)}));return t}(f);return{clientSequence:t,from:s,groupProfile:o,clientTime:i,priority:S,random:r,sequence:a,time:c,messageControlInfo:{excludedFromLastMessage:1===(null==u?void 0:u.NoLastMsg),excludedFromUnreadCount:1===(null==u?void 0:u.NoUnread)},isSupportExtension:l,tinyID:d,cloudCustomData:p,messageVersion:h,messageCheckResult:g,needReadReceipt:_,isPlaceMessage:m,revokerInfo:I,atUserList:E,elements:Qh(n),to:Jh(e)}}function Jh(e){const{utils:{isEmpty:t},constants:{IS_TOPIC_MESSAGE:s}}=Vt,{ToGroupId:o,GroupInfo:{MillionGroupFlag:n=0,TopicId:i}={}}=e;return n!==s||t(i)?o:i}function Qh(e){if(!e)return null;if(Array.isArray(e))return e.map((e=>{const t=Vt.message.messageFactory.getElementClass(e.MsgType);return null==t?void 0:t.parseServerPushElement(e)}));const t=Vt.message.messageFactory.getElementClass(e.MsgType);return null==t?void 0:t.parseServerPushElement(e)}function Xh(e){const{From_Account:t,MsgBody:s,MsgClientTime:o,MsgRandom:n,MsgSeq:i,MsgTimeStamp:r,GroupId:a,TopicId:c,MsgVersion:u,CloudCustomData:l}=e;return{from:t,clientTime:o,random:n,sequence:i,time:r,groupID:a,topicID:c,elements:Qh(s),messageVersion:u,cloudCustomData:l}}function Zh({conversationUpdateFields:e,message:t}){const{conversationID:s,conversationType:o,conversationSubType:n,flow:i,_isExcludedFromUnreadCount:r,_isExcludedFromLastMessage:a}=t,c=a?"":t,u=!r&&i===Nh.IN;e.has(s)?(e.get(s).lastMessage=c,u&&e.get(s).unreadCount++):e.set(s,{conversationID:s,type:o,subType:n,unreadCount:u?1:0,lastMessage:c})}function eg(e){return e.filter((e=>{const t=!me(null==e?void 0:e.getElements()),s=1===(null==e?void 0:e.isPlaceMessage);if(!t){Vt.ssoLog.createSSOLogData({method:"emptyMessageBody"}).setLogInfo({message:`from:${e.from} to:${e.to} sequence:${e.sequence}`}).end()}return t&&!s}))}var tg=Object.freeze({__proto__:null,autoIncrementIndex:wh,filterValidMessages:eg,parseServerGroupMessage:zh,parseServerPushC2CModifyMessage:Yh,parseServerPushGroupModifyMessage:Xh,parseServerPushMessage:Wh,parseServerPushMessageElement:Qh,updateConversationFields:Zh});const{isPlainObject:sg}=Vt.utils;function og(e,t={}){const{onlineUserOnly:s,messageControlInfo:o}=t;let{offlinePushInfo:n}=t;e.conversationType===Th.CONV_C2C&&!0===s&&(n?n.disablePush=!0:n={disablePush:!0});let i="";"string"==typeof e.cloudCustomData&&e.cloudCustomData.length>0&&(i=e.cloudCustomData);const r=[];if(o&&sg(o)){const{excludedFromUnreadCount:e,excludedFromLastMessage:t,excludedFromContentModeration:s}=o;!0===e&&r.push("NoUnread"),!0===t&&r.push("NoLastMsg"),!0===s&&r.push("NoMsgCheck")}return{onlineUserOnly:s,cloudCustomData:i,messageControlInfo:r,offlinePushInfo:n}}function ng(e){const{webhookInfo:{disableCloudMessagePreHook:t=!1,disableCloudMessagePostHook:s=!1}={}}=e||{};if(!t&&!s)return;const o=[];return t&&o.push("ForbidBeforeSendMsgCallback"),s&&o.push("ForbidAfterSendMsgCallback"),o}function ig(e,t){return h(this,void 0,void 0,(function*(){const s=e.conversationType===Th.CONV_GROUP?function(e,t){var s;const o=og(e,t),{onlineUserOnly:n,cloudCustomData:i,messageControlInfo:r,offlinePushInfo:a}=o,c=JSON.parse(JSON.stringify(e.transformElementsToServerFormat()));let u;return v(e._receiverList)&&e._receiverList.length>0&&(u=e._receiverList,e._receiverList.length>50&&(u=e._receiverList.slice(0,50),console.warn("ReceiverListLimit"))),{servcmd:"group_open_http_svc.send_group_msg",data:{From_Account:null===(s=Vt.store.get("login"))||void 0===s?void 0:s.userId,GroupId:e.to,MsgBody:c,CloudCustomData:i,Random:e.random,MsgPriority:e.priority,ClientSeq:e.clientSequence,GroupAtInfo:e._groupAtInfoList,OnlineOnlyFlag:n?1:0,MsgClientTime:e.clientTime,OfflinePushInfo:Hh(a),SendMsgControl:n?void 0:r,NeedReadReceipt:!0===e.needReadReceipt?1:0,To_Account:u,SupportMessageExtension:!0===e.isSupportExtension?1:0,IsRelayMsg:!0===e._relayFlag?1:0,CustomModerationConfigID:e._cmConfigID,ForbidCallbackControl:ng(t)}}}(e,t):function(e,t){var s;const o=og(e,t),{onlineUserOnly:n,cloudCustomData:i,messageControlInfo:r,offlinePushInfo:a}=o,c=!0===n?0:void 0,u=JSON.parse(JSON.stringify(e.transformElementsToServerFormat()));return{servcmd:"openim.sendmsg",data:{From_Account:null===(s=Vt.store.get("login"))||void 0===s?void 0:s.userId,To_Account:e.to,MsgBody:u,CloudCustomData:i,MsgSeq:e.sequence,MsgRandom:e.random,MsgLifeTime:c,From_AccountNick:e.nick,From_AccountHeadurl:e.avatar,SendMsgControl:0!==c?r:void 0,MsgClientTime:e.clientTime,IsNeedReadReceipt:!0===e.needReadReceipt?1:0,SupportMessageExtension:!0===e.isSupportExtension?1:0,IsRelayMsg:!0===e._relayFlag?1:0,CustomModerationConfigID:e._cmConfigID,OfflinePushInfo:Hh(a),forbidCallbackControl:ng(t)}}}(e,t),o=yield to(s);return o?{time:o.MsgTime,messageDropReason:o.MsgDropReason,sequence:o.MsgSeq}:null}))}const{isPlainObject:rg}=Vt.utils,{MSG_AUDIO:ag,MSG_FILE:cg,MSG_IMAGE:ug,MSG_VIDEO:lg,MSG_MERGER:dg}=hs;class pg{init(){Sh.getInstance().registerApi({apiName:"sendMessage",context:this,matcher:e=>![ag,cg,ug,lg,dg].includes(e[0].type)})}sendMessage(e,t){return h(this,void 0,void 0,(function*(){const s=Vt.ssoLog.createSSOLogData({method:"sendMessage"}),{TOTAL_COUNT:o,SEND_COST:n,SUCCESS_COUNT:i,FAILED_COUNT:r}=Ss;if(!(e instanceof Ph)){const e=new Fs({code:gs.MSG_INSTANCE_REQUIRED});throw s.setError(e).end(),e}const a=e.validateBeforeSend();if(!a.isValid){const{code:e,message:t=""}=a.error||{},o=new Fs({code:e,message:t});throw s.setError(o).end(),o}this._reportMessageSendQuality({name:o,message:e});let c=!1;const{messageDataHandler:u}=Vt.message||{};try{const{messageControlInfo:s}=t||{};let o=null;u.addRandomOfSentMessage(e.random);const r=Date.now();if(e.conversationType===Th.CONV_C2C?(c=!0===(null==t?void 0:t.onlineUserOnly),o=yield ig(e,t)):e.conversationType===Th.CONV_GROUP&&(yield this._validateBeforeSendGroupMessage(e),o=yield ig(e,t)),o){const{messageDropReason:t,sequence:a,time:l}=o;if(this._updateNickAndAvatarOfSentMessageByMe(e),t&&this._logRateLimitInfo(e,a),this._reportMessageSendQuality({name:i,message:e}),this._reportMessageSendQuality({name:n,message:e,startTs:r}),!0===e.isResend){const t=u.findMessage(e.ID);t&&(console.log(`sendMessage resend ok. ID:${t.ID}`),u.deleteConversationMessage(t))}return e.status=Zt.SUCCESS,e.time=l,e.conversationType===Th.CONV_GROUP&&(e.sequence=a),c?e._onlineOnlyFlag=!0:(u.storeConversationMessage(e),this._applySentMessageControlInfo(e,s),this._emitOnlineMessageSent(e)),{code:0,data:{message:e}}}}catch(t){e.status=Zt.FAIL,u.removeRandomOfSentMessage(e.random);const{errorCode:s,errorMessage:o="",errorInfo:n=o}=t||{};this._hasRiskContent(s)&&(e.hasRiskContent=!0),c||this._isRejectedByRestApi(s)||u.storeConversationMessage(e),this._reportMessageSendQuality({name:r,message:e,error:t});const i=new Fs({code:s,message:n,data:{message:e}});throw this._logSendMessageError({message:e,error:i}),i}}))}_hasRiskContent(e){return 80001===e||80004===e}_isRejectedByRestApi(e){return e>=10100&&e<=10200||e>=120001&&e<=13e4}_logSendMessageError({message:e,error:t}){const s=Vt.ssoLog.createSSOLogData({method:"sendMessage"});let o=`head.seq: type:${e.type} from:${e.from} to:${e.to}`;if(Vt.utils.IN_BROWSER){if("connection"in navigator){const e=navigator.connection;o+=` downlink:${e.downlink} effectiveType:${e.effectiveType} rtt:${e.rtt}`}if("memory"in window.performance){const e=window.performance.memory;o+=` usedJSHeapSize:${e.usedJSHeapSize} totalJSHeapSize:${e.totalJSHeapSize} jsHeapSizeLimit:${e.jsHeapSizeLimit}`}}s.setLogInfo({message:o}).setError(t).end()}_emitOnlineMessageSent(e){const t=e._isExcludedFromLastMessage?"":e,{conversationID:s,conversationType:o}=e,n=Xs(s)?zt.TOPIC_NEW_MESSAGE:zt.NEW_MESSAGE;Vt.notificationCenter.emitInnerEvent(n,{result:{conversationUpdateFieldList:[{conversationID:s,type:o,message:e,lastMessage:t,unreadCount:0}]}})}_applySentMessageControlInfo(e,t){t&&rg(t)&&(!0===t.excludedFromLastMessage&&(e._isExcludedFromLastMessage=!0),!0===t.excludedFromUnreadCount&&(e._isExcludedFromUnreadCount=!0))}_logRateLimitInfo(e,t){const s=Vt.ssoLog.createSSOLogData({method:"messageDropReason"}),o=`from:${e.from} to:${e.to} sequence:${t} messageDropReason:${messageDropReason}`;s.setLogInfo({message:o}).end(),console.warn(`sendMessage ${o}`)}_updateNickAndAvatarOfSentMessageByMe(e){const{messageDataHandler:t}=Vt.message||{};let s=!1;const{conversationID:o}=e,n=t.getLatestMsgSentByMe(o);if(n){const{nick:i,avatar:r}=n;i===e.nick&&r===e.avatar||(s=!0),s&&t.updateNickAndAvatarOfSentMessage({conversationID:o,latestNick:e.nick,latestAvatar:e.avatar,isSentByMe:!0})}}_validateBeforeSendGroupMessage(e){return h(this,void 0,void 0,(function*(){var t,s,o;const{to:n,from:i}=e;let r=n,a=mh.getGroup(r);if(Qs({groupID:r})&&(null==a?void 0:a.isSupportTopic))throw new Fs({code:gs.MSG_SEND_GRP_WITH_TOPIC_FAIL});if(Xs(n)&&([r]=n.split(ls.TOPIC),a=mh.getGroup(r)),!a&&"function"==typeof(null===(t=Sh.getInstance().getApiMap())||void 0===t?void 0:t.getGroupProfile)){const e=yield Sh.getInstance().getApiMap().getGroupProfile({groupID:r});if((null===(o=null===(s=null==e?void 0:e.data)||void 0===s?void 0:s.group)||void 0===o?void 0:o.type)===hs.GRP_AVCHATROOM){const e=ks({code:gs.MSG_SEND_FAIL_NOT_IN_AV,replacement1:i,replacement2:r});throw new Fs({code:gs.MSG_SEND_FAIL_NOT_IN_AV,message:e})}}return!0}))}_reportMessageSendQuality(e){Vt.notificationCenter.emitInnerEvent(zt.QUALITY_STAT,{label:Is.MESSAGE_SEND_SUCCESS_RATE,data:e})}}class hg{constructor(e){this.value=e,this.next=null}}class gg{constructor(e){this.head=null,this.tail=null,this.size=0,this.capacity=e}append(e){this.size>=this.capacity&&this.removeHead();const t=new hg(e);this.head?(this.tail.next=t,this.tail=t):(this.head=t,this.tail=t),this.size+=1}delete(e){if(!this.head)return;if(this.head.value===e)return void(this.head=this.head.next);let t=this.head;for(;t.next;){if(t.next.value===e)return void(t.next=t.next.next);t=t.next}}has(e){if(!this.head)return!1;let t=this.head,s=!1;for(;t;)t.value===e&&(s=!0),t=t.next;return s}removeHead(){this.head&&(this.head===this.tail?(this.head=null,this.tail=null):this.head=this.head.next,this.size-=1)}peek(){var e;return null===(e=this.head)||void 0===e?void 0:e.value}length(){return this.size}isEmpty(){return 0===this.size}isFull(){return this.size===this.capacity}clear(){this.head=null,this.tail=null,this.size=0}}var _g=new class{constructor(){this._sparseMessagesByConversation=new Map,this._latestMessageSentByPeerMap=new Map,this._latestMessageSentByMeMap=new Map,this._randomOfSentMessageList=new gg(100),Vt.notificationCenter.subscribeInnerEvent(zt.LOGOUT,this._reset,this),Vt.notificationCenter.subscribeInnerEvent(zt.DESTROY,this._dispose,this)}get _messagesByConversation(){return vh.getMessages()}storeConversationMessage(e,t=!1){const{conversationID:s}=e;if(!s)return!1;if(this._messagesByConversation.has(s)||this._messagesByConversation.set(s,new Map),this._shouldSkipStoreMessage(e,t))return!1;const o=this._getUniqueIdOfMessage(e);return this._messagesByConversation.get(s).set(o,e),this._updateLatestMessageMap(e),!0}_updateLatestMessageMap(e){const{conversationID:t}=e;"out"===e.flow?this._setLatestMsgSentByMe(t,e):t.startsWith("C2C")&&this._setLatestMsgSentByPeer(t,e)}_shouldSkipStoreMessage(e,t){const s=this._getUniqueIdOfMessage(e),o=this._messagesByConversation.get(e.conversationID);if(null==o?void 0:o.has(s)){const e=null==o?void 0:o.get(s);if(!t||!0===(null==e?void 0:e.isModified))return!0}return!1}deleteConversationMessage(e){var t;const{conversationID:s=""}=e,o=this._getUniqueIdOfMessage(e);this._messagesByConversation.has(s)&&(null===(t=this._messagesByConversation.get(s))||void 0===t||t.delete(o))}modifyConversationMessage(e,t){var s;if(!this._messagesByConversation.has(e)&&!this._sparseMessagesByConversation.has(e))return{isUpdated:!1,message:null};const o=this._getUniqueIdOfMessage(t),n=this._getMessageFromLocalMessage(e,o);if(n){const{messageVersion:o,elements:i,cloudCustomData:r,checkResult:a=0}=t,c=a>1;if(console.log(`conversationToMessageMap modifyConversationMessage localVersion:${n.version} remoteVersion:${o}`),n.version<o){const t=this._getUniqueIdOfMessage(n),a=ve(i);return(null===(s=this._messagesByConversation.get(e))||void 0===s?void 0:s.has(t))?vh.updateMessage(e,[t],{isModified:!0,version:o,_elements:a,payload:a[0].content,type:a[0].type,cloudCustomData:r,hasRiskContent:c,operation:es.modify}):(n.version=o,n._elements=a,n.payload=n._elements[0].content,n.type=n._elements[0].type,n.cloudCustomData=r,n.isModified=!0,n.hasRiskContent=c),{isUpdated:!0,message:n}}return{isUpdated:!1,message:n}}return{isUpdated:!1,message:null}}_getMessageFromLocalMessage(e,t){var s;if(this._messagesByConversation.has(e))return null===(s=this._messagesByConversation.get(e))||void 0===s?void 0:s.get(t);if(this._sparseMessagesByConversation.has(e)){const s=[...this._sparseMessagesByConversation.get(e).values()];for(let e=0;e<s.length;e++)if(this._getUniqueIdOfMessage(s[e])===t)return s[e]}return null}findMessage(e){let t=null;const s=Array.from(this._messagesByConversation.values());for(const o of s){if(t=Array.from(o.values()).find((t=>t.ID===e))||null,t)break}if(!t){const s=Array.from(this._sparseMessagesByConversation.values());for(const o of s)if(t=o.get(e)||null,t)break}return t}deleteConversationMessageList(e){this._messagesByConversation.has(e)&&(this._messagesByConversation.delete(e),this._latestMessageSentByMeMap.delete(e),this._latestMessageSentByPeerMap.delete(e)),this._sparseMessagesByConversation.has(e)&&this._sparseMessagesByConversation.delete(e)}revokeMessage({conversationID:e,sequence:t,random:s,revoker:o}){const n=this._messagesByConversation.get(e);let i=null;if(n){const r=Array.from(n.values());if(i=this._findMessageBySequenceAndRandom({messageList:r,random:s,sequence:t}),i){const t=this._getUniqueIdOfMessage(i);return vh.updateMessage(e,[t],{isRevoked:!0,revoker:o,operation:es.revoke}),i}}if(this._sparseMessagesByConversation.has(e)){const n=Array.from(this._sparseMessagesByConversation.get(e).values());if(i=this._findMessageBySequenceAndRandom({messageList:n,random:s,sequence:t}),i)return i.isRevoked=!0,i.revoker=o,i}}_findMessageBySequenceAndRandom({messageList:e,sequence:t,random:s}){for(let o=0;o<e.length;o+=1){const n=e[o];if(n.sequence===t&&(g(s)||n.random===s))return n}return null}prependLocalMessageList(e){const{messageList:t,conversationID:s}=e;if(0===t.length)return[];const o=[],n=[],i=this._messagesByConversation.get(s)||new Map;for(const e of t){const t=this._getUniqueIdOfMessage(e);i.has(t)||(o.push(e),n.push([t,e]))}if(n.length>0){const e=new Map([...n,...i.entries()]);this._messagesByConversation.set(s,e),this._updateLatestMessageSentByMe(s),this._updateLatestMessageSentByPeer(s)}return o}storeSparseMessageList(e){if(0===e.length)return;const{conversationID:t}=e[0],s=e.length;this._sparseMessagesByConversation.has(t)||this._sparseMessagesByConversation.set(t,new Map);const o=this._sparseMessagesByConversation.get(t);for(let t=0;t<s;t++){const s=e[t];o.has(s.ID)||o.set(s.ID,s)}}_updateLatestMessageSentByMe(e){var t;const s=Array.from((null===(t=this._messagesByConversation.get(e))||void 0===t?void 0:t.values())||[]);if(0!==s.length)for(let t=s.length-1;t>=0;t--)if("out"===s[t].flow){this._setLatestMsgSentByMe(e,s[t]);break}}_updateLatestMessageSentByPeer(e){var t;const s=Array.from((null===(t=this._messagesByConversation.get(e))||void 0===t?void 0:t.values())||[]);if(0!==s.length&&e.startsWith("C2C"))for(let t=s.length-1;t>=0;t--)if("in"===s[t].flow){this._setLatestMsgSentByPeer(e,s[t]);break}}_getUniqueIdOfMessage(e){const{from:t,to:s,random:o,sequence:n,time:i}=e;return`${t}-${s}-${o}-${n}-${i}`}_setLatestMsgSentByPeer(e,t){this._latestMessageSentByPeerMap.set(e,t)}_setLatestMsgSentByMe(e,t){this._latestMessageSentByMeMap.set(e,t)}getLatestMsgSentByPeer(e){return this._latestMessageSentByPeerMap.get(e)}getLatestMsgSentByMe(e){return this._latestMessageSentByMeMap.get(e)}addRandomOfSentMessage(e){this._randomOfSentMessageList.append(e)}removeRandomOfSentMessage(e){this._randomOfSentMessageList.delete(e)}updateNickAndAvatarOfSentMessage(e){const{conversationID:t="",latestAvatar:s,latestNick:o,isSentByMe:n=!0}=e,i=this._messagesByConversation.get(t);if(!i)return;const r=Array.from(i.values()),a=n?"out":"in";r.forEach((e=>{const{nick:t,avatar:n,flow:i}=e;i===a&&(t!==o&&(e.nick=o),n!==s&&(e.avatar=s))}))}isInMessageList(e){var t;const{conversationID:s}=e;if(!s)return!1;if(!this._messagesByConversation.has(s))return!1;const o=this._getUniqueIdOfMessage(e);return null===(t=this._messagesByConversation.get(s))||void 0===t?void 0:t.has(o)}isMessageSentByCurrentInstance(e){const{random:t}=e;return this._randomOfSentMessageList.has(t)}getContinuousMessagesByConversation(){return this._messagesByConversation}getLocalMessageList(e){const t=this._messagesByConversation.get(e);return t?[...t.values()]:[]}getSparseMessageList(e){const t=this._sparseMessagesByConversation.get(e);return t?[...t.values()]:[]}_reset(){this._messagesByConversation.clear(),this._latestMessageSentByPeerMap.clear(),this._latestMessageSentByMeMap.clear(),this._randomOfSentMessageList.clear()}_dispose(){this._reset(),Vt.notificationCenter.unSubscribeInnerEvent(zt.LOGOUT,this._reset,this),Vt.notificationCenter.unSubscribeInnerEvent(zt.DESTROY,this._dispose,this)}};function mg(e,t){const s=_h.getConversation(e);if(null==s?void 0:s.lastMessage){const{lastMessage:o}=s,{lastTime:n,lastSequence:i,version:r}=o,{time:a,sequence:c,messageVersion:u,elements:l,cloudCustomData:d}=t;n===a&&i===c&&r!==u&&(o.type=l[0].type,o.payload=l[0].content,o.messageForShow=co(o.type,o.payload),o.cloudCustomData=d,o.version=u,_h.updateConversation(e,{lastMessage:o}))}}class vg{init(){Sh.getInstance().registerApi({apiName:"modifyMessage",context:this})}modifyMessage(e){return h(this,void 0,void 0,(function*(){const t=Vt.ssoLog.createSSOLogData({method:"modifyMessage"}),{to:s,payload:o,sequence:n,conversationType:i,random:r,time:a,from:c,type:u}=e;if(!this._canModifyMessageElement(u))return void t.setLogInfo({message:`can not modify message element. message type: ${u}`}).end();const l=e.getElements();l.length>1&&(l[0].type=u,l[0].content=o);try{let o=null,u=null;if(t.setLogInfo({message:`to:${s}`}),i===Th.CONV_C2C?o=yield function(e){return h(this,void 0,void 0,(function*(){const{from:t,to:s,version:o=0,sequence:n,random:i,time:r,type:a,cloudCustomData:c}=e,u={From_Account:t,To_Account:s,MsgVersion:o,MsgSeq:n,MsgRandom:i,MsgTime:r,MsgType:a,MsgBody:e.transformElementsToServerFormat(),CloudCustomData:c},l=yield to({servcmd:"openim.modify_c2c_msg",data:u});if(l){const{MsgBody:e,MsgVersion:t,CloudCustomData:s}=l;return{elements:Qh(e),messageVersion:t,cloudCustomData:s}}}))}(e):i===Th.CONV_GROUP&&(o=yield function(e){return h(this,void 0,void 0,(function*(){const{to:t,version:s=0,sequence:o,cloudCustomData:n}=e,i={GroupId:t,MsgVersion:s,MsgSeq:o,MsgBody:e.transformElementsToServerFormat(),CloudCustomData:n},r=yield to({servcmd:"openim.modify_group_msg",data:i});if(r){const{MsgBody:e,MsgVersion:t,CloudCustomData:s}=r;return{elements:Qh(e),messageVersion:t,cloudCustomData:s}}}))}(e)),o){t.end();let l=`${i}${s}`;return s===io()&&i===Th.CONV_C2C&&(l=`${i}${c}`),u={conversationType:i,from:c,to:s,time:a,random:r,sequence:n,elements:null==o?void 0:o.elements,cloudCustomData:null==o?void 0:o.cloudCustomData,messageVersion:null==o?void 0:o.messageVersion,conversationID:l},this._handleModifyMessageSuccess(u),{code:0,data:{message:e}}}}catch(e){const{errorCode:t}=e||{},s=new Fs({functionName:"modifyMessage",code:t});throw this._logModifyMessageError(s),s}}))}_logModifyMessageError(e){Vt.ssoLog.getSSOLogData("modifyMessage").setError(e).end()}_handleModifyMessageSuccess(e){const{conversationID:t}=e,{isUpdated:s,message:o}=Vt.message.messageDataHandler.modifyConversationMessage(t,e);!0===s&&Vt.notificationCenter.emitOuterEvent(Wt.MESSAGE_MODIFIED,{name:Wt.MESSAGE_MODIFIED,data:[o]}),Vt.notificationCenter.emitInnerEvent(zt.MESSAGE_MODIFIED,{conversationID:t,message:o}),mg(t,e)}_canModifyMessageElement(e){return[Oh.MSG_TEXT,Oh.MSG_CUSTOM,Oh.MSG_LOCATION,Oh.MSG_FACE].includes(e)}}class fg{init(){const{notificationCenter:e}=Vt,{InnerEventSubType:t}=e;zs.getInstance().registerWorkflowStep(ms.RECEIVE_C2C_NEW_MESSAGE,vs.HANDLE_C2C_NEW_MESSAGE,this._handleC2CMessagePush,this),zs.getInstance().registerWorkflowStep(ms.RECEIVE_C2C_NEW_MESSAGE,vs.EMIT_C2C_MESSAGE_EVENT,this._emitMessageEventsAfterReceiveNewMessage,this),zs.getInstance().registerWorkflowStep(ms.SYNC_SERVER_INFO_AFTER_RE_ONLINE,vs.EMIT_C2C_MESSAGE_EVENT,this._emitMessageEventsAfterSyncUnreadMessage,this),e.subscribeInnerEvent(zt.MESSAGE_PUSH,t.C2C_REALTIME_MESSAGE,this._executeReceiverNewMessageWorkFlow,this),e.subscribeInnerEvent(zt.MESSAGE_PUSH,t.C2C_MESSAGE_MODIFIED,this._handleC2CMessageModify,this),e.subscribeInnerEvent(zt.DESTROY,this._dispose,this)}_executeReceiverNewMessageWorkFlow(e){zs.getInstance().executeWorkflow(ms.RECEIVE_C2C_NEW_MESSAGE,e)}_handleC2CMessagePush(e){const t=e.data||{},{messageDataHandler:s}=Vt.message||{},o=[],n=new Map;return t.C2cMsgArray.forEach((e=>{const t=this._generateC2CMessage(e);this._updateMessageProfile(t);let i=1===t.isModified;if(s.isMessageSentByCurrentInstance(t)?t.isModified=i:i=!1,t.isOnlineMessage())t._onlineOnlyFlag=!0,s.isMessageSentByCurrentInstance(t)||o.push(t);else if(!s.isInMessageList(t)){s.storeConversationMessage(t)&&Zh({conversationUpdateFields:n,message:t}),s.isMessageSentByCurrentInstance(t)&&!i||o.push(t)}})),{conversationUpdateFieldList:[...n.values()],messages:o}}_emitMessageEventsAfterReceiveNewMessage(e){var t;const{messages:s=[]}=(null===(t=e.result)||void 0===t?void 0:t[vs.HANDLE_C2C_NEW_MESSAGE])||{};this._emitMessageEvents(s)}_emitMessageEventsAfterSyncUnreadMessage(e){var t;const{messages:s=[]}=(null===(t=e.result)||void 0===t?void 0:t[vs.UNREAD_MESSAGE_SYNC])||{};this._emitMessageEvents(s)}_emitMessageEvents(e){const t=(null==e?void 0:e.filter((e=>!0===(null==e?void 0:e.isModified))))||[];t.length>0&&Vt.notificationCenter.emitOuterEvent("onMessageModified",{name:"onMessageModified",data:t});const s=null==e?void 0:e.filter((e=>!(null==e?void 0:e.isModified)));s.length>0&&Vt.notificationCenter.emitOuterEvent("onMessageReceived",{name:"onMessageReceived",data:s})}_generateC2CMessage(e){const t=Th.CONV_C2C,s=Wh(e),o=Vt.message.messageFactory.createMessage(Object.assign(Object.assign({},s),{conversationType:t,flow:Nh.IN})),{elements:n}=s;return o.setElement(n),o}_updateMessageProfile(e){var t;const{messageDataHandler:s}=Vt.message||{},o=null===(t=Vt.store.get("login"))||void 0===t?void 0:t.userId,{from:n,nick:i,avatar:r,conversationID:a=""}=e;if(n!==o){const t=s.getLatestMsgSentByPeer(a);if(t){const{nick:o,avatar:n}=t;g(i)||g(r)?(e.nick=_(o)?o:e.nick,e.avatar=_(n)?n:e.avatar):i===o&&r===n||(s.updateNickAndAvatarOfSentMessage({conversationID:a,latestNick:i,latestAvatar:r,isSentByMe:!1}),this._updateConversationUserProfile({conversationID:a,nick:i,avatar:r}))}}else{const e=s.getLatestMsgSentByMe(a);!e||i===e.nick&&r===e.avatar||s.updateNickAndAvatarOfSentMessage({conversationID:a,latestNick:i,latestAvatar:r,isSentByMe:!0})}}_updateConversationUserProfile(e){const{conversationID:t,nick:s,avatar:o}=e,n=_h.getConversation(t),{userProfile:i={}}=n||{};i.avatar===o&&i.nick===s||_h.updateConversation(t,{userProfile:Object.assign(Object.assign({},i),{nick:s,avatar:o})})}_updateMessageListDueToModify(e){const{conversationID:t}=e,{isUpdated:s,message:o}=Vt.message.messageDataHandler.modifyConversationMessage(t,e);!0===s&&Vt.notificationCenter.emitOuterEvent("onMessageModified",{name:"onMessageModified",data:[o]}),Vt.notificationCenter.emitInnerEvent("ModifyMessageSuccess",e),mg(t,e)}_handleC2CMessageModify(e){e.C2cMsgModNotifys.forEach((e=>{var t;const s=Th.CONV_C2C;let o=Yh(e);const{to:n,from:i}=o;let r=`${s}${n}`;n===(null===(t=Vt.store.get("login"))||void 0===t?void 0:t.userId)&&(r=`${s}${i}`),o=Object.assign({conversationType:s,conversationID:r},o),this._updateMessageListDueToModify(o)}))}_dispose(){const{notificationCenter:e}=Vt,{InnerEventSubType:t}=e;Vt.notificationCenter.unSubscribeInnerEvent(zt.MESSAGE_PUSH,t.C2C_REALTIME_MESSAGE,this._handleC2CMessagePush,this),Vt.notificationCenter.unSubscribeInnerEvent(zt.MESSAGE_PUSH,t.C2C_MESSAGE_MODIFIED,this._handleC2CMessageModify,this),Vt.notificationCenter.unSubscribeInnerEvent(zt.DESTROY,this._dispose,this)}}class Ig{init(){const{notificationCenter:e}=Vt,{InnerEventSubType:t}=e;zs.getInstance().registerWorkflowStep(ms.RECEIVE_GROUP_NEW_MESSAGE,vs.HANDLE_GROUP_NEW_MESSAGE,this._handleGroupMessagePush,this),zs.getInstance().registerWorkflowStep(ms.RECEIVE_GROUP_NEW_MESSAGE,vs.EMIT_GROUP_MESSAGE_EVENT,this._emitMessageEvents,this),e.subscribeInnerEvent(zt.MESSAGE_PUSH,t.GROUP_REALTIME_MESSAGE,this._executeReceiverNewMessageWorkFlow,this),e.subscribeInnerEvent(zt.MESSAGE_PUSH,t.GROUP_MESSAGE_MODIFIED,this._handleGroupMessageModify,this),e.subscribeInnerEvent(zt.DESTROY,this._dispose,this)}_executeReceiverNewMessageWorkFlow(e){this._canExecuteReceiverNewMessageWorkFlow(e)&&zs.getInstance().executeWorkflow(ms.RECEIVE_GROUP_NEW_MESSAGE,e)}_handleGroupMessagePush(e){const t=e.data||{},{messageDataHandler:s}=Vt.message,o=[],n=new Map,i=null==t?void 0:t.GroupMsgArray;return null==i||i.forEach((e=>{if(1===e.GroupInfo.NotVisible)return;const t=this._generateGroupMessage(e);this.updateMessageProfile(t);let i=1===t.isModified;if(s.isMessageSentByCurrentInstance(t)?t.isModified=i:i=!1,t.isOnlineMessage())t._onlineOnlyFlag=!0,s.isMessageSentByCurrentInstance(t)||o.push(t);else if(!s.isInMessageList(t)){s.storeConversationMessage(t)&&(o.push(t),Zh({conversationUpdateFields:n,message:t}))}})),{conversationUpdateFieldList:[...n.values()],messages:o}}_emitMessageEvents(e){var t;const{messages:s}=(null===(t=e.result)||void 0===t?void 0:t[vs.HANDLE_GROUP_NEW_MESSAGE])||{},o=(null==s?void 0:s.filter((e=>!0===(null==e?void 0:e.isModified))))||[];o.length>0&&Vt.notificationCenter.emitOuterEvent("onMessageModified",{name:"onMessageModified",data:o});const n=(null==s?void 0:s.filter((e=>!(null==e?void 0:e.isModified))))||[];n.length>0&&Vt.notificationCenter.emitOuterEvent("onMessageReceived",{name:"onMessageReceived",data:n})}_generateGroupMessage(e){const t=Th.CONV_GROUP,s=zh(e),o=Vt.message.messageFactory.createMessage(Object.assign(Object.assign({},s),{conversationType:t,flow:Nh.IN})),{elements:n}=s;return o.setElement(n),o}updateMessageProfile(e){var t;const{messageDataHandler:s}=Vt.message||{},o=null===(t=Vt.store.get("login"))||void 0===t?void 0:t.userId,{from:n,nick:i,avatar:r,conversationID:a="",_elements:c}=e;if(n===o){const e=s.getLatestMsgSentByMe(a);!e||i===e.nick&&r===e.avatar||s.updateNickAndAvatarOfSentMessage({conversationID:a,latestNick:i,latestAvatar:r,isSentByMe:!0})}else if(n===hs.CONV_SYSTEM){const{operationType:t,memberInfoList:s,operatorInfo:o}=c;let n={};if(me(s)?me(o)||(n=o):[ds.JOINED,ds.KICKED,ds.ADMIN_SET,ds.ADMIN_CANCELED].includes(t)&&(n=Object.assign({},s[0])),!me(n)){const{nick:t="",avatar:s=""}=n;e.nick=t,e.avatar=s}}}_updateMessageListDueToModify(e){const{conversationID:t}=e,{isUpdated:s,message:o}=Vt.message.messageDataHandler.modifyConversationMessage(t,e);!0===s&&Vt.notificationCenter.emitOuterEvent("onMessageModified",{name:"onMessageModified",data:[o]}),mg(t,e)}_handleGroupMessageModify(e){e.GroupMsgModNotifys.forEach((e=>{const t=Th.CONV_GROUP;let s=Xh(e);const{topicID:o,groupID:n}=s,i=o||n,r=`${t}${i}`;s=Object.assign({conversationType:t,conversationID:r,to:i},s),this._updateMessageListDueToModify(s)}))}_dispose(){const{notificationCenter:e}=Vt,{InnerEventSubType:{GROUP_REALTIME_MESSAGE:t,GROUP_MESSAGE_MODIFIED:s}}=e;e.unSubscribeInnerEvent(zt.MESSAGE_PUSH,t,this._handleGroupMessagePush,this),e.unSubscribeInnerEvent(zt.MESSAGE_PUSH,s,this._handleGroupMessageModify,this),e.unSubscribeInnerEvent(zt.DESTROY,this._dispose,this)}_canExecuteReceiverNewMessageWorkFlow(e){var t,s;const{GroupId:o,GroupType:n}=(null===(s=null===(t=null==e?void 0:e.GroupMsgArray)||void 0===t?void 0:t[0])||void 0===s?void 0:s.GroupInfo)||{},i=n===us.GRP_AVCHATROOM;return!(!mh.getGroup(o)&&i)}}var Sg=new class{constructor(){this.c2cMessageReceiver=new fg,this.groupMessageReceiver=new Ig}init(){this.c2cMessageReceiver.init(),this.groupMessageReceiver.init()}};const Eg={createCustomMessage:{to:{required:!0,rules:["string"],allowEmpty:!1},conversationType:{required:!0,rules:["string"],allowEmpty:!1},payload:{required:!0,rules:["object"],allowEmpty:!1},cloudCustomData:{required:!1,rules:["string"],allowEmpty:!1},priority:{required:!1,rules:["string"],allowEmpty:!1},customModerationConfigurationID:{required:!1,rules:["string"],allowEmpty:!1}},sendMessage:[{key:"message",required:!0,rules:["object"],allowEmpty:!1},{key:"options",required:!1,rules:["object"],allowEmpty:!1}],createTextMessage:{to:{required:!0,rules:["string"],allowEmpty:!1},conversationType:{required:!0,rules:["string"],allowEmpty:!1,customValidator:e=>!(!e.startsWith("C2C")&&!e.startsWith("GROUP"))||"conversationType is invalid."},payload:{required:!0,rules:["object"],allowEmpty:!1,customValidator:e=>function(e){var t;if("string"!=typeof(null==e?void 0:e.text)||"string"==typeof e.text&&0===(null===(t=null==e?void 0:e.text)||void 0===t?void 0:t.length))return"payload.text is invalid.";return!0}(e)}}};const Cg={createCustomMessage:!0,sendMessage:!0,modifyMessage:!0};var Mg=new class{getGroupRoamingMessagesByAnchor(e){return h(this,void 0,void 0,(function*(){try{const t=Vt.ssoLog.createSSOLogData({method:"getGroupRoamingMessagesByAnchor"}),{conversationID:s,count:o,direction:n,sequence:i}=e,r=s.replace(rs.CONV_GROUP,""),a=[];let c=i;if(n===ts.BACKWARD){if("number"!=typeof i)return{messageList:[],hasNoMoreHistoryMessage:!1,nextReqMessageIDFromServer:""};c=i+o-1}const u=yield function(e){return h(this,void 0,void 0,(function*(){const{groupID:t,count:s,messageSequence:o}=e,n={GroupId:t,ReqMsgNumber:s,WithRecalledMsg:1,Version:1};return o&&(n.ReqMsgSeq=o),yield to({servcmd:"group_open_http_svc.group_msg_get",data:n})}))}({groupID:r,count:o,messageSequence:c});if(u){const{RspMsgList:e=[],NextReqMsgSeq:s=0,IsFinished:o,InvisibleMsgSeq:l}=u;t.setLogInfo({message:`groupID:${r} sequence:${i} reqSeq:${c} direction:${n}\n complete:${o} nextSequence:${s} remoteMsgCount:${e.length} invisibleSequenceList:${l}`}).end();const d=[];for(let t=0;t<e.length;t++){const s=e[t];s.From_Account===hs.CONV_SYSTEM&&a.push(s);const o=this._parseMessage(s);d.push(o)}d.reverse();let p=o===bh;n===ts.BACKWARD&&(p=d[d.length-1].sequence>=i);return{messageList:eg(d),invisibleSequenceList:l,nextReqMessageIDFromServer:s,hasNoMoreHistoryMessage:p,serverGroupTipList:a}}}catch(e){const t=new Fs({code:null==e?void 0:e.code});Vt.ssoLog.getSSOLogData("getGroupRoamingMessagesByAnchor").setError(t).end()}}))}_parseMessage(e){const t=rs.CONV_GROUP;4===e.Event&&(e.MsgBody.MsgType=hs.MSG_GRP_TIP);const s=zh(e),o=Fh.createMessage(Object.assign(Object.assign({},s),{conversationType:t,flow:"in"}));return o.setElement(s.elements),o}};class yg{constructor(){this.messageHelper=tg,this.messageFactory=Fh,this.messageSender=new pg,this.messageAction=new vg,this.messageReceiver=Sg,this.messageDataHandler=_g,this.messageHistory=Mg,this.messageSender.init(),this.messageFactory.init(),this.messageAction.init(),this.messageReceiver.init(),Ws({auth:Cg,params:Eg})}}const Tg="User",Ag="Tag_Profile_IM_",Og=100,Dg={NICK:`${Ag}Nick`,GENDER:`${Ag}Gender`,BIRTHDAY:`${Ag}BirthDay`,LOCATION:`${Ag}Location`,SELFSIGNATURE:`${Ag}SelfSignature`,ALLOWTYPE:`${Ag}AllowType`,LANGUAGE:`${Ag}Language`,AVATAR:`${Ag}Image`,MESSAGESETTINGS:`${Ag}MsgSettings`,ADMINFORBIDTYPE:`${Ag}AdminForbidType`,LEVEL:`${Ag}Level`,ROLE:`${Ag}Role`},Rg="USER_STATUS",Lg=1,Ng={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:[]},bg=new Map([[Dg.NICK,"nick"],[Dg.GENDER,"gender"],[Dg.BIRTHDAY,"birthday"],[Dg.LOCATION,"location"],[Dg.SELFSIGNATURE,"selfSignature"],[Dg.ALLOWTYPE,"allowType"],[Dg.LANGUAGE,"language"],[Dg.AVATAR,"avatar"],[Dg.MESSAGESETTINGS,"messageSettings"],[Dg.ADMINFORBIDTYPE,"adminForbidType"],[Dg.LEVEL,"level"],[Dg.ROLE,"role"]]);var Gg=new class{createProfile(e,t){const s={userID:e,profileCustomField:[]};return t.forEach((e=>{const{tag:t,value:o}=e;t&&t.indexOf("Tag_Profile_Custom")>-1?s.profileCustomField.push({key:t,value:o}):bg.has(t)&&(s[bg.get(t)]=o)})),Object.assign(Object.assign({},Ng),s)}parseProfileItem(e=[]){const t=[];return e.forEach((e=>{t.push({tag:e.Tag,value:e.Value})})),t}parseProfileList(e=[]){const t=[];return e.forEach((e=>{t.push({tag:e.Tag,value:e.ValueBytes})})),t}convertParamsToProfile(e){const t=[];return Object.keys(e).forEach((s=>{t.push({tag:Dg[s.toUpperCase()],value:e[s]})})),t}normalizeProfileFields(e){const t={};return e.forEach((e=>{const{tag:s,value:o}=e;if(bg.has(s)){const e=bg.get(s);t[e]=o}})),t}};const{generateProtocolData:wg}=Vt.common;function Pg(e){return h(this,void 0,void 0,(function*(){const t="profile.portrait_get_all",s={From_Account:io(),UserItem:[]};e.forEach((e=>{s.UserItem.push({CustomSequence:0,StandardSequence:0,To_Account:e})}));const o=wg({servcmd:t,data:s}),n=`${o.head.seq}${t}`,i=yield Vt.channel.sendPacket(o,{requestId:n});if(i)return function(e){const{ActionStatus:t,ErrorCode:s,ErrorDisplay:o,ErrorInfo:n,UserProfileItem:i}=e,r=[];return i.map((e=>{const{To_Account:t,CustomSequence:s,ResultCode:o,ResultInfo:n,StandardSequence:i,ProfileItem:a}=e,c=Gg.parseProfileItem(a);r.push({userId:t,customSequence:s,resultCode:o,resultInfo:n,standardSequence:i,profileItem:c})})),{actionStatus:t,errorCode:s,errorDisplay:o,errorInfo:n,userProfile:r}}(i)}))}function Ug(e){return fh.getFriendMap().has(e)}const{isEmpty:kg}=Vt.utils;class Fg{init(){Sh.getInstance().registerApi({apiName:"getMyProfile",context:this}),Sh.getInstance().registerApi({apiName:"getUserProfile",context:this}),Sh.getInstance().registerApi({apiName:"updateMyProfile",context:this}),this.createProfile=Gg.createProfile.bind(Gg);const{notificationCenter:e}=Vt;zs.getInstance().registerWorkflowStep(ms.SYNC_SERVER_INFO_AFTER_LOGIN,vs.USER_PROFILE_SYNC,this.getMyProfileCacheThenServer,this),e.subscribeInnerEvent(zt.MESSAGE_PUSH,e.InnerEventSubType.PROFILE_MODIFIED,this._onProfileDataModify,this),e.subscribeInnerEvent(zt.LOGOUT,this._reset,this),e.subscribeInnerEvent(zt.DESTROY,this._dispose,this)}getMyProfile(){return h(this,void 0,void 0,(function*(){const e=Vt.ssoLog.createSSOLogData({method:"getMyProfile"});try{const t=io(),s=yield Pg([t]);if(s){const e=this._handleProfileFormResponse(s)[0];return fh.getUserProfileMap().set(t,e),{code:0,data:e}}e.end()}catch(t){const{errorCode:s,errorInfo:o}=t,n=new Fs({functionName:"getMyProfile",code:s,message:o});throw e.setError(n).end(),t}}))}getUserProfile(e){return h(this,void 0,void 0,(function*(){const t=Vt.ssoLog.createSSOLogData({method:"getUserProfile"});try{let{userIDList:s}=e;s.length>Og&&(s=s.slice(0,Og));const{userIdListToRequest:o,userIdListToCache:n}=this._filterRequestAndCacheUsers(s),i=[];n.forEach((e=>{const t=fh.getUserProfile(e);i.push(t)}));const r=`userIDList.length:${s.length}`;if(0===o.length)return t.setLogInfo({message:r}).end(),{code:0,data:i};const a=yield Pg(o);if(a){const e=this._handleProfileFormResponse(a);e.forEach((e=>{Ug(e.userID)&&fh.getUserProfileMap().set(e.userID,e)}));const s=e.concat(i);return t.setLogInfo({message:r}).end(),{code:0,data:s}}}catch(e){const{errorCode:s}=e,o=new Fs({functionName:"getUserProfile",code:s});throw t.setError(o).end(),o}}))}getMyProfileCacheThenServer(){return h(this,void 0,void 0,(function*(){const e=io(),t=fh.getUserProfileMap().has(e);return t?{code:0,data:t}:this.getMyProfile()}))}updateMyProfile(e){return h(this,void 0,void 0,(function*(){const t=Vt.ssoLog.createSSOLogData({method:"updateMyProfile"}),s=io(),o={};for(const t in e)void 0!==e[t]&&(o[t]=e[t]);const n=Gg.convertParamsToProfile(o);try{const e={From_Account:s,ProfileItem:n};t.setLogInfo({message:JSON.stringify(n)}),yield function(e){return h(this,void 0,void 0,(function*(){const t="profile.portrait_set",s=wg({servcmd:t,data:e}),o=`${s.head.seq}${t}`,n=yield Vt.channel.sendPacket(s,{requestId:o});if(n){const{ActionStatus:e,ErrorCode:t,ErrorDisplay:s,ErrorInfo:o}=n;return{actionStatus:e,errorCode:t,errorDisplay:s,errorInfo:o}}}))}(e);const i=fh.getUserProfile(s);let r;r=i?Object.assign(Object.assign({},i),o):Gg.createProfile(s,n);return!jt(i,r,["lastUpdatedTime","profileCustomField"])&&Vt.notificationCenter.emitOuterEvent(Wt.PROFILE_UPDATED,{name:Wt.PROFILE_UPDATED,data:[r]}),r.lastUpdatedTime=Date.now(),fh.getUserProfileMap().set(s,r),t.end(),{code:0,data:r}}catch(e){const{errorCode:s,errorInfo:o}=e,n=new Fs({functionName:"updateMyProfile",code:s,message:o});throw t.setError(n).end(),n}}))}updateMyNickAndAvatar(e){return h(this,void 0,void 0,(function*(){const t=io(),s=Date.now(),o=fh.getUserProfile(t);let n={};n=o?Object.assign(o,e):Gg.createProfile(t,e),n.lastUpdatedTime=s,fh.getUserProfileMap().set(t,n)}))}_onProfileDataModify(e){const t=function(e){const{Profile_Account:t,PushType:s,ProfileList:o}=e;return{userId:t,pushType:s,profileList:Gg.parseProfileList(o)}}(e.ProfileDataMod[0]);if(kg(t))return;const{isProfileUpdated:s,profile:o}=this._handleProfileModified(t);s&&(Vt.notificationCenter.emitInnerEvent(zt.PROFILE_UPDATE,{name:zt.PROFILE_UPDATE,data:[o]}),Vt.notificationCenter.emitOuterEvent(Wt.PROFILE_UPDATED,{name:Wt.PROFILE_UPDATED,data:[o]}))}_dispose(){const{notificationCenter:e}=Vt;e.unSubscribeInnerEvent(zt.LOGOUT,this._reset,this),e.unSubscribeInnerEvent(zt.MESSAGE_PUSH,e.InnerEventSubType.PROFILE_MODIFIED,this._onProfileDataModify,this),e.unSubscribeInnerEvent(zt.DESTROY,this._dispose,this),this._reset()}_handleProfileModified(e){const{userId:t,profileList:s}=e,o=fh.getUserProfile(t);if(!o||!Ug(t))return{isProfileUpdated:!1,profile:null};const n=Gg.normalizeProfileFields(s),i=Object.keys(n).some((e=>o[e]!==n[e]));if(!i)return{isProfileUpdated:!1,profile:o};const r=Date.now(),a=Object.assign(Object.assign(Object.assign({},o),n),{lastUpdatedTime:r});return fh.getUserProfileMap().set(t,a),_h.updateConversation(`C2C${t}`,{userProfile:a}),{isProfileUpdated:i,profile:a}}_filterRequestAndCacheUsers(e){const t=[],s=[];return e.forEach((e=>{const o=fh.getUserProfileMap().has(e);Ug(e)&&o?s.push(e):t.push(e)})),{userIdListToRequest:t,userIdListToCache:s}}_handleProfileFormResponse(e){const{userProfile:t}=e;if(!Array.isArray(t))return[];const s=t.filter((e=>"@TLS#NOT_FOUND"!==e.userId&&""!==e.userId&&!kg(e.profileItem))),o=Date.now();return s.map((e=>{const t=Gg.createProfile(e.userId,e.profileItem);return t.lastUpdatedTime=o,t}))}_reset(){fh.getUserProfileMap().clear()}}const $g=new Map,qg=["0","1","2","3","4","5","6","7","8","9","A","B","C","D","E","F"];for(let e=0,t=qg.length;e<t;e++)$g.set(e,qg[e]);function xg(e){if(!e)return"";const t=String(e).replace(/[=]+$/,"");let s="";if(t.length%4==1)return"";for(let e,o,n=0,i=0;o=t.charAt(i++);~o&&(e=n%4?64*e+o:o,n++%4)?s+=String.fromCharCode(255&e>>(-2*n&6)):0)o="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=".indexOf(o);try{return decodeURIComponent(escape(s))}catch(e){return console.warn(e),""}}const{isEmpty:Vg}=Vt.utils,{generateProtocolData:Bg}=Vt.common;function jg(e){return h(this,void 0,void 0,(function*(){const t="im_open_status.ws_get_user_status",s=Bg({servcmd:t,data:{To_Account:e}}),o=`${s.head.seq}${t}`,n=yield Vt.channel.sendPacket(s,{requestId:o});if(n)return function(e){const{ErrorCode:t,ErrorInfo:s,ErrorList:o=[],UserStatusList:n=[]}=e,i=n.map((e=>{const{To_Account:t,Status:s,CustomStatus:o}=e;return{userID:t,statusType:s,customStatus:xg(o)}})),r=o.map((e=>{const{To_Account:t,Invalid_Account:s,ErrorCode:o,ErrorInfo:n}=e;return{userID:Vg(s)?t:s,code:o,message:n}}));return{errorCode:t,errorInfo:s,successUserList:i,failureUserList:r}}(n)}))}class Kg{constructor(){this._customStatus=""}init(){const{notificationCenter:e}=Vt;Sh.getInstance().registerApi({apiName:"getUserStatus",context:this}),Sh.getInstance().registerApi({apiName:"setSelfStatus",context:this}),Sh.getInstance().registerApi({apiName:"subscribeUserStatus",context:this}),Sh.getInstance().registerApi({apiName:"unsubscribeUserStatus",context:this}),zs.getInstance().registerWorkflowStep(ms.SYNC_SERVER_INFO_AFTER_RE_ONLINE,vs.USER_STATUS_UPDATE,this._onReOnline,this),e.subscribeInnerEvent(zt.MESSAGE_PUSH,e.InnerEventSubType.USER_STATUS_UPDATE,this._onUserStatusUpdate,this),e.subscribeInnerEvent(zt.LOGOUT,this._reset,this),e.subscribeInnerEvent(zt.DESTROY,this._dispose,this)}setSelfStatus(e){return h(this,void 0,void 0,(function*(){const t=Vt.ssoLog.createSSOLogData({method:"setSelfStatus"}),s=io(),{customStatus:o}=e;try{return yield function(e){return h(this,void 0,void 0,(function*(){const t="im_open_status.ws_set_custom_status",s=Bg({servcmd:t,data:{CustomStatus:e}}),o=`${s.head.seq}${t}`,n=yield Vt.channel.sendPacket(s,{requestId:o});if(n){const{ErrorCode:e,ErrorInfo:t}=n;return{errorCode:e,errorInfo:t}}}))}(o),this._customStatus=o,t.setLogInfo({message:`customStatus: ${o}`}).end(),{code:0,data:{userID:s,statusType:Lg,customStatus:o}}}catch(e){const{errorCode:s,errorInfo:o}=e,n=new Fs({functionName:"setSelfStatus",code:s,message:o});throw t.setError(n).end(),n}}))}getUserStatus(e){return h(this,void 0,void 0,(function*(){const t=Vt.ssoLog.createSSOLogData({method:"getUserStatus"}),{userIDList:s=[]}=e;return t.setLogInfo({moreMessage:`userIDList length: ${s.length}`}),this._isOnlyMeInArray(s)?this._getMyStatus():this._getUserStatus(s)}))}setCustomStatus(e){const t=xg(e);this._customStatus=t}subscribeUserStatus(e){return h(this,void 0,void 0,(function*(){try{console.log(`${Tg} subscribeUserStatus options: `,e);const{userIDList:t=[]}=e;this._checkBusinessCapabilityBits("subscribeUserStatus");const s=this._getMaxUserCount("subscribe"),o=this._sliceUserIDList(t,s),n=yield function(e){return h(this,void 0,void 0,(function*(){const{channel:t}=Vt,s="im_open_status.ws_status_subscribe",o=Bg({servcmd:s,data:{To_Account:e}}),n=`${o.head.seq}${s}`;return yield t.sendPacket(o,{requestId:n})}))}(o);return{code:0,data:{failureUserList:this._parseResponse(n)}}}catch(e){throw console.error(`${Tg} subscribeUserStatus error:`,e),e}}))}unsubscribeUserStatus(e){return h(this,void 0,void 0,(function*(){try{console.log(`${Tg} unsubscribeUserStatus options: `,e),this._checkBusinessCapabilityBits("unsubscribeUserStatus");const{userIDList:t=[]}=e,s=this._getMaxUserCount("unsubscribe"),o=this._sliceUserIDList(t,s),n=yield function(e){return h(this,void 0,void 0,(function*(){const{channel:t}=Vt,s="im_open_status.ws_status_unsubscribe";let o={};o=0===e.length?{UnsubscribeAll:1}:{To_Account:e};const n=Bg({servcmd:s,data:o}),i=`${n.head.seq}${s}`;return yield t.sendPacket(n,{requestId:i})}))}(o);return{code:0,data:{failureUserList:this._parseResponse(n)}}}catch(e){throw console.error(`${Tg} unsubscribeUserStatus error:`,e),e}}))}_onUserStatusUpdate(e){const{UserStatusList:t=[]}=e||{},s=t.map((e=>{const{To_Account:t,Status:s,CustomStatus:o}=e;return{userID:t,statusType:s,customStatus:xg(o)}}));this._emitUserStatusUpdatedEvent(s)}_onReOnline(e){const t=xg(e.data.customStatus);if(this._customStatus===t)return;this._customStatus=t;const s={userID:io(),statusType:Lg,customStatus:t};this._emitUserStatusUpdatedEvent(s)}_emitUserStatusUpdatedEvent(e){Vt.notificationCenter.emitOuterEvent(Wt.USER_STATUS_UPDATED,{name:Wt.USER_STATUS_UPDATED,data:e})}_sliceUserIDList(e,t){return e.slice(0,t)}_parseResponse(e){const{ErrorList:t=[]}=e;return t.map((e=>{const{To_Account:t,Invalid_Account:s,ErrorCode:o,ErrorInfo:n}=e;return{userID:Vt.utils.isEmpty(s)?t:s,code:o,message:n}}))}_checkBusinessCapabilityBits(e){if(!Vt.store.get("commercialConfig").get(Rg))throw new Fs({functionName:e,code:gs.NO_USE,replacement1:e})}_getMaxUserCount(e){const t=Vt.store.get("cloudConfig")||{},s={query:{key:"status_query_count",default:500},subscribe:{key:"status_sub_count",default:Og},unsubscribe:{key:"status_unsub_count",default:Og}},{key:o,default:n}=s[e],i=t[o]||n;return parseInt(i,10)}_getMyStatus(){const e=Vt.ssoLog.getSSOLogData("getUserStatus");e.setLogInfo({moreMessage:"getUserStatus._getMyStatus"});const t={userID:io(),statusType:Lg,customStatus:this._customStatus};return e.end(),{code:0,data:{successUserList:[t],failureUserList:[]}}}_getUserStatus(e){return h(this,void 0,void 0,(function*(){const t=Vt.ssoLog.getSSOLogData("getUserStatus");t.setLogInfo({moreMessage:"getUserStatus._getUserStatus"});try{this._checkBusinessCapabilityBits("getUserStatus");const s=this._getMaxUserCount("query"),o=this._sliceUserIDList(e,s),n=yield jg(o),{successUserList:i,failureUserList:r}=n||{};return t.end(),{code:0,data:{successUserList:i,failureUserList:r}}}catch(e){const{errorCode:s}=e,o=new Fs({functionName:"getUserStatus",code:s});throw t.setError(o).end(),o}}))}_isOnlyMeInArray(e){const t=io();return 1===e.length&&e.indexOf(t)>-1}_dispose(){const{notificationCenter:e}=Vt;e.unSubscribeInnerEvent(zt.MESSAGE_PUSH,e.InnerEventSubType.USER_STATUS_UPDATE,this._onUserStatusUpdate,this),e.unSubscribeInnerEvent(zt.DESTROY,this._dispose,this),e.unSubscribeInnerEvent(zt.LOGOUT,this._reset,this),this._reset()}_reset(){this._customStatus=""}}const Hg={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}}},Wg={getMyProfile:!0,getUserProfile:!0,updateMyProfile:!0,setSelfStatus:!0,getUserStatus:!0,subscribeUserStatus:!0,unsubscribeUserStatus:!0};class Yg{constructor(){this.userProfile=new Fg,this.userStatus=new Kg,this.userProfile.init(),this.userStatus.init(),Ws({auth:Wg,params:Hg})}}function zg(e){const t=[];if(!_(e))return t;const s=e.length;if(0===s)return t;for(let o=s-1;o>=0;o--)"1"===e[o]&&t.push(2**(s-o-1));return t}var Jg,Qg,Xg;!function(e){e.NOT_START="notStart",e.PENDING="pending",e.RESOLVED="resolved",e.REJECTED="rejected"}(Jg||(Jg={})),function(e){e[e.C2C=1]="C2C",e[e.GROUP=2]="GROUP"}(Qg||(Qg={})),function(e){e[e.C2C=8]="C2C",e[e.GROUP=2]="GROUP"}(Xg||(Xg={}));class Zg{constructor(){this._name="SyncConversationHandler",this._pagingStatus=Jg.NOT_START,this._pagingTimeStamp=0,this._pagingStartIndex=0,this._pagingPinnedTimeStamp=0,this._pagingPinnedStartIndex=0}init(){const{notificationCenter:e}=Vt;zs.getInstance().registerWorkflowStep(ms.SYNC_SERVER_INFO_AFTER_RE_ONLINE,vs.CONVERSATION_RECOVER,this._syncConversationList,this),zs.getInstance().registerWorkflowStep(ms.SYNC_SERVER_INFO_AFTER_LOGIN,vs.CONVERSATION_LIST_SYNC,this._syncConversationListAfterLogin,this),e.subscribeInnerEvent(zt.LOGOUT,this._reset,this),e.subscribeInnerEvent(zt.DESTROY,this._dispose,this),console.log(`${this._name}.init`)}isSyncCompleted(){return this._pagingStatus===Jg.RESOLVED}_syncConversationListAfterLogin(){return h(this,void 0,void 0,(function*(){return this._pagingStatus=Jg.NOT_START,this._pagingTimeStamp=0,this._pagingStartIndex=0,this._pagingPinnedTimeStamp=0,this._pagingPinnedStartIndex=0,this._syncConversationList()}))}_syncConversationList(){return h(this,void 0,void 0,(function*(){const{ssoLog:e}=Vt,t=e.createSSOLogData({method:"syncConversationList"});try{const e=yield this._pagingGetConversationList(!0);this._pagingStatus=Jg.RESOLVED;const{conversationList:s=[]}=e||{};return t.setLogInfo({message:`count:${s.length}`}).end(),console.log(`${this._name}._syncConversationList ok, count:${s.length}`),e}catch(e){const{errorCode:s,errorInfo:o}=e,n=new Fs({functionName:"syncConversationList",code:s,message:o});t.setError(n).end(),console.error(`${this._name}._syncConversationList fail:`,n)}}))}_pagingGetConversationList(e){return h(this,void 0,void 0,(function*(){try{const t=[];this._pagingStatus=Jg.PENDING;const s=yield function(e){return h(this,void 0,void 0,(function*(){const{fromAccount:t,pagingTimeStamp:s,pagingStartIndex:o,pagingPinnedTimeStamp:n,pagingPinnedStartIndex:i}=e;return to({servcmd:"recentcontact.page_get",data:{AssistFlags:31,MsgAssistFlags:15,OrderType:1,From_Account:t,StartIndex:o,TimeStamp:s,TopStartIndex:i,TopTimeStamp:n}})}))}({fromAccount:io(),pagingTimeStamp:e?this._pagingTimeStamp:0,pagingStartIndex:e?this._pagingStartIndex:0,pagingPinnedTimeStamp:e?this._pagingPinnedTimeStamp:0,pagingPinnedStartIndex:e?this._pagingPinnedStartIndex:0}),{CompleteFlag:o,SessionItem:n=[],TimeStamp:i,StartIndex:r,TopTimeStamp:a,TopStartIndex:c}=s||{};if(n.length>0){const e=this._getConversationOptions(n);t.push(...e);const{notificationCenter:s}=Vt;s.emitInnerEvent(zt.SYNC_CONVERSATION_LIST,{conversationUpdateFieldList:e})}if(this._pagingTimeStamp=i,this._pagingStartIndex=r,this._pagingPinnedTimeStamp=a,this._pagingPinnedStartIndex=c,1!==o){const{conversationList:s}=yield this._pagingGetConversationList(e);t.push(...s)}return{conversationList:t}}catch(e){throw console.error(`${this._name}._pagingGetConversationList fail:`,e),e}}))}_getConversationOptions(e){const{utils:{isUndefined:t}}=Vt,s=this._convertConversationKey(e);return this._filterValidConversations(s).map((e=>(t(e.lastMsg)&&(e.lastMsg={elements:[]}),e.type===Qg.C2C?this._assembleC2COption(e):this._assembleGroupOption(e))))}_filterValidConversations(e){return e.filter((({type:e,userID:t})=>e===Qg.C2C&&!function(e){let t;return e.startsWith(hs.CONV_C2C)&&(t=e.replace(hs.CONV_C2C,"")),"@TLS#ERROR"===t||"@TLS#NOT_FOUND"===t}(t)||2===e))}_assembleC2COption(e){var t,s,o,n,i,r;const a=this._createUserprofile(e);return{conversationID:`${hs.CONV_C2C}${e.userID}`,type:hs.CONV_C2C,lastMessage:{lastTime:e.time,lastSequence:e.sequence,fromAccount:e.lastC2CMsgFromAccount,type:(null===(t=e.lastMsg)||void 0===t?void 0:t.elements[0])?null===(s=e.lastMsg)||void 0===s?void 0:s.elements[0].type:null,payload:(null===(o=e.lastMsg)||void 0===o?void 0:o.elements[0])?this._amendLayersOverLimitProp(e.lastMsg.elements[0].content):null,cloudCustomData:(null===(n=e.lastMsg)||void 0===n?void 0:n.cloudCustomData)||"",isRevoked:e.lastMessageFlag===Xg.C2C,onlineOnlyFlag:!1,nick:"",nameCard:"",version:0,isPeerRead:this._computeIsPeerRead(e),revoker:(null===(r=null===(i=e.lastMsg)||void 0===i?void 0:i.revokerInfo)||void 0===r?void 0:r.revoker)||null},unreadCount:0,userProfile:a,peerReadTime:e.peerReadTime,isPinned:1===e.isPinned,customData:e.customMark||"",markList:zg(e.standardMark),conversationGroupList:[],remark:e.friendRemark||"",messageRemindType:this._transMsgRemindType(e.messageRemindType)}}_createUserprofile(e){var t;const{userID:s,nick:o,peerAvatar:n}=e,i=[{tag:"Tag_Profile_IM_Nick",value:o},{tag:"Tag_Profile_IM_Image",value:n}];return null===(t=Vt.user.userProfile)||void 0===t?void 0:t.createProfile(s,i)}_computeIsPeerRead(e){const t=io(),{lastC2CMsgFromAccount:s,time:o,c2cPeerReadTime:n}=e;return s===t&&o<=n}_assembleGroupOption(e){var t,s,o;return{conversationID:`${hs.CONV_GROUP}${e.groupID}`,type:hs.CONV_GROUP,lastMessage:Object.assign(Object.assign({lastTime:e.time,lastSequence:e.sequence,fromAccount:e.msgGroupFromAccount},this._patchTypeAndPayload(e)),{cloudCustomData:(null===(t=e.lastMsg)||void 0===t?void 0:t.cloudCustomData)||"",isRevoked:e.lastMessageFlag===Xg.GROUP,onlineOnlyFlag:!1,nick:e.msgGroupFromNickName||"",nameCard:e.msgGroupFromCardName||"",revoker:(null===(o=null===(s=e.lastMsg)||void 0===s?void 0:s.revokerInfo)||void 0===o?void 0:o.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:zg(e.standardMark),conversationGroupList:[],messageRemindType:this._transMsgRemindType(e.messageRemindType),subType:e.groupType}}_convertConversationKey(e){return e.map((e=>({type:e.Type,userID:e.To_Account,nick:e.C2cNick,peerAvatar:e.C2cImage,time:e.MsgTimeStamp,sequence:e.MsgSeq,lastC2CMsgFromAccount:e.LastC2cMsgFrom_Account,lastMsg:this._convertLastMsgKey(e.LastMsg),lastMessageFlag:e.LastMsgFlags,c2cPeerReadTime:e.LastC2cMsgPeerReadTime,peerReadTime:e.C2cPeerReadTime,friendRemark:e.C2cRemark,isPinned:e.TopFlags,standardMark:e.StandardMark,customMark:e.CustomMark,messageRemindType:e.MsgRecvOption,groupID:e.ToAccount,groupNick:e.GroupNick,groupImage:e.GroupImage,groupType:e.GroupType,nextMessageSeq:e.GroupNextMsgSeq,msgGroupFromAccount:e.MsgGroupFrom_Account,msgGroupFromNickName:e.MsgGroupFromNickName,MsgGroupFromCardName:e.MsgGroupFromCardName,unreadCount:e.UnreadMsgCount,noUnreadCount:e.GroupIgnoredUnreadSeqCount})))}_convertLastMsgKey(e){var t,s;const{utils:{isEmpty:o}}=Vt;if(o(e))return null;let n="",i=null;return e.MsgBody&&(n=null===(t=e.MsgBody[0])||void 0===t?void 0:t.MsgType,i=this._parseContent(n,e.MsgBody[0])),{event:e.Event,elements:[{type:n,content:i,cloudCustomData:e.CloudCustomData}],revokerInfo:{revoker:null===(s=e.RevokerInfo)||void 0===s?void 0:s.revoker}}}_parseContent(e,t){var s;if(!t)return t;const o=Vt.message.messageFactory.getElementClass(e);return o?null===(s=o.parseServerPushElement(t))||void 0===s?void 0:s.content:t}_amendLayersOverLimitProp(e){const{LayersOverLimit:t}=e;return p(e,["LayersOverLimit"]).layersOverLimit=1===t,e}_transMsgRemindType(e){let t="";return 0===e?t=hs.MSG_REMIND_ACPT_AND_NOTE:1===e?t=hs.MSG_REMIND_DISCARD:2===e?t=hs.MSG_REMIND_ACPT_NOT_NOTE:3===e&&(t=hs.NOT_RECEIVE_OFFLINE_PUSH_EXCEPT_AT),t}_patchTypeAndPayload(e){const{utils:{isUndefined:t}}=Vt,{event:s,elements:o=[]}=e.lastMsg||{};return t(s)?{type:o[0]?o[0].type:null,payload:o[0]?this._amendLayersOverLimitProp(o[0].content):null}:{type:hs.MSG_GRP_TIP,payload:{}}}_computeGroupUnreadCount(e){const{unreadCount:t=0,noUnreadCount:s=0}=e,o=t-s;return o>0?o:0}_reset(){this._pagingStatus=Jg.NOT_START,this._pagingTimeStamp=0,this._pagingStartIndex=0,this._pagingPinnedTimeStamp=0,this._pagingPinnedStartIndex=0}_dispose(){this._reset();const{notificationCenter:e}=Vt;e.unSubscribeInnerEvent(zt.LOGOUT,this._reset,this),e.unSubscribeInnerEvent(zt.DESTROY,this._dispose,this)}}class e_{constructor(){this.syncConversationHandler=new Zg,this.syncConversationHandler.init()}}console.log(`TencentCloudLiteChat.VERSION:${We}`);var t_={create:function(e){var t,s;const{SDKAppID:o,testEnv:n=!1,devMode:i=!1,unlimitedAVChatRoom:r=!1,scene:a="",oversea:c=!1,instance:u}=e;let l=o;if(!function(e){if("number"==typeof e)return!0;const t=Number(e);return!Number.isNaN(t)}(l))return console.error("Create SDK instance failed. Failed to parse the SDKAppID, please check the arguments"),null;if(l=Number(l),Js.has(l))return Js.get(l);let d=null;if(u)d=u,d._workflowManager&&zs.setInstance(d._workflowManager),d._pluginManager&&d._pluginManager.installBuiltInPlugin(ph),u.isReady()&&(null===(s=(t=zs.getInstance()).executeWorkflow)||void 0===s||s.call(t,ms.SYNC_SERVER_INFO_AFTER_LOGIN));else{const e=function(){function e(){return(65536*(1+Math.random())|0).toString(16).substring(1)}return`${e()+e()}${e()}${e()}${e()}${e()}${e()}${e()}`}();Vt.init({sdkAppId:l,instanceId:e,testEnv:n,devMode:i,unlimitedAVChatRoom:r,scene:a,oversea:c,sdkEdition:dh}),zs.getInstance().init(),Vt.message=new yg,Vt.user=new Yg,Vt.login=new yh,Vt.conversation=new e_,gh.getInstance().installBuiltInPlugin(ph),d=Sh.getInstance().exposeApiForClient(),d._workflowManager=zs.getInstance(),d._pluginManager=gh.getInstance()}return Js.set(l,d),d},TSignaling:Jt,EVENT:Wt,VERSION:We,TYPES:hs};export{t_ as default};
|
|
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 n=(...e)=>{s.apply(r,e),this.off(t,n)};this.on(t,n)}}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:[],n=[];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=>{n.push({type:c.SERVER_PUSH_MESSAGE+":"+e,data:t})}):n.push({type:c.SERVER_PUSH_MESSAGE+":"+s,data:t})}),n}!function(e){e.SERVER_PUSH_MESSAGE="im_open_push.msg_push",e.SERVER_PUSH_MESSAGE_MULTIPLE="im_open_push.multi_msg_push_ws",e.ERROR="error"}(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,n,o){var i,t;if(["string","number"].includes(typeof r)){let e=r,t=n;null!=(i=this._innerEventEmitter)&&i.on(s+":"+e,t,o)}else{let e=r;null!=(t=this._innerEventEmitter)&&t.on(s,e,n)}}emitInnerEvent(t,s){var e;if(null!=(e=this._innerEventEmitter)&&e.emit(t,s),Object.keys(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,n,o){var i,t;if(["string","number"].includes(typeof r)){let e=r,t=n;null!=(i=this._innerEventEmitter)&&i.off(s+":"+e,t,o)}else{let e=r;null!=(t=this._innerEventEmitter)&&t.off(s,e,n)}}subscribeOuterEvent(e,t,s){var r;null!=(r=this._outerEventEmitter)&&r.on(e,t,s)}unSubscribeOuterEvent(e,t,s){var r;null!=(r=this._outerEventEmitter)&&r.off(e,t,s)}emitOuterEvent(e,t){var s;null!=(s=this._outerEventEmitter)&&s.emit(e,t)}getOuterEventEmitter(){return this._outerEventEmitter}rest(){this._outerEventEmitter=null,this._innerEventEmitter=null}};function p(e,t){var s={};for(n in e)Object.prototype.hasOwnProperty.call(e,n)&&t.indexOf(n)<0&&(s[n]=e[n]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols)for(var r=0,n=Object.getOwnPropertySymbols(e);r<n.length;r++)t.indexOf(n[r])<0&&Object.prototype.propertyIsEnumerable.call(e,n[r])&&(s[n[r]]=e[n[r]]);return s}function h(e,i,a,l){return new(a=a||Promise)(function(s,t){function r(e){try{o(l.next(e))}catch(e){t(e)}}function n(e){try{o(l.throw(e))}catch(e){t(e)}}function o(e){var t;e.done?s(e.value):((t=e.value)instanceof a?t:new a(function(e){e(t)})).then(r,n)}o((l=l.apply(e,i||[])).next())})}let g=e=>void 0===e,_=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,n,o)=>{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],!(g(r[a])||n&&n.includes(a)))if(I(s[a])&&I(r[a]))i+=M(s[a],r[a],n,o);else{if(o&&o.includes(r[a]))continue;s[a]!==r[a]&&(s[a]=r[a],i+=1)}return i};function y(s){let r,n,o=s,i="";for(let e=0,t=(o=s.length%8!=0?"0".repeat(8-s.length%8)+s:o)["length"];e<t;e+=8)r=parseInt(o.slice(e,e+4),2),n=parseInt(o.slice(e+4,e+8),2),i+=base16Map.get(r)+base16Map.get(n);return i}let A="undefined"!=typeof wx&&"function"==typeof wx.getSystemInfoSync&&("mac"===wx.getSystemInfoSync().platform||"windows"===wx.getSystemInfoSync().platform),T="undefined"!=typeof wx&&"function"==typeof wx.getSystemInfoSync&&Boolean(wx.getSystemInfoSync().fontSizeSetting)||A,O=T&&"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=T&&"object"==typeof wx.miniapp,P="undefined"!=typeof uni,U=T||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:T?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":T?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=x.getSystemInfoSync()["platform"];void 0!==t&&(e=t)}catch(e){console.error(e)}return e}let de=2800,pe=2801,he=3e3,ge="application/x-www-form-urlencoded;charset=UTF-8";function _e(e){return h(this,arguments,void 0,function*({method:n,url:o,data:i,timeout:a=he}){return new Promise(U?(t,e)=>{x.request({url:o,data:i,method:n,timeout:a,header:{"content-type":ge},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(n,o,!0),s.setRequestHeader("Content-type",ge),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:T,IN_WX_MINI_APP_DESK:A,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:_e,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:_,isUndefined:g,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:n}=e;this._socket&&(this._socket.binaryType="arraybuffer",this._socket.onopen=e,this._socket.onmessage=t,this._socket.onclose=s,this._socket.onerror=r,this._onSendFail=n)}unbindSocketHandlers(){this._socket&&(this._socket.onopen=null,this._socket.onmessage=null,this._socket.onclose=null,this._socket.onerror=null)}disconnect(){this._socket&&(this._socket.close(),this._socket=null)}}class Ee{connectSocket(e){return this._socket=x.connectSocket({url:e,header:{"content-type":"application/json"},complete:()=>{}}),this._socket}send(e){var t;null!=(t=this._socket)&&t.send({data:e,fail:this._onSendFail})}bindSocketHandlers(e){var{onOpen:e,onMessage:t,onClose:s,onError:r,onSendFail:n}=e;this._socket.onClose(s),this._socket.onOpen(e),this._socket.onMessage(t),this._socket.onError(r),this._onSendFail=n}unbindSocketHandlers(){this._socket&&(this._socket.onClose(()=>{}),this._socket.onOpen(()=>{}),this._socket.onMessage(()=>{}),this._socket.onError(()=>{}))}disconnect(){this._socket&&(this._socket.close(),this._socket=null)}}let Ce="CONNECT",Me="SEND",ye="DISCONNECT",Ae="OPEN",Te="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:n,onError:o,onSendFail:i}=e;if(this._worker){let s={[Ae]:t,[Te]:r,[Oe]:n,[De]:o,[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,T||G?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(g(e.isWorkerEnabled)||"1"===e.isWorkerEnabled)&&re}}let we="CHINA",Pe="OVERSEA",Ue="SINGAPORE",ke="KOREA",Fe="GERMANY",$e="IND",qe="JPN",xe="USA",Ve="INDONESIA",Be={TEST:{CHINA:{DEFAULT:"wss://wss-dev.tim.qq.com"},OVERSEA:{DEFAULT:"wss://wss-dev.tim.qq.com"},SINGAPORE:{DEFAULT:"wss://wsssgp-dev.im.qcloud.com"},KOREA:{DEFAULT:"wss://wsskr-dev.im.qcloud.com"},GERMANY:{DEFAULT:"wss://wssger-dev.im.qcloud.com"},IND:{DEFAULT:"wss://wssind-dev.im.qcloud.com"},JPN:{DEFAULT:"wss://wssjpn-dev.im.qcloud.com"},USA:{DEFAULT:"wss://wssusa-dev.im.qcloud.com"},INDONESIA:{DEFAULT:"wss://wssidn-dev.im.qcloud.com"}},PRODUCTION:{CHINA:{INITIAL:"wss://*w4c.my-imcloud.com",DEFAULT:"wss://wss.im.qcloud.com",IPV6:"wss://wssv6.im.qcloud.com",BACKUP:"wss://wss.tim.qq.com",BACKUP_WEB_ONLY:"wss://*w4c.my-cpaas.com",BACKUP_CN:"wss://wss.im.tencent.cn",STAT:"https://events.im.qcloud.com",ANYCAST:"wss://162.14.13.203"},OVERSEA:{INITIAL:"wss://*w4c.my-imcloud.com",DEFAULT:"wss://wss.im.qcloud.com",IPV6:"wss://wssv6.im.qcloud.com",BACKUP:"wss://wss.my-imcloud.com",BACKUP_WEB_ONLY:"wss://*w4c.my-cpaas.com",BACKUP_CN:"wss://wss.im.tencent.cn",STAT:"https://api.my-imcloud.com"},SINGAPORE:{INITIAL:"wss://*w4s.my-imcloud.com",DEFAULT:"wss://wsssgp.im.qcloud.com",IPV6:"wss://wsssgpv6.im.qcloud.com",BACKUP:"wss://wsssgp.my-imcloud.com",BACKUP_WEB_ONLY:"wss://*w4s.my-cpaas.com",STAT:"https://apisgp.my-imcloud.com",ANYCAST:"wss://162.14.19.159"},KOREA:{INITIAL:"wss://*w4k.my-imcloud.com",DEFAULT:"wss://wsskr.im.qcloud.com",IPV6:"wss://wsskrv6.im.qcloud.com",BACKUP:"wss://wsskr.my-imcloud.com",BACKUP_WEB_ONLY:"wss://*w4k.my-cpaas.com",STAT:"https://apikr.my-imcloud.com",ANYCAST:"wss://162.14.13.104"},GERMANY:{INITIAL:"wss://*w4g.my-imcloud.com",DEFAULT:"wss://wssger.im.qcloud.com",IPV6:"wss://wssgerv6.im.qcloud.com",BACKUP:"wss://wssger.my-imcloud.com",BACKUP_WEB_ONLY:"wss://*w4g.my-cpaas.com",STAT:"https://apiger.my-imcloud.com",ANYCAST:"wss://162.14.3.17"},IND:{INITIAL:"wss://*w4i.my-imcloud.com",DEFAULT:"wss://wssind.my-imcloud.com",IPV6:"wss://wssindv6.im.qcloud.com",BACKUP:"wss://wssind.im.qcloud.com",BACKUP_WEB_ONLY:"wss://*w4i.my-cpaas.com",STAT:"https://apiind.my-imcloud.com",ANYCAST:"wss://162.14.19.46"},JPN:{INITIAL:"wss://*w4j.my-imcloud.com",DEFAULT:"wss://wssjpn.im.qcloud.com",IPV6:"wss://wssjpnv6.im.qcloud.com",BACKUP:"wss://wssjpn.my-imcloud.com",BACKUP_WEB_ONLY:"wss://*w4j.my-cpaas.com",STAT:"https://apijpn.my-imcloud.com",ANYCAST:"wss://162.14.13.254"},USA:{INITIAL:"wss://*w4u.my-imcloud.com",DEFAULT:"wss://wssusa.im.qcloud.com",IPV6:"wss://wssusav6.im.qcloud.com",BACKUP:"wss://wssusa.my-imcloud.com",BACKUP_WEB_ONLY:"wss://*w4u.my-cpaas.com",STAT:"https://apiusa.my-imcloud.com",ANYCAST:"wss://162.14.10.42"},INDONESIA:{INITIAL:"wss://*w4y.my-imcloud.com",DEFAULT:"wss://wssidn.im.qcloud.com",IPV6:"wss://wssidnv6.im.qcloud.com",BACKUP:"wss://wssidn.my-imcloud.com",BACKUP_WEB_ONLY:"wss://*w4y.my-cpaas.com",STAT:"https://apiidn.my-imcloud.com",ANYCAST:"wss://43.129.34.169"}}},je={[Ue]:[[2e7,3e7],[172e7,173e7]],[ke]:[[3e7,4e7],[173e7,174e7]],[Fe]:[[4e7,5e7],[174e7,175e7]],[$e]:[[5e7,6e7],[175e7,176e7]],[qe]:[[6e7,7e7],[176e7,177e7]],[xe]:[[7e7,8e7],[177e7,178e7]],[Ve]:[[8e7,9e7],[178e7,179e7]]};function Ke(t){var e;if(null!=(e=be.get("instance"))&&e.oversea)return Pe;for(let e of Object.keys(je))for(var[s,r]of je[e])if(t>=s&&t<r)return e;return we}var We,He="1.5.1";!function(e){e.INITIAL="INITIAL",e.DEFAULT="DEFAULT",e.BACKUP="BACKUP",e.BACKUP_WEB_ONLY="BACKUP_WEB_ONLY",e.BACKUP_CN="BACKUP_CN",e.ANYCAST="ANYCAST",e.IPV6="IPV6"}(We=We||{});let Ye=We.INITIAL;function ze(){var e=Math.random();return 0===e?ze():e}function Je(e,t){var s,{isBinary:t=!1}=t||{},{sdkAppId:r,instanceId:n}=be.get("instance"),o=ze(),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:n,random:o,platform:j,host:i,version:a,sdkversion:He},Object.keys(s).map(e=>e+"="+s[e]).join("&"));return t?e+`/binfo?${r}&compress=gzip`:e+"/info?"+r}function Qe(e){var{sdkAppId:t,testEnv:s}=be.get("instance"),t=Ke(t);if(s)return Je(Be.TEST[t].DEFAULT,{isBinary:e});let r=Be.PRODUCTION[t],n=q&&r.ANYCAST,o=q,i=!!r.BACKUP_CN;return Je({[We.INITIAL]:()=>(Ye=We.DEFAULT,r.DEFAULT),[We.DEFAULT]:()=>(Ye=We.IPV6,r.IPV6),[We.IPV6]:()=>(Ye=We.BACKUP,r.BACKUP),[We.BACKUP]:()=>{return o?(Ye=We.BACKUP_WEB_ONLY,e=r.BACKUP_WEB_ONLY,t=Math.floor(10001*Math.random())+1e4,e.replace("*",String(t))):i?(Ye=We.BACKUP_CN,r.BACKUP_CN):n?(Ye=We.ANYCAST,r.ANYCAST):r.DEFAULT;var e,t},[We.BACKUP_WEB_ONLY]:()=>i?(Ye=We.BACKUP_CN,r.BACKUP_CN):n?(Ye=We.ANYCAST,r.ANYCAST):r.DEFAULT,[We.BACKUP_CN]:()=>(Ye=n?We.ANYCAST:We.DEFAULT,r[Ye]),[We.ANYCAST]:()=>(Ye=We.DEFAULT,r.ANYCAST="",r.DEFAULT)}[Ye](),{isBinary:e})}var Xe=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 Ze=16;var et=new class{constructor(){this._tasks=[],this._timer=null,this._taskMap=new Map}_addTaskToScheduler(e){var t=e["id"];this.removeTask(t),this._tasks.push(e),this._taskMap.set(t,e),this._sort(),this._scheduleNextTask()}_createTask(e){var{id:e,callback:t,context:s,isOnce:r=!1,intervalMs:n=Ze}=e,o=Math.max(n,Ze);return{id:e,nextExecuteTime:Date.now()+o,intervalMs:n,callback:t,context:s,isOnce:r}}addTask(e){e=this._createTask(e);this._addTaskToScheduler(e)}addOnceTask(e){e=this._createTask(Object.assign(Object.assign({},e),{isOnce:!0}));this._addTaskToScheduler(e)}removeTask(t){var e=this._tasks.findIndex(e=>e.id===t);-1<e&&(this._tasks.splice(e,1),this._taskMap.delete(t),this._scheduleNextTask())}updateTaskInterval(e,t){e=this._taskMap.get(e);e&&(e.intervalMs=t,e.nextExecuteTime=Date.now()+t,this._sort(),this._scheduleNextTask())}clearAllTasks(){this._tasks=[],this._taskMap.clear(),this._timer&&(clearTimeout(this._timer),this._timer=null)}dispose(){this.clearAllTasks()}_sort(){this._tasks.sort((e,t)=>e.nextExecuteTime-t.nextExecuteTime)}_scheduleNextTask(){this._timer&&(clearTimeout(this._timer),this._timer=null);var e=this._tasks[0];e&&(e=Math.max(0,e.nextExecuteTime-Date.now()),this._timer=setTimeout(()=>this._execute(),e))}_execute(){for(var e=Date.now();this._tasks.length&&this._tasks[0].nextExecuteTime<=e;){var t=this._tasks[0];try{t.context?t.callback.call(t.context):t.callback(),t.isOnce?this.removeTask(t.id):(t.nextExecuteTime=e+t.intervalMs,this._sort())}catch(e){console.warn(`Task ${t.id} execution failed:`,e),t.isOnce&&this.removeTask(t.id)}}this._scheduleNextTask()}};function st(t){var s=[];for(let e=0;e<t.length;e+=1){var r,n=t.charCodeAt(e);55296<=n&&n<=56319?(r=t.charCodeAt(++e)-56320+(n-55296<<10)+65536,s.push(240|r>>18,128|r>>12&63,128|r>>6&63,128|63&r)):n<=127?s.push(n):n<=2047?s.push(192|n>>6,128|63&n):s.push(224|n>>12,128|n>>6&63,128|63&n)}return new Uint8Array(s)}function ot(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]=ot(e[t]));return s}function nt(e,t){if(s.includes(e))return 0;var r=st(JSON.stringify(t));let n=4294967295;var o=r["length"];for(let e=0;e<o;e++){n^=r[e];for(let e=0;e<8;e++)1&~n?n>>>=1:n=n>>>1^3988292384}return(4294967295^n)>>>0}function it(e){var t,{servcmd:e,data:s}=e,r=(r=e,t=be.get("login")||{},n=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:n.sdkAppId,contenttype:"json",reqtime:Math.floor(Date.now()/1e3),identifier:t.a2Key?void 0:t.userId,usersig:t.a2Key?void 0:t.userSig,sdkability:75689843,sdkability_ext:y(""),cappid:t.cappid||0,tjgID:"",seq:ct(),cs:0}),n=ot(s);return r.cs=nt(e,n),{head:r,body:n}}function rt(e){var t,{servcmd:e,data:s}=e,r=(r=e,t=be.get("login")||{},n=be.get("instance")||{},{servcmd:r,ver:"v4",platform:j,websdkappid:537048168,websdkversion:"1.7.3",sdkappid:n.sdkAppId,contenttype:"",reqtime:Math.floor(Date.now()/1e3),identifier:"",usersig:"",status_instid:t.statusInstanceId||0,sdkability:75689843,sdkability_ext:y(""),cappid:t.cappid||0,seq:ct(),cs:0}),n=ot(s);return r.cs=nt(e,n),{head:r,body:n}}let at=C();function ct(){return at=at<2415919103?at+1:C()}function ut(){var e=be.get("login")||{},t=be.get("instance")||{};return{sdk_type:30,sdk_app_id:t.sdkAppId,sdk_version:"1.5.1",tiny_id:Number(e.tinyID),user_id:e.userId,platform:j,instance_id:t.instanceId,trace_id:(new Date).getTime()}}var lt,gt,dt=Object.freeze({__proto__:null,generateCosSpecifiedData:function(e){var t,{servcmd:e,data:s}=e,r=(r=e,t=be.get("login")||{},n=be.get("instance")||{},{servcmd:r,ver:"v4",platform:j,websdkappid:537048168,websdkversion:"1.7.3",sdkappid:n.sdkAppId,contenttype:"json",reqtime:Math.floor(Date.now()/1e3),identifier:t.userId,usersig:t.userSig,status_instid:t.statusInstanceId||0,sdkability:75689843,sdkability_ext:y(""),cappid:t.cappid||0,seq:ct(),cs:0}),n=ot(s);return r.cs=nt(e,n),{head:r,body:n}},generateProtocolData:it,generateSSOLogProtocolData:rt,generateSequence:ct,getCommonHead:ut,taskScheduler:et,timeManager:Xe});!function(e){e[e.info=4]="info",e[e.warning=5]="warning",e[e.error=6]="error"}(lt=lt||{});let pt={method:"extension",networkType:"network_type",eventType:"event_type",code:"error_code",message:"error_message",moreMessage:"more_message",duplicate:"duplicate",costTime:"cost_time",level:"level",uiPlatform:"ui_platform",timestamp:"timestamp"};class ht{constructor(e){this.level=lt.info,this._canSendLog=!0,this._logCreatedAt=Xe.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+=Xe.getTimeOffsetWithServer()}end(e=!1){var t;this._canSendLog&&(t=Xe.getServerTimeMs(),0===this.costTime&&(this.costTime=t-this._logCreatedAt),this.setMoreMessage(`startts:${this._logCreatedAt} endts:`+t),e?(this._canSendLog=!1,this.timestamp=Xe.getServerTimeMs(),this._ssoLogModule.pushToLogQueue(this._convertSSOLogDataKeyToServe())):setTimeout(()=>{this._canSendLog=!1,this.timestamp=Xe.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=lt.error):console.warn("SSOLogData.setError value not instanceof Error, please check!"),this}setLogInfo(t){return Object.keys(t).forEach(e=>{Object.keys(pt).includes(e)&&(this[e]=t[e])}),this}setSSOLogModule(e){this._ssoLogModule=e}_convertSSOLogDataKeyToServe(){let t={};return Object.keys(this).forEach(e=>{pt[e]&&(t[pt[e]]=this[e])}),t}}!function(e){e.RECONNECTED="reconnected",e.CLOUD_CONFIG_UPDATE="cloud_config_update",e.SOCKET_DISCONNECTED="socket_disconnected"}(gt=gt||{});var _t=gt;let mt=20,vt=6e4,ft=[4,5,6],It=[],St=[],Et="report-logger";var Ct=new class{constructor(){this._sdkAppIdBlackList=[],this._tinyIdWhiteList=[],this._reportLevel=[4,5,6],this._minThreshold=mt,this._maxThreshold=100,this._waitingTime=vt,this._lastReportAt=Date.now(),this._ssoLogMap=new Map,d.subscribeInnerEvent(_t.CLOUD_CONFIG_UPDATE,this._handleCloudConfigUpdate,this),et.addTask({id:Et,intervalMs:1e3,callback:this._checkAndReportIfDue,context:this}),this._logQueue=[],this._savePlatFormInfo()}_handleCloudConfigUpdate(e){var{evt_rpt_threshold:e=mt,evt_rpt_waiting:t=vt,evt_rpt_level:s=ft,evt_rpt_sdkappid_bl:r=It,evt_rpt_tinyid_wl:n=St}=e||{};this._sdkAppIdBlackList=r,this._waitingTime=t,this._minThreshold=e,this._reportLevel=s,this._tinyIdWhiteList=n}createSSOLogData(e){var t=new ht(e);return t.setSSOLogModule(this),this._ssoLogMap.set(e.method,t),t}getSSOLogData(e){return this._ssoLogMap.get(e)||{}}pushToLogQueue(e){e&&(this._logQueue.push(e),this._shouldUploadImmediately())&&this.uploadSSOLogData()}_shouldUploadImmediately(){return this._logQueue.length>=this._minThreshold}_isReportDue(){return Date.now()>=this._lastReportAt+this._waitingTime}_checkAndReportIfDue(){this._isReportDue()&&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:ut(),Event:t}).Header.user_id)||(e=(t=rt({servcmd:e="imopenstat.tim_web_report_v2",data:t})).head.seq+e,yield void Vt.sendPacket(t,{requestId:e})),this._lastReportAt=Date.now())})}_savePlatFormInfo(){var e,t;if(T){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"),et.removeTask(Et),d.unSubscribeInnerEvent(_t.CLOUD_CONFIG_UPDATE,this._handleCloudConfigUpdate,this),this._lastReportAt=0,this.uploadSSOLogData(),this._sdkAppIdBlackList=[],this._tinyIdWhiteList=[],this._minThreshold=mt,this._maxThreshold=100,this._waitingTime=vt,this._logQueue=[]}};let Mt=15e3,yt="Channel",At="channel_schedule_task",Tt="channel_reconnect_task",Ot="connected",Dt="connecting",Rt="disconnected",Lt=1e3,Nt="network_status_change",bt="activity_status_change",Gt="send_fail",wt="reconnect_failed",Pt="socket_error",Ut="socket_close";function kt(e){return(kt="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 Ft(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 $t,Wt,qt={exports:{}},xt=($t||(qt.exports=function s(r,n,o){function i(t,e){if(!n[t]){if(!r[t]){if(!e&&Ft)return Ft(t);if(a)return a(t,!0);e=new Error("Cannot find module '"+t+"'");throw e.code="MODULE_NOT_FOUND",e}e=n[t]={exports:{}};r[t][0].call(e.exports,function(e){return i(r[t][1][e]||e)},e,e.exports,s,r,n,o)}return n[t].exports}for(var a=Ft,e=0;e<o.length;e++)i(o[e]);return i}({1:[function(e,t,s){var r="undefined"!=typeof Uint8Array&&"undefined"!=typeof Uint16Array&&"undefined"!=typeof Int32Array,n=(s.assign=function(e){for(var t,s,r=Array.prototype.slice.call(arguments,1);r.length;){var n=r.shift();if(n){if("object"!=kt(n))throw new TypeError(n+"must be non-object");for(var o in n)t=n,s=o,Object.prototype.hasOwnProperty.call(t,s)&&(e[o]=n[o])}}return e},s.shrinkBuf=function(e,t){return e.length===t?e:e.subarray?e.subarray(0,t):(e.length=t,e)},{arraySet:function(e,t,s,r,n){if(t.subarray&&e.subarray)e.set(t.subarray(s,s+r),n);else for(var o=0;o<r;o++)e[n+o]=t[s+o]},flattenChunks:function(e){for(var t,s,r,n,o=t=0,i=e.length;o<i;o++)t+=e[o].length;for(n=new Uint8Array(t),o=s=0,i=e.length;o<i;o++)r=e[o],n.set(r,s),s+=r.length;return n}}),o={arraySet:function(e,t,s,r,n){for(var o=0;o<r;o++)e[n+o]=t[s+o]},flattenChunks:function(e){return[].concat.apply([],e)}};s.setTyped=function(e){e?(s.Buf8=Uint8Array,s.Buf16=Uint16Array,s.Buf32=Int32Array,s.assign(s,n)):(s.Buf8=Array,s.Buf16=Array,s.Buf32=Array,s.assign(s,o))},s.setTyped(r)},{}],2:[function(e,t,s){var l=e("./common"),n=!0,o=!0;try{String.fromCharCode.apply(null,[0])}catch(e){n=!1}try{String.fromCharCode.apply(null,new Uint8Array(1))}catch(e){o=!1}for(var c=new l.Buf8(256),r=0;r<256;r++)c[r]=252<=r?6:248<=r?5:240<=r?4:224<=r?3:192<=r?2:1;function u(e,t){if(t<65534&&(e.subarray&&o||!e.subarray&&n))return String.fromCharCode.apply(null,l.shrinkBuf(e,t));for(var s="",r=0;r<t;r++)s+=String.fromCharCode(e[r]);return s}c[254]=c[254]=1,s.string2buf=function(e){for(var t,s,r,n,o=e.length,i=0,a=0;a<o;a++)55296==(64512&(s=e.charCodeAt(a)))&&a+1<o&&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=n=0;n<i;a++)55296==(64512&(s=e.charCodeAt(a)))&&a+1<o&&56320==(64512&(r=e.charCodeAt(a+1)))&&(s=65536+(s-55296<<10)+(r-56320),a++),s<128?t[n++]=s:(s<2048?t[n++]=192|s>>>6:(s<65536?t[n++]=224|s>>>12:(t[n++]=240|s>>>18,t[n++]=128|s>>>12&63),t[n++]=128|s>>>6&63),t[n++]=128|63&s);return t},s.buf2binstring=function(e){return u(e,e.length)},s.binstring2buf=function(e){for(var t=new l.Buf8(e.length),s=0,r=t.length;s<r;s++)t[s]=e.charCodeAt(s);return t},s.buf2string=function(e,t){for(var s,r,n,o=t||e.length,i=new Array(2*o),a=s=0;a<o;)if((r=e[a++])<128)i[s++]=r;else if(4<(n=c[r]))i[s++]=65533,a+=n-1;else{for(r&=2===n?31:3===n?15:7;1<n&&a<o;)r=r<<6|63&e[a++],n--;1<n?i[s++]=65533:r<65536?i[s++]=r:(r-=65536,i[s++]=55296|r>>10&1023,i[s++]=56320|1023&r)}return u(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+c[e[s]]>t?s:t}},{"./common":$t=1}],3:[function(e,t,s){t.exports=function(e,t,s,r){for(var n=65535&e,o=e>>>16&65535,i=0;0!==s;){for(s-=i=2e3<s?2e3:s;o=o+(n=n+t[r++]|0)|0,--i;);n%=65521,o%=65521}return n|o<<16}},{}],4:[function(e,t,s){t.exports={Z_NO_FLUSH:0,Z_PARTIAL_FLUSH:1,Z_SYNC_FLUSH:2,Z_FULL_FLUSH:3,Z_FINISH:4,Z_BLOCK:5,Z_TREES:6,Z_OK:0,Z_STREAM_END:1,Z_NEED_DICT:2,Z_ERRNO:-1,Z_STREAM_ERROR:-2,Z_DATA_ERROR:-3,Z_BUF_ERROR:-5,Z_NO_COMPRESSION:0,Z_BEST_SPEED:1,Z_BEST_COMPRESSION:9,Z_DEFAULT_COMPRESSION:-1,Z_FILTERED:1,Z_HUFFMAN_ONLY:2,Z_RLE:3,Z_FIXED:4,Z_DEFAULT_STRATEGY:0,Z_BINARY:0,Z_TEXT:1,Z_UNKNOWN:2,Z_DEFLATED:8}},{}],5:[function(e,t,s){var a=function(){for(var e=[],t=0;t<256;t++){for(var s=t,r=0;r<8;r++)s=1&s?3988292384^s>>>1:s>>>1;e[t]=s}return e}();t.exports=function(e,t,s,r){var n=a,o=r+s;e^=-1;for(var i=r;i<o;i++)e=e>>>8^n[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,n,o,i,a,l=e.state,c=e.next_in,u=e.input,d=c+(e.avail_in-5),h=e.next_out,p=e.output,g=h-(t-e.avail_out),_=h+(e.avail_out-257),m=l.dmax,v=l.wsize,f=l.whave,I=l.wnext,S=l.window,E=l.hold,C=l.bits,M=l.lencode,y=l.distcode,A=(1<<l.lenbits)-1,T=(1<<l.distbits)-1;e:do{for(C<15&&(E+=u[c++]<<C,C+=8,E+=u[c++]<<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(n=65535&s,(r&=15)&&(C<r&&(E+=u[c++]<<C,C+=8),n+=E&(1<<r)-1,E>>>=r,C-=r),C<15&&(E+=u[c++]<<C,C+=8,E+=u[c++]<<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(o=65535&s,C<(r&=15)&&(E+=u[c++]<<C,(C+=8)<r)&&(E+=u[c++]<<C,C+=8),m<(o+=E&(1<<r)-1)){e.msg="invalid distance too far back",l.mode=30;break e}if(E>>>=r,C-=r,(r=h-g)<o){if(f<(r=o-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<n){for(n-=r;p[h++]=S[i++],--r;);i=h-o,a=p}}else if(I<r){if(i+=v+I-r,(r-=I)<n){for(n-=r;p[h++]=S[i++],--r;);if(i=0,I<n){for(n-=r=I;p[h++]=S[i++],--r;);i=h-o,a=p}}}else if(i+=I-r,r<n){for(n-=r;p[h++]=S[i++],--r;);i=h-o,a=p}for(;2<n;)p[h++]=a[i++],p[h++]=a[i++],p[h++]=a[i++],n-=3;n&&(p[h++]=a[i++],1<n)&&(p[h++]=a[i++])}else{for(i=h-o;p[h++]=p[i++],p[h++]=p[i++],p[h++]=p[i++],2<(n-=3););n&&(p[h++]=p[i++],1<n)&&(p[h++]=p[i++])}break}}break}}while(c<d&&h<_);c-=n=C>>3,E&=(1<<(C-=n<<3))-1,e.next_in=c,e.next_out=h,e.avail_in=c<d?d-c+5:5-(c-d),e.avail_out=h<_?_-h+257:257-(h-_),l.hold=E,l.bits=C}},{}],8:[function(e,t,s){var N=e("../utils/common"),b=e("./adler32"),G=e("./crc32"),w=e("./inffast"),P=e("./inftrees"),U=0,k=-2,F=1,r=852,n=592;function q(e){return(e>>>24&255)+(e>>>8&65280)+((65280&e)<<8)+((255&e)<<24)}function o(){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(n),t.sane=1,t.back=-1,U):k}function a(e){var t;return e&&e.state?((t=e.state).wsize=0,t.whave=0,t.wnext=0,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 c(e,t){var s;return e?(s=new o,(e.state=s).window=null,(s=l(e,t))!==U&&(e.state=null),s):k}var x,V,B=!0;function K(e,t,s,r){var n,e=e.state;return null===e.window&&(e.wsize=1<<e.wbits,e.wnext=0,e.whave=0,e.window=new N.Buf8(e.wsize)),r>=e.wsize?(N.arraySet(e.window,t,s-e.wsize,e.wsize,0),e.wnext=0,e.whave=e.wsize):(r<(n=e.wsize-e.wnext)&&(n=r),N.arraySet(e.window,t,s-r,n,e.wnext),(r-=n)?(N.arraySet(e.window,t,s-r,r,0),e.wnext=r,e.whave=e.wsize):(e.wnext+=n,e.wnext===e.wsize&&(e.wnext=0),e.whave<e.wsize&&(e.whave+=n))),0}s.inflateReset=a,s.inflateReset2=l,s.inflateResetKeep=i,s.inflateInit=function(e){return c(e,15)},s.inflateInit2=c,s.inflate=function(e,t){var s,r,n,o,i,a,l,c,u,d,h,p,g,_,m,v,f,I,S,E,C,M,y,A,T=0,O=new N.Buf8(4),D=[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,n=e.output,l=e.avail_out,o=e.next_in,r=e.input,a=e.avail_in,c=s.hold,u=s.bits,d=a,h=l,M=U;e:for(;;)switch(s.mode){case F:if(0===s.wrap)s.mode=13;else{for(;u<16;){if(0===a)break e;a--,c+=r[o++]<<u,u+=8}if(2&s.wrap&&35615===c)O[s.check=0]=255&c,O[1]=c>>>8&255,s.check=G(s.check,O,2,0),u=c=0,s.mode=2;else if(s.flags=0,s.head&&(s.head.done=!1),!(1&s.wrap)||(((255&c)<<8)+(c>>8))%31)e.msg="incorrect header check",s.mode=30;else if(8!=(15&c))e.msg="unknown compression method",s.mode=30;else{if(u-=4,C=8+(15&(c>>>=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&c?10:12,u=c=0}}break;case 2:for(;u<16;){if(0===a)break e;a--,c+=r[o++]<<u,u+=8}if(s.flags=c,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=c>>8&1),512&s.flags&&(O[0]=255&c,O[1]=c>>>8&255,s.check=G(s.check,O,2,0)),u=c=0,s.mode=3;case 3:for(;u<32;){if(0===a)break e;a--,c+=r[o++]<<u,u+=8}s.head&&(s.head.time=c),512&s.flags&&(O[0]=255&c,O[1]=c>>>8&255,O[2]=c>>>16&255,O[3]=c>>>24&255,s.check=G(s.check,O,4,0)),u=c=0,s.mode=4;case 4:for(;u<16;){if(0===a)break e;a--,c+=r[o++]<<u,u+=8}s.head&&(s.head.xflags=255&c,s.head.os=c>>8),512&s.flags&&(O[0]=255&c,O[1]=c>>>8&255,s.check=G(s.check,O,2,0)),u=c=0,s.mode=5;case 5:if(1024&s.flags){for(;u<16;){if(0===a)break e;a--,c+=r[o++]<<u,u+=8}s.length=c,s.head&&(s.head.extra_len=c),512&s.flags&&(O[0]=255&c,O[1]=c>>>8&255,s.check=G(s.check,O,2,0)),u=c=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,o,p,C)),512&s.flags&&(s.check=G(s.check,r,p,o)),a-=p,o+=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[o+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,o)),a-=p,o+=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[o+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,o)),a-=p,o+=p,C)break e}else s.head&&(s.head.comment=null);s.mode=9;case 9:if(512&s.flags){for(;u<16;){if(0===a)break e;a--,c+=r[o++]<<u,u+=8}if(c!==(65535&s.check)){e.msg="header crc mismatch",s.mode=30;break}u=c=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(;u<32;){if(0===a)break e;a--,c+=r[o++]<<u,u+=8}e.adler=s.check=q(c),u=c=0,s.mode=11;case 11:if(0===s.havedict)return e.next_out=i,e.avail_out=l,e.next_in=o,e.avail_in=a,s.hold=c,s.bits=u,2;e.adler=s.check=1,s.mode=12;case 12:if(5===t||6===t)break e;case 13:if(s.last)c>>>=7&u,u-=7&u,s.mode=27;else{for(;u<3;){if(0===a)break e;a--,c+=r[o++]<<u,u+=8}switch(s.last=1&c,--u,3&(c>>>=1)){case 0:s.mode=14;break;case 1:L=R=void 0;var L,R=s;if(B){for(x=new N.Buf32(512),V=new N.Buf32(32),L=0;L<144;)R.lens[L++]=8;for(;L<256;)R.lens[L++]=9;for(;L<280;)R.lens[L++]=7;for(;L<288;)R.lens[L++]=8;for(P(1,R.lens,0,288,x,0,R.work,{bits:9}),L=0;L<32;)R.lens[L++]=5;P(2,R.lens,0,32,V,0,R.work,{bits:5}),B=!1}if(R.lencode=x,R.lenbits=9,R.distcode=V,R.distbits=5,s.mode=20,6!==t)break;c>>>=2,u-=2;break e;case 2:s.mode=17;break;case 3:e.msg="invalid block type",s.mode=30}c>>>=2,u-=2}break;case 14:for(c>>>=7&u,u-=7&u;u<32;){if(0===a)break e;a--,c+=r[o++]<<u,u+=8}if((65535&c)!=(c>>>16^65535)){e.msg="invalid stored block lengths",s.mode=30;break}if(s.length=65535&c,u=c=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(n,r,o,p,i),a-=p,o+=p,l-=p,i+=p,s.length-=p}else s.mode=12;break;case 17:for(;u<14;){if(0===a)break e;a--,c+=r[o++]<<u,u+=8}if(s.nlen=257+(31&c),c>>>=5,u-=5,s.ndist=1+(31&c),c>>>=5,u-=5,s.ncode=4+(15&c),c>>>=4,u-=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(;u<3;){if(0===a)break e;a--,c+=r[o++]<<u,u+=8}s.lens[D[s.have++]]=7&c,c>>>=3,u-=3}for(;s.have<19;)s.lens[D[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[c&(1<<s.lenbits)-1])>>>16&255,f=65535&T,!((m=T>>>24)<=u);){if(0===a)break e;a--,c+=r[o++]<<u,u+=8}if(f<16)c>>>=m,u-=m,s.lens[s.have++]=f;else{if(16===f){for(A=m+2;u<A;){if(0===a)break e;a--,c+=r[o++]<<u,u+=8}if(c>>>=m,u-=m,0===s.have){e.msg="invalid bit length repeat",s.mode=30;break}C=s.lens[s.have-1],p=3+(3&c),c>>>=2,u-=2}else if(17===f){for(A=m+3;u<A;){if(0===a)break e;a--,c+=r[o++]<<u,u+=8}C=0,p=3+(7&(c>>>=m)),c>>>=3,u=u-m-3}else{for(A=m+7;u<A;){if(0===a)break e;a--,c+=r[o++]<<u,u+=8}C=0,p=11+(127&(c>>>=m)),c>>>=7,u=u-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=o,e.avail_in=a,s.hold=c,s.bits=u,w(e,h),i=e.next_out,n=e.output,l=e.avail_out,o=e.next_in,r=e.input,a=e.avail_in,c=s.hold,u=s.bits,12===s.mode&&(s.back=-1);break}for(s.back=0;v=(T=s.lencode[c&(1<<s.lenbits)-1])>>>16&255,f=65535&T,!((m=T>>>24)<=u);){if(0===a)break e;a--,c+=r[o++]<<u,u+=8}if(v&&!(240&v)){for(I=m,S=v,E=f;v=(T=s.lencode[E+((c&(1<<I+S)-1)>>I)])>>>16&255,f=65535&T,!(I+(m=T>>>24)<=u);){if(0===a)break e;a--,c+=r[o++]<<u,u+=8}c>>>=I,u-=I,s.back+=I}if(c>>>=m,u-=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;u<A;){if(0===a)break e;a--,c+=r[o++]<<u,u+=8}s.length+=c&(1<<s.extra)-1,c>>>=s.extra,u-=s.extra,s.back+=s.extra}s.was=s.length,s.mode=23;case 23:for(;v=(T=s.distcode[c&(1<<s.distbits)-1])>>>16&255,f=65535&T,!((m=T>>>24)<=u);){if(0===a)break e;a--,c+=r[o++]<<u,u+=8}if(!(240&v)){for(I=m,S=v,E=f;v=(T=s.distcode[E+((c&(1<<I+S)-1)>>I)])>>>16&255,f=65535&T,!(I+(m=T>>>24)<=u);){if(0===a)break e;a--,c+=r[o++]<<u,u+=8}c>>>=I,u-=I,s.back+=I}if(c>>>=m,u-=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;u<A;){if(0===a)break e;a--,c+=r[o++]<<u,u+=8}s.offset+=c&(1<<s.extra)-1,c>>>=s.extra,u-=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}g=p>s.wnext?(p-=s.wnext,s.wsize-p):s.wnext-p,p>s.length&&(p=s.length),_=s.window}else _=n,g=i-s.offset,p=s.length;for(l-=p=l<p?l:p,s.length-=p;n[i++]=_[g++],--p;);0===s.length&&(s.mode=21);break;case 26:if(0===l)break e;n[i++]=s.length,l--,s.mode=21;break;case 27:if(s.wrap){for(;u<32;){if(0===a)break e;a--,c|=r[o++]<<u,u+=8}if(h-=l,e.total_out+=h,s.total+=h,h&&(e.adler=s.check=(s.flags?G:b)(s.check,n,h,i-h)),h=l,(s.flags?c:q(c))!==s.check){e.msg="incorrect data check",s.mode=30;break}u=c=0}s.mode=28;case 28:if(s.wrap&&s.flags){for(;u<32;){if(0===a)break e;a--,c+=r[o++]<<u,u+=8}if(c!==(4294967295&s.total)){e.msg="incorrect length check",s.mode=30;break}u=c=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=o,e.avail_in=a,s.hold=c,s.bits=u,(s.wsize||h!==e.avail_out&&s.mode<30&&(s.mode<27||4!==t))&&K(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,n,h,e.next_out-h)),e.data_type=s.bits+(s.last?64:0)+(12===s.mode?128:0)+(20===s.mode||15===s.mode?256:0),M=(0==d&&0===h||4===t)&&M===U?-5:M)},s.inflateEnd=function(e){var t;return e&&e.state?((t=e.state).window&&(t.window=null),e.state=null,U):k},s.inflateGetHeader=function(e,t){return e&&e.state&&2&(e=e.state).wrap?((e.head=t).done=!1,U):k},s.inflateSetDictionary=function(e,t){var s,r=t.length;return!e||!e.state||0!==(s=e.state).wrap&&11!==s.mode?k:11===s.mode&&b(1,t,r,0)!==s.check?-3:K(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,n,o,i,a){for(var l,c,u,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,O=0,D=null,L=0,R=new w.Buf16(16),N=new w.Buf16(16),b=null,G=0,f=0;f<=15;f++)R[f]=0;for(I=0;I<r;I++)R[t[s+I]]++;for(C=v,E=15;1<=E&&0===R[E];E--);if(E<C&&(C=E),0===E)n[o++]=20971520,n[o++]=20971520,a.bits=1;else{for(S=1;S<E&&0===R[S];S++);for(C<S&&(C=S),f=A=1;f<=15;f++)if((A=(A<<1)-R[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]+R[f];for(I=0;I<r;I++)0!==t[s+I]&&(i[N[t[s+I]]++]=I);if(p=0===e?(D=b=i,19):1===e?(D=P,L-=257,b=U,G-=257,256):(D=k,b=F,-1),f=S,h=o,y=I=O=0,u=-1,d=(T=1<<(M=C))-1,1===e&&852<T||2===e&&592<T)return 1;for(;;){for(m=i[I]<p?(_=0,i[I]):i[I]>p?(_=b[G+i[I]],D[L+i[I]]):(_=96,0),l=1<<(g=f-y),S=c=1<<M;n[h+(O>>y)+(c-=l)]=g<<24|_<<16|m,0!==c;);for(l=1<<f-1;O&l;)l>>=1;if(0!==l?O=(O&l-1)+l:O=0,I++,0==--R[f]){if(f===E)break;f=t[s+i[I]]}if(C<f&&(O&d)!==u){for(h+=S,A=1<<(M=f-(y=0===y?C:y));M+y<E&&!((A-=R[M+y])<=0);)M++,A<<=1;if(T+=1<<M,1===e&&852<T||2===e&&592<T)return 1;n[u=O&d]=C<<24|M<<16|h-o}}0!==O&&(n[h+O]=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"),g=e("./zlib/constants"),r=e("./zlib/messages"),n=e("./zlib/zstream"),o=e("./zlib/gzheader"),_=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 n,this.strm.avail_out=0,d.inflateInit2(this.strm,t.windowBits));if(e!==g.Z_OK)throw new Error(r[e]);if(this.header=new o,d.inflateGetHeader(this.strm,this.header),t.dictionary&&("string"==typeof t.dictionary?t.dictionary=p.string2buf(t.dictionary):"[object ArrayBuffer]"===_.call(t.dictionary)&&(t.dictionary=new Uint8Array(t.dictionary)),t.raw)&&(e=d.inflateSetDictionary(this.strm,t.dictionary))!==g.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,n,o,i,a=this.strm,l=this.options.chunkSize,c=this.options.dictionary,u=!1;if(this.ended)return!1;r=t===~~t?t:!0===t?g.Z_FINISH:g.Z_NO_FLUSH,"string"==typeof e?a.input=p.binstring2buf(e):"[object ArrayBuffer]"===_.call(e)?a.input=new Uint8Array(e):a.input=e,a.next_in=0,a.avail_in=a.input.length;do{if(0===a.avail_out&&(a.output=new h.Buf8(l),a.next_out=0,a.avail_out=l),(s=(s=d.inflate(a,g.Z_NO_FLUSH))===g.Z_NEED_DICT&&c?d.inflateSetDictionary(this.strm,c):s)===g.Z_BUF_ERROR&&!0===u&&(s=g.Z_OK,u=!1),s!==g.Z_STREAM_END&&s!==g.Z_OK)return this.onEnd(s),!(this.ended=!0)}while(!a.next_out||0!==a.avail_out&&s!==g.Z_STREAM_END&&(0!==a.avail_in||r!==g.Z_FINISH&&r!==g.Z_SYNC_FLUSH)||("string"===this.options.to?(n=p.utf8border(a.output,a.next_out),o=a.next_out-n,i=p.buf2string(a.output,n),a.next_out=o,a.avail_out=l-o,o&&h.arraySet(a.output,a.output,n,o,0),this.onData(i)):this.onData(h.shrinkBuf(a.output,a.next_out))),0===a.avail_in&&0===a.avail_out&&(u=!0),(0<a.avail_in||0===a.avail_out)&&s!==g.Z_STREAM_END);return(r=s===g.Z_STREAM_END?g.Z_FINISH:r)===g.Z_FINISH?(s=d.inflateEnd(this.strm),this.onEnd(s),this.ended=!0,s===g.Z_OK):r!==g.Z_SYNC_FLUSH||(this.onEnd(g.Z_OK),!(a.avail_out=0))},i.prototype.onData=function(e){this.chunks.push(e)},i.prototype.onEnd=function(e){e===g.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")),qt.exports),Vt=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=Lt,this._currentConnectState=Ot,this._beforeSendInterceptors=[]}init(){et.addTask({id:At,intervalMs:1e3,callback:this._executeScheduledTaskIfReady,context:this}),this._updateIsBinarySupported(),this._url=function(e){var{sdkAppId:t,testEnv:s,disableIndependentDomain:r}=be.get("instance"),n=Ke(t);let o="";return s?o=Be.TEST[n].DEFAULT:r?(o=Be.PRODUCTION[n].DEFAULT,Ye=We.DEFAULT):o=Be.PRODUCTION[n].INITIAL.replace("*",""+t),Je(o,{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:n=Mt,canResend:o=!0}=t||{};if(me(e))return console.warn(yt+".sendPacket: packet is empty ",e),null;this._executeBeforeSendInterceptors(e),this._currentConnectState===Rt&&this._handleConnectStateChange({state:Rt,shouldEmitEvent:!0,shouldAttemptReconnect:!0,reason:Gt});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:n,canResend:o})}t=this._isBinarySupported?st(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(),t=yt+`.connect isWorkerEnabled: false socketID:${e} url:`+this._url;this._connectionId=e,this._ssoLog({method:"connect",message:t}),console.log(t)}disconnect(){var e=null==(e=this._socketAdapter)?void 0:e.getId(),e=yt+".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(yt+".dispose"),et.removeTask(At),et.removeTask(Tt),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=Lt,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===Dt&&this._isReconnecting;return!this._socketAdapter||e}reconnect(){return h(this,void 0,void 0,function*(){var e=`${yt}.reconnect isReconnecting: ${this._isReconnecting} currentConnectState: `+this._currentConnectState;if(this._ssoLog({method:"reconnect",message:e}),console.log(e),!this._shouldSkipReconnect()){this._url=Qe(this._isBinarySupported);try{this._isReconnecting=!0,this.disconnect(),this.connect()}catch(e){this._isReconnecting=!1,this._handleConnectStateChange({state:Rt,shouldEmitEvent:!0,shouldAttemptReconnect:!0,reason:wt}),console.warn(yt+".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=`${yt}.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:Rt,shouldEmitEvent:!0,shouldAttemptReconnect:!0,reason:Ut}),this._isReconnecting&&(this._isReconnecting=!1)}_onError(e){var{socketId:e,error:t}=e||{},t=`${yt}.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:Rt,shouldEmitEvent:!0,shouldAttemptReconnect:!0,reason:Pt}),this._isReconnecting&&(this._isReconnecting=!1)}_onSendFail(e){var{socketId:e,error:t}=e||{},e=`${yt}.onSendFail sendFailSocketId: ${e} currentSocketID: ${this._connectionId} isReconnecting: ${this._isReconnecting} error: `+t;this._ssoLog({method:"onSendFail",message:e}),console.warn(e),this._isReconnecting&&(this._isReconnecting=!1)}_onMessage(t){let s,e;this._updateHeartbeatTime();try{s=this._isBinarySupported?(this._isCompressedData(t.data)?e=>{var t=new Uint8Array(e).slice(4);let s;try{s=xt.inflate(t,{to:"string"})}catch(e){console.error("inflate error",e)}return s}:function(e){var n=new Uint8Array(e);let o="",i=0;for(var a=n["length"];i<a;){let t=n[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=n[i+e+1],r=r<<6|63&t;else r=65533,s=a-i;o+=String.fromCodePoint(r),i+=s+1}return o})(t.data):t.data,e=JSON.parse(s)}catch(s){let e=t.data;return this._ssoLog({method:"jsonParseError",message:e}),void console.error(s)}var r;e&&e.head&&({seq:t,servcmd:r}=e.head,this._pendingRequests.has(""+t+r)?this._handleRequestResponse(e):this._handlePushMessage(e))}_handleRequestResponse(e){var{seq:t,servcmd:s}=e.head,{int32_error_code:r,str_error_message:n}=(null==e?void 0:e.body)||{},o=(null==(o=null==e?void 0:e.body)?void 0:o.ErrorCode)||r,r=(null==(r=null==e?void 0:e.body)?void 0:r.ErrorInfo)||n,n=""+t+s,{resolve:t,reject:s}=this._pendingRequests.get(n);this._pendingRequests.delete(n),o&&0!==o?(d.emitInnerEvent("error",{errorCode:o,errorInfo:r}),s({errorCode:o,errorInfo:r})):t(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(`${yt}._checkPendingRequestsAndResend reConnectFlag:${this._isReconnecting} promiseMap.size:`+this._pendingRequests.size),null!=(e=this._pendingRequests)&&e.forEach((e,t)=>{var{uplinkData:s,canResend:r,resolve:n,reject:o,timeout:i}=e;if(r){this._pendingRequests.set(t,{resolve:n,reject:o,timestamp:Date.now(),uplinkData:s,timeout:i,canResend:r});let e=this._isBinarySupported?st(s).buffer:s;null!=(n=this._socketAdapter)&&n.send(e)}else this._pendingRequests.delete(t)})}_onConnect(e){var{socketId:e,event:t={}}=e||{},s=(this._connectionId=e,this._connectionEstablishedTime=Date.now(),Date.now()-this._connectionStartTime),s=yt+`.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=yt+".reconnect success";this._ssoLog({method:"reconnectSuccess",message:e}),console.log(e),d.emitInnerEvent(_t.RECONNECTED),this._isReconnecting=!1}this._resetReconnectDelay(),this._handleConnectStateChange({state:Ot,shouldEmitEvent:!0,shouldAttemptReconnect:!1})}_sendAck(e){e=it({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=it({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=yt+`.sendHeartbeat failed. isNetWorkOnline:${s} error: `+t;this._ssoLog({method:"sendHeartbeatError",message:s}),console.debug(s),this._handleConnectStateChange({state:Rt,shouldEmitEvent:!0,shouldAttemptReconnect:!0})}})}_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=yt+".networkStatusChange "+JSON.stringify(e),{isNetworkOnline:t,networkType:e}=(this._ssoLog({method:"networkStatusChange",message:t}),console.warn(t),e);t&&"none"!==e?this._handleConnectStateChange({state:Ot,shouldEmitEvent:!1,shouldAttemptReconnect:!0,reason:Nt}):this._handleConnectStateChange({state:Rt,shouldEmitEvent:!1,shouldAttemptReconnect:!0,reason:Nt})}isPrivateNetWork(){var e=be.get("instance")||{};return e.proxyServer&&!e.fileDownloadProxy}_handleConnectStateChange(e){var{state:e,shouldAttemptReconnect:t,shouldEmitEvent:s,reason:r}=e,r=`${yt}._handleConnectStateChange currentConnectState: ${this._currentConnectState} shouldAttemptReconnect: ${t} shouldEmitEvent: ${s} reason: `+r;this._currentConnectState!==e&&(this._ssoLog({method:"handleConnectStateChange",message:r}),console.log(r),s&&(console.log(`${yt}._handleConnectStateChange from ${this._currentConnectState} to `+e),d.emitOuterEvent("netStateChange",{name:"netStateChange",data:{state:e}}),(this._currentConnectState=e)===Rt)&&d.emitInnerEvent(_t.SOCKET_DISCONNECTED),t)&&(this._resetReconnectDelay(),et.addTask({id:Tt,intervalMs:this._intendedDelay,callback:this._scheduleReconnectWithBackoff,context:this}))}_handleActivityStatusChange(e){var t=null==(t=null==(t=this._socketAdapter)?void 0:t._ws)?void 0:t.readyState,e=`${yt}.activityStatusChange ${JSON.stringify(e)} readyState: `+t;this._ssoLog({method:"activityStatusChange",message:e}),console.warn(e),3===t&&this._handleConnectStateChange({state:Rt,shouldEmitEvent:!0,shouldAttemptReconnect:!0,reason:bt})}_resetReconnectDelay(){console.log(yt+"._resetReconnectDelay"),et.removeTask(Tt);var e=null==(e=be.get("activityMonitor"))?void 0:e.isActive;this._intendedDelay=e?Lt:1e3}_scheduleReconnectWithBackoff(){var e=null==(e=be.get("activityMonitor"))?void 0:e.isActive,e=(this._intendedDelay=e?Math.min(5e3,Math.max(Lt,1.5*this._intendedDelay)):Math.min(3e5,Math.max(1e3,1.5*this._intendedDelay)),(new Date).toTimeString().slice(0,8)),e=yt+`.scheduleReconnectWithBackoff timeStr: ${e} intendedDelay: `+this._intendedDelay;this._ssoLog({method:"scheduleReconnectWithBackoff",message:e}),console.log(e),this.reconnect(),et.updateTaskInterval(Tt,this._intendedDelay)}_ssoLog(e){var{method:e,message:t}=e;Ct.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 _e({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 _e({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)||T&&"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 Bt={init:function(e){be.set("instance",e),Vt.init()},destroy:function(){Vt.dispose(),be.clear(),et.dispose()},notificationCenter:d,channel:Vt,store:be,ssoLog:Ct,utils:Ie,common:dt,constants:i},jt=e=>"function"==typeof e;function Kt(t,s,r){let n=r||[];var e,o;return!(!t||!s)&&(e=Object.keys(t).filter(e=>!n.includes(e)),o=Object.keys(s).filter(e=>!n.includes(e)),e.length===o.length)&&e.every(e=>!!s.hasOwnProperty(e)&&("object"==typeof t[e]&&null!==t[e]?Kt(t[e],s[e],r):t[e]===s[e]))}!function(e){e.SDK_READY="sdkStateReady",e.SDK_NOT_READY="sdkStateNotReady",e.SDK_DESTROY="sdkDestroy",e.MESSAGE_RECEIVED="onMessageReceived",e.ROOM_CUSTOM_DATA_RECEIVED="onRoomCustomDataReceived",e.MESSAGE_MODIFIED="onMessageModified",e.MESSAGE_REVOKED="onMessageRevoked",e.MESSAGE_READ_BY_PEER="onMessageReadByPeer",e.MESSAGE_READ_RECEIPT_RECEIVED="onMessageReadReceiptReceived",e.MESSAGE_EXTENSIONS_UPDATED="onMessageExtensionsUpdated",e.MESSAGE_EXTENSIONS_DELETED="onMessageExtensionsDeleted",e.MESSAGE_REACTIONS_UPDATED="onMessageReactionsUpdated",e.CONVERSATION_LIST_UPDATED="onConversationListUpdated",e.TOTAL_UNREAD_MESSAGE_COUNT_UPDATED="onTotalUnreadMessageCountUpdated",e.CONVERSATION_GROUP_LIST_UPDATED="onConversationGroupListUpdated",e.CONVERSATION_IN_GROUP_UPDATED="onConversationInGroupUpdated",e.GROUP_LIST_UPDATED="onGroupListUpdated",e.GROUP_ATTRIBUTES_UPDATED="groupAttributesUpdated",e.GROUP_COUNTER_UPDATED="onGroupCounterUpdated",e.TOPIC_CREATED="onTopicCreated",e.TOPIC_DELETED="onTopicDeleted",e.TOPIC_UPDATED="onTopicUpdated",e.PROFILE_UPDATED="onProfileUpdated",e.USER_STATUS_UPDATED="onUserStatusUpdated",e.BLACKLIST_UPDATED="blacklistUpdated",e.FRIEND_LIST_UPDATED="onFriendListUpdated",e.FRIEND_GROUP_LIST_UPDATED="onFriendGroupListUpdated",e.FRIEND_APPLICATION_LIST_UPDATED="onFriendApplicationListUpdated",e.MY_FOLLOWERS_LIST_UPDATED="onMyFollowersListUpdated",e.MY_FOLLOWING_LIST_UPDATED="onMyFollowingListUpdated",e.MUTUAL_FOLLOWERS_LIST_UPDATED="onMutualFollowersListUpdated",e.KICKED_OUT="kickedOut",e.ERROR="error",e.NET_STATE_CHANGE="netStateChange",e.ALL_RECEIVE_MESSAGE_OPT_UPDATED="onAllReceiveMessageOptUpdated",e.SERVER_CONFIG_UPDATED="onServerConfigUpdated"}(Wt=Wt||{});var Ht,Yt=Wt;!function(e){e.LOGOUT="logout",e.DESTROY="destroy",e.CLOUD_CONFIG_UPDATE="cloud_config_update",e.PROFILE_UPDATE="profile_updated",e.ERROR="error",e.RECONNECTED="reconnected",e.FORCE_OFFLINE="im_open_status.stat_forceoffline",e.COMMERCIAL_CONFIG_PUSH="im_sdk_config_mgr.push_imsdk_purchase_bitsv2",e.OVERLOAD_PUSH="OverLoadPush.notify2",e.NEW_MESSAGE="new_message",e.MESSAGE_PUSH="im_open_push.msg_push",e.MESSAGE_DELETED="message_deleted",e.MESSAGE_REVOKED="message_revoked",e.MESSAGE_MODIFIED="message_modified",e.SOCKET_DISCONNECTED="socket_disconnected",e.CONVERSATION_UPDATED="conversation_updated",e.TOPIC_MESSAGE_DELETED="topic_message_deleted",e.TOPIC_MESSAGE_REVOKED="topic_message_revoked",e.TOPIC_MESSAGE_MODIFIED="topic_message_modified",e.TOPIC_NEW_MESSAGE="topic_new_message",e.QUALITY_STAT="quality_stat",e.SYNC_CONVERSATION_LIST="sync_conversation_list"}(Ht=Ht||{});var zt,es,ss,Jt=Ht,Qt=(!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"}(zt=zt||{}),zt);let Xt=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"},ts=(!function(e){e.UNSENT="unSend",e.SUCCESS="success",e.FAIL="fail"}(es=es||{}),{modify:Jt.MESSAGE_MODIFIED,delete:Jt.MESSAGE_DELETED,revoke:Jt.MESSAGE_REVOKED}),os=(!function(e){e[e.FORWARD=0]="FORWARD",e[e.BACKWARD=1]="BACKWARD"}(ss=ss||{}),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:es,Direction:ss})),ns={[ts.modify]:Jt.TOPIC_MESSAGE_MODIFIED,[ts.delete]:Jt.TOPIC_MESSAGE_DELETED,[ts.revoke]:Jt.TOPIC_MESSAGE_REVOKED},is={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"},rs=Object.assign({},is),as={CONV_C2C:"C2C",CONV_GROUP:"GROUP",CONV_TOPIC:"TOPIC",CONV_SYSTEM:"@TIM#SYSTEM"},cs=Object.assign(Object.assign(Object.assign(Object.assign({},as),{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"}),us=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"}),ls={GRP_WORK:"Private",GRP_PUBLIC:"Public",GRP_MEETING:"ChatRoom",GRP_AVCHATROOM:"AVChatRoom",GRP_COMMUNITY:"Community",GRP_ROOM:"Room",GRP_LIVE:"Live"},ds={COMMUNITY:"@TGS#_",TOPIC:"@TOPIC#_"},ps={JOINED:1,QUITTED:2,KICKED:3,ADMIN_SET:4,ADMIN_CANCELED:5,GROUP_PROFILE_UPDATED:6,GROUP_MEMBER_PROFILE_UPDATED:7,TOPIC_PROFILE_UPDATED:8},hs=Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},ls),{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:ds,GROUP_TIPS_OPERATION_TYPE:ps}),gs=Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},Xt),os),rs),cs),us),hs),{IOS_OFFLINE_PUSH_NO_SOUND:"push.no_sound",IOS_OFFLINE_PUSH_DEFAULT_SOUND:"default"}),{NET_STATE_CONNECTING:"connecting",NET_STATE_DISCONNECTED:"disconnected"}),_s={NO_SDKAPPID:2e3,NO_TINYID:2022,NO_A2KEY:2023,USER_NOT_LOGGED_IN:2024,REPEAT_LOGIN:2025,MSG_SEND_FAIL:2100,MSG_SEND_FAIL_NOT_IN_AV:2101,MSG_SEND_GRP_WITH_TOPIC_FAIL:2115,MSG_INSTANCE_REQUIRED:2105,MSG_INVALID_CONV_TYPE:2106,MSG_REVOKE_FAIL:2110,MSG_DELETE_FAIL:2111,MSG_UNREAD_ALL_FAIL:2112,READ_RECEIPT_MSG_LIST_EMPTY:2114,CANNOT_DELETE_GRP_SYSTEM_NOTICE:2116,NOT_MY_FRIEND:2700,NETWORK_ERROR:2800,NETWORK_TIMEOUT:2801,NO_NETWORK:2805,UNCAUGHT_ERROR:2903,INVALID_OPERATION:2905,SDK_IS_NOT_READY:2999,LOGGING_IN:3e3,LOGIN_FAILED:3001,KICKED_OUT_MULT_DEVICE:3002,KICKED_OUT_MULT_ACCOUNT:3003,KICKED_OUT_USERSIG_EXPIRED:3004,LOGGED_OUT:3005,KICKED_OUT_REST_API:3006,NO_USE:3122,OPTIONS_IS_EMPTY:3153,MSG_A2KEY_EXPIRED:20002,ACCOUNT_A2KEY_EXPIRED:70001,HELLO_ANSWER_KICKED_OUT:1002,OPEN_SERVICE_OVERLOAD_ERROR:60022},ms={BASIC:"1",STANDARD:"2",PROFESSIONAL:"3"},vs={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"},fs={USER_STATUS_UPDATE:"user-status-update",CONVERSATION_RECOVER:"conversation-recover",HISTORY_MESSAGE_RECOVER:"history-message-recover",BLACKLIST_RECOVER:"blacklist-recover",FRIEND_RECOVER:"friend-recover",GROUP_ATTRIBUTE_CACHE_CLEAR:"group-attribute-cache-clear",UNREAD_MESSAGE_RECOVER:"unread-message-recover",HANDLE_NEW_MESSAGE:"handle-new-message",HANDLE_CONVERSATION_PROFILE_UPDATED:"handle-conversation-profile-updated",COMMERCIAL_CONFIG_UPDATE:"commercial-config-update",UNREAD_MESSAGE_SYNC:"unread-message-sync",FRIEND_AND_BLACKLIST_SYNC:"friend-and-blacklist-sync",SIGNALING_MESSAGE_RECOVER:"signaling-message-recover",GROUP_LIST_SYNC:"group-list-sync",CONVERSATION_LIST_SYNC:"conversation-list-sync",USER_PROFILE_SYNC:"user-profile-sync",CONVERSATION_UPDATE_AFTER_UNREAD_SYNC_FINISHED:"conversation-update-after-unread-sync-finished",CONVERSATION_UPDATE_AFTER_GROUP_LIST_SYNC_FINISHED:"conversation-update-after-group-list-sync-finished",HANDLE_C2C_NEW_MESSAGE:"handle-c2c-new-message",HANDLE_GROUP_NEW_MESSAGE:"handle-group-new-message",CREATE_OR_UPDATE_CONVERSATION_BY_RECEIVE_NEW_MESSAGE:"create-or-update-conversation-by-receive-new-message",HANDLE_GROUP_TIPS_FROM_SYNC_UNREAD:"handle-group-tips-from-sync-unread",HANDLE_C2C_REVOKED_MESSAGE_FROM_SYNC_UNREAD:"handle-c2c-revoked-message-from-sync-unread",GROUP_REVOKED_NOTICE_RECOVER:"group-revoked-notice-recover",CLOUD_CONFIG_SYNC:"cloud-config-sync",UPDATE_GROUP_NEXT_SEQUENCE:"update-group-next-sequence",EMIT_C2C_MESSAGE_EVENT:"emit-c2c-message-event",EMIT_GROUP_MESSAGE_EVENT:"emit-group-message-event",CONVERSATION_GROUP_LIST_SYNC:"conversation-group-list-sync",CONVERSATION_GROUP_UPDATE:"conversation-group-update",UPDATE_TOPIC_AFTER_UNREAD_SYNC_FINISHED:"update-topic-after-unread-sync-finished",UPDATE_TOPIC_BY_RECEIVE_NEW_MESSAGE:"update-topic-by-received-new-message",TOPIC_REQUEST_INFO_RESET:"topic-request-info-reset",QUALITY_REPORT:"quality-report",GROUP_TIPS_RECOVER:"group-tips-recover"},Is={[vs.SYNC_SERVER_INFO_AFTER_RE_ONLINE]:[{stepId:fs.USER_STATUS_UPDATE},{stepId:fs.GROUP_ATTRIBUTE_CACHE_CLEAR},{stepId:fs.UNREAD_MESSAGE_SYNC},{stepId:fs.CONVERSATION_RECOVER},{stepId:fs.HISTORY_MESSAGE_RECOVER,dependency:fs.CONVERSATION_RECOVER},{stepId:fs.BLACKLIST_RECOVER},{stepId:fs.FRIEND_RECOVER},{stepId:fs.GROUP_REVOKED_NOTICE_RECOVER,dependency:fs.HISTORY_MESSAGE_RECOVER},{stepId:fs.GROUP_TIPS_RECOVER,dependency:fs.HISTORY_MESSAGE_RECOVER},{stepId:fs.TOPIC_REQUEST_INFO_RESET},{stepId:fs.HANDLE_C2C_REVOKED_MESSAGE_FROM_SYNC_UNREAD,dependency:fs.UNREAD_MESSAGE_SYNC},{stepId:fs.HANDLE_GROUP_TIPS_FROM_SYNC_UNREAD,dependency:fs.UNREAD_MESSAGE_SYNC},{stepId:fs.CONVERSATION_UPDATE_AFTER_UNREAD_SYNC_FINISHED,dependency:[fs.UNREAD_MESSAGE_SYNC,fs.CONVERSATION_RECOVER]},{stepId:fs.EMIT_C2C_MESSAGE_EVENT,dependency:[fs.UNREAD_MESSAGE_SYNC,fs.CONVERSATION_UPDATE_AFTER_UNREAD_SYNC_FINISHED],skipIfDependencyMissing:!1}],[vs.SYNC_SERVER_INFO_AFTER_LOGIN]:[{stepId:fs.COMMERCIAL_CONFIG_UPDATE},{stepId:fs.CLOUD_CONFIG_SYNC},{stepId:fs.USER_PROFILE_SYNC},{stepId:fs.UNREAD_MESSAGE_SYNC},{stepId:fs.FRIEND_AND_BLACKLIST_SYNC},{stepId:fs.GROUP_LIST_SYNC},{stepId:fs.CONVERSATION_LIST_SYNC},{stepId:fs.SIGNALING_MESSAGE_RECOVER,dependency:fs.UNREAD_MESSAGE_SYNC},{stepId:fs.UPDATE_TOPIC_AFTER_UNREAD_SYNC_FINISHED,dependency:[fs.UNREAD_MESSAGE_SYNC]},{stepId:fs.CONVERSATION_UPDATE_AFTER_UNREAD_SYNC_FINISHED,dependency:[fs.UNREAD_MESSAGE_SYNC,fs.CONVERSATION_LIST_SYNC]},{stepId:fs.CONVERSATION_UPDATE_AFTER_GROUP_LIST_SYNC_FINISHED,dependency:[fs.GROUP_LIST_SYNC,fs.CONVERSATION_LIST_SYNC]},{stepId:fs.CONVERSATION_GROUP_LIST_SYNC},{stepId:fs.CONVERSATION_GROUP_UPDATE,dependency:[fs.CONVERSATION_LIST_SYNC,fs.CONVERSATION_GROUP_LIST_SYNC]},{stepId:fs.QUALITY_REPORT}],[vs.RECEIVE_C2C_NEW_MESSAGE]:[{stepId:fs.HANDLE_C2C_NEW_MESSAGE},{stepId:fs.UNREAD_MESSAGE_SYNC},{stepId:fs.CREATE_OR_UPDATE_CONVERSATION_BY_RECEIVE_NEW_MESSAGE,dependency:fs.HANDLE_C2C_NEW_MESSAGE},{stepId:fs.EMIT_C2C_MESSAGE_EVENT,dependency:[fs.HANDLE_C2C_NEW_MESSAGE,fs.CREATE_OR_UPDATE_CONVERSATION_BY_RECEIVE_NEW_MESSAGE],skipIfDependencyMissing:!1},{stepId:fs.CONVERSATION_UPDATE_AFTER_UNREAD_SYNC_FINISHED,dependency:[fs.UNREAD_MESSAGE_SYNC]}],[vs.RECEIVE_GROUP_NEW_MESSAGE]:[{stepId:fs.HANDLE_GROUP_NEW_MESSAGE},{stepId:fs.CREATE_OR_UPDATE_CONVERSATION_BY_RECEIVE_NEW_MESSAGE,dependency:fs.HANDLE_GROUP_NEW_MESSAGE},{stepId:fs.UPDATE_GROUP_NEXT_SEQUENCE,dependency:fs.HANDLE_GROUP_NEW_MESSAGE},{stepId:fs.UPDATE_TOPIC_BY_RECEIVE_NEW_MESSAGE,dependency:fs.HANDLE_GROUP_NEW_MESSAGE},{stepId:fs.EMIT_GROUP_MESSAGE_EVENT,dependency:[fs.HANDLE_GROUP_NEW_MESSAGE,fs.CREATE_OR_UPDATE_CONVERSATION_BY_RECEIVE_NEW_MESSAGE],skipIfDependencyMissing:!1}]},Ss={MESSAGE_SEND_SUCCESS_RATE:"messageSendSuccessRate"},Es={TOTAL_COUNT:"sendMessageTotalCount",SUCCESS_COUNT:"sendMessageSuccessCount",FAILED_COUNT:"sendMessageFailedCount",SEND_COST:"sendMessageCost"};var Ms,ys,As,Cs=Object.freeze({__proto__:null,ERROR_CODE:_s,InnerEvent:Jt,OuterConstant:gs,OuterEvent:Yt,QUALITY_METRICS:Ss,SDK_EDITION:ms,SDK_INFO:{VERSION:"1.7.3",APPID:537048168},SEND_MESSAGE_STAT:Es,SignalingEvent:Qt,WORKFLOW_DEFINITIONS:Is,WORKFLOW_NAME:vs,WORKFLOW_STEP:fs});!function(e){e[e.USER_INITIATED=0]="USER_INITIATED",e[e.KICKED_OUT=1]="KICKED_OUT"}(Ms=Ms||{}),function(e){e[e.multipleAccount=1]="multipleAccount",e[e.multipleDevice=2]="multipleDevice",e[e.restApi=3]="restApi"}(ys=ys||{}),function(e){e[e.multipleDevice=3002]="multipleDevice",e[e.multipleAccount=3003]="multipleAccount",e[e.usersigExpired=70001]="usersigExpired",e[e.restApi=20002]="restApi"}(As=As||{});let Ts={[ys.multipleAccount]:"multipleAccount",[ys.multipleDevice]:"multipleDevice",[ys.restApi]:"REST_API_Kick",[As.multipleAccount]:"multipleAccount",[As.multipleDevice]:"multipleDevice",[As.restApi]:"REST_API_Kick",[As.usersigExpired]:"userSigExpired"},Os="login_online_presence_task",{ERROR:Ds,DESTROY:Rs,FORCE_OFFLINE:Ls}=Jt,{KICKED_OUT_MULT_ACCOUNT:Ns,KICKED_OUT_MULT_DEVICE:bs,KICKED_OUT_REST_API:Gs,ACCOUNT_A2KEY_EXPIRED:ws,MSG_A2KEY_EXPIRED:Ps}=_s;class Us{init(){var e=Bt["notificationCenter"];e.subscribeInnerEvent(Ls,this._handleForceOfflineFromServerPush,this),e.subscribeInnerEvent(Ds,Ps,this._handleForceOfflineFromResponse,this),e.subscribeInnerEvent(Ds,ws,this._handleForceOfflineFromResponse,this),e.subscribeInnerEvent(Ds,Ns,this._handleForceOfflineFromResponse,this),e.subscribeInnerEvent(Ds,bs,this._handleForceOfflineFromResponse,this),e.subscribeInnerEvent(Ds,Gs,this._handleForceOfflineFromResponse,this),e.subscribeInnerEvent(Rs,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{this._logKickedOutEvent(t),yield Bt.login.loginAction.logout(Ms.KICKED_OUT)}catch(e){console.debug(e)}finally{Bt.notificationCenter.emitOuterEvent(Yt.KICKED_OUT,{data:{type:Ts[e]},name:Yt.KICKED_OUT}),[ys.restApi,ws,Ps].includes(e)&&Bt.channel.reconnect()}})}_logKickedOutEvent(e){var{kickedOutReasonCode:e,newInstanceInfo:t={}}=e,s=Bt.ssoLog.createSSOLogData({method:"kickedOut"}),e=`type:${Ts[e]} newInstanceInfo: `+JSON.stringify(t);s.setLogInfo({message:e}).end(!0),console.warn("loginModule."+e)}_isKickedOut(e){return[ys.multipleAccount,ys.multipleDevice,ys.restApi].includes(e)}_dispose(){var e=Bt["notificationCenter"];e.unSubscribeInnerEvent(Ls,this._handleForceOfflineFromServerPush,this),e.unSubscribeInnerEvent(Ds,ws,this._handleForceOfflineFromResponse,this),e.unSubscribeInnerEvent(Ds,Ps,this._handleForceOfflineFromResponse,this),e.unSubscribeInnerEvent(Ds,Ns,this._handleForceOfflineFromResponse,this),e.unSubscribeInnerEvent(Ds,bs,this._handleForceOfflineFromResponse,this),e.unSubscribeInnerEvent(Ds,Gs,this._handleForceOfflineFromResponse,this),e.unSubscribeInnerEvent(Rs,this._dispose,this)}}function ks(){return h(this,void 0,void 0,function*(){let e="im_open_status.wslogin",t=Bt.common.generateProtocolData({servcmd:e,data:{state:"Online",isWebUniapp:0,InstType:0,customInfo:""}}),s=""+t.head.seq+e;try{let d=yield Bt.channel.sendPacket(t,{timeout:9e4,requestId:s});if(d){let{HelloInterval:e,InstId:t,TinyId:s,TimeStamp:r,CustomStatus:n,PurchaseBits:o,A2Key:i,RichMsgAuthKey:a,ErrorCode:l,ErrorInfo:c,ActionStatus:u}=d;return{helloInterval:e,instanceID:t,tinyID:s,timeStamp:r,customStatus:n,purchaseBits:o,a2Key:i,authKey:a,errorCode:l,errorInfo:c,actionStatus:u}}}catch(e){throw console.warn(e),e}})}function Fs(t){var s;try{var r=be.getStorage("errorMessage");if(!t||!r)return"";var n=(null==(s=JSON.parse(r))?void 0:s.errorMessage)||{},{isIntl:o=!1,code:i,replacement1:a="",replacement2:l=""}=t;if(!i)return"";var c=o?i+"_en":i+"_cn";let e=n[n[c]?c: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 $s extends Error{constructor(e){var{functionName:t="Unknown",code:s,message:r="",data:n=""}=e;let o=r;s&&!r&&(o=Fs(e));r=s?`${t} failed. error: {"message": ${o}, "code": ${s}}`:`${t} failed. error: {"message": ${o}}`;super(),this.code=s,this.errorCode=s,this.errorMessage=r,this.message=r,this.data=n}}function qs(e,t){if(e&&!0!==(null==(e=Bt.store.get("login"))?void 0:e.isLoggedIn))throw new $s({code:_s.USER_NOT_LOGGED_IN,functionName:t})}function xs(t,s,r){if(Array.isArray(t))for(let e=0;e<t.length;e++)Vs.call(this,Object.assign(Object.assign({},t[e]),{value:s[e],name:r}));else for(var e in t)Vs.call(this,Object.assign(Object.assign({},t[e]),{value:s[0][e],name:r,key:e}))}function Vs({required:e,rules:r,value:t,allowEmpty:n,name:o,key:i,customValidator:a}){if(void 0===t){if(e)throw new $s({functionName:o,message:`[${o}] 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 $s({functionName:o,message:e})}if(!1===n){if(Array.isArray(t)&&(0===t.length||"string"==typeof t[0]&&""===t[0].trim()))throw new $s({functionName:o,message:i+" can not be empty."});if("string"==typeof t&&""===t.trim())throw new $s({functionName:o,message:i+" can not be empty."})}if(a&&"function"==typeof a){let e=a(t);if(!0!==e)throw new $s({functionName:o,message:`[${i}] custom validation failed: `+(e||"Invalid value")})}}}let Bs=[],js={},Ks={};function Ws(e,t){var s;qs(js[e],e),xs(Ks[e],t,e),s=e,Bs.forEach(e=>{var{interceptor:e,context:t}=e;e.apply(t,[s])})}function Hs(e,t){Bs.push({interceptor:e,context:t})}function Ys(e){var{params:e,auth:t}=e;e&&"object"==typeof e&&Object.assign(Ks,e),t&&"object"==typeof t&&Object.assign(js,t)}function zs(e){return Bt.store.get("commercialConfig").get(e)}class Js{constructor(){this._handlers=new Map,this._activeWorkflows=new Map,this._stepStartTimes=new Map,this._logHandlers={start:(e,t)=>{var s=Date.now();t?(this._stepStartTimes.set(e+"-"+t,s),console.log(`[Workflow ${e}] Step ${t} started at `+new Date(s).toISOString())):(this._workflowStartTimes.set(e,s),console.log(`[Workflow ${e}] started at `+new Date(s).toISOString()))},success:(s,e)=>{var r=Date.now();if(e){var t=this._stepStartTimes.get(s+"-"+e),t=t?r-t:0;this._stepStartTimes.delete(s+"-"+e),console.log(`[Workflow ${s}] Step ${e} completed successfully at ${new Date(r).toISOString()} (${t}ms)`)}else{let e=this._workflowStartTimes.get(s),t=e?r-e:0;this._workflowStartTimes.delete(s),console.log(`[Workflow ${s}] completed successfully at ${new Date(r).toISOString()} (${t}ms)`)}},error:(s,e,r)=>{var n=Date.now();if(e){var t=this._stepStartTimes.get(s+"-"+e),t=t?n-t:0;this._stepStartTimes.delete(s+"-"+e),console.error(`[Workflow ${s}] Step ${e} failed at ${new Date(n).toISOString()} (${t}ms)`,r)}else{let e=this._workflowStartTimes.get(s),t=e?n-e:0;this._workflowStartTimes.delete(s),console.error(`[Workflow ${s}] failed at ${new Date(n).toISOString()} (${t}ms)`,r)}}}}static getInstance(){return Js._instance||(Js._instance=new Js),Js._instance}static setInstance(e){Js._instance=e}init(){this._initializeWorkflows()}registerWorkflowStep(e,t,s,r){var n;this._handlers.has(e)?Is[e].find(e=>e.stepId===t)?(n=this._handlers.get(e)).has(t)||n.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=Is[i],o={cancelled:!1};this._activeWorkflows.set(i,{cancelToken:o});try{let t=new Map,n=(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:o});yield new Promise((t,s)=>{let r=()=>{o.cancelled?t():this._getExecutableSteps({pendingSteps:n.pendingSteps,completedSteps:n.completedSteps,stepMap:n.stepMap,workflowName:i}).filter(e=>!n.runningSteps.has(e)).forEach(e=>{n.completedSteps.has(e)||n.runningSteps.has(e)||this._executeWorkflowStep(e,n,{onComplete:()=>{0===n.pendingSteps.size?t():0===this._getExecutableSteps({pendingSteps:n.pendingSteps,completedSteps:n.completedSteps,stepMap:n.stepMap,workflowName:i}).filter(e=>!n.runningSteps.has(e)).length&&0===n.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,c){return h(this,void 0,void 0,function*(){let{workflowName:o,runningSteps:e,stepMap:s,stepResults:r,data:n}=l;e.add(a),this._logWorkflowExecution(o,a,"start");try{let e=s.get(a),t=null;null!=e&&e.dependency&&(_(e.dependency)?t=r[e.dependency]:Array.isArray(e.dependency)&&(t={},e.dependency.forEach(e=>{t[e]=r[e]})));var i=this._handlers.get(o).get(a);if(i){let e=yield Promise.resolve(i({data:n,result:t}));r[a]=e,this._logWorkflowExecution(o,a,"success")}l.completedSteps.add(a)}catch(e){let t=`[Workflow].${o}.`+a,{errorCode:s,errorInfo:r=t+" failed"}=e||{},n=new $s({functionName:t,code:s,message:r});Bt.ssoLog.createSSOLogData({method:"Workflow"}).setLogInfo({message:`workflowName: ${o}, stepId: `+a}).setError(n).end(),this._logWorkflowExecution(o,a,"error",e),c.onError(e)}finally{e.delete(a),l.pendingSteps.delete(a),c.onStepComplete(),c.onComplete()}})}reset(){this._cancelAllWorkflows()}destroy(){this.reset(),this._handlers.clear()}_initializeWorkflows(){Object.keys(Is).forEach(e=>{this._handlers.has(e)||this._handlers.set(e,new Map)})}_cancelWorkFlow(e){var t=this._activeWorkflows.get(e);t&&(t=t["cancelToken"],t.cancelled=!0,this._activeWorkflows.delete(e))}_cancelAllWorkflows(){Object.keys(Is).forEach(e=>{this._cancelWorkFlow(e)})}_validateWorkflow(e){return Is[e]?!!this._handlers.get(e)||(console.debug(`No handlers registered for workflow '${e}'`),!1):(console.debug(`Workflow '${e}' not defined`),!1)}_getExecutableSteps(e){let{pendingSteps:t,completedSteps:s,stepMap:r,workflowName:n}=e;return Array.from(t).filter(e=>{var{dependency:t,skipIfDependencyMissing:e=!0}=r.get(e)||{};if(!t)return!0;if(_(t))return this._isStepRegistered({workflowName:n,stepId:t})?s.has(t):!e;if(v(t)){if(0<t.filter(e=>!this._isStepRegistered({workflowName:n,stepId:e})).length&&e)return!1;for(let e of t)if(!s.has(e))return!1;return!0}return!1})}_isStepRegistered(e){var{workflowName:e,stepId:t}=e;return null==(e=this._handlers.get(e))?void 0:e.has(t)}_logWorkflowExecution(e,t,s,r){this._logHandlers[s](e,t)}}let Qs=new Map,Xs=({type:e,groupID:t})=>e===gs.GRP_COMMUNITY||(""+t).startsWith(ds.COMMUNITY)&&!(""+t).includes(ds.TOPIC),Zs=(e="")=>{e=e.startsWith("GROUP")?e.replace("GROUP",""):e;return e.startsWith(ds.COMMUNITY)&&(""+e).includes(ds.TOPIC)},eo="openim",to="million_group_open_http_svc";function so(s){return h(this,void 0,void 0,function*(){var{servcmd:e,data:t}=oo(e=s.data)||no(e)?function(e){let{servcmd:t,data:s}=e;var r,n,o;return no(s)?({servcmd:e,data:r}=e,{GroupId:n=""}=r,[n]=(o=n).split(ds.TOPIC),{servcmd:io(e),data:Object.assign(Object.assign({},r),{GroupId:n,TopicId:o})}):{servcmd:t=oo(s)?io(t):t,data:s}}(s):s,t=Bt.common.generateProtocolData({servcmd:e,data:t}),e=""+t.head.seq+e;return Bt.channel.sendPacket(t,{requestId:e})})}function oo(e){var{Type:e,GroupId:t,GroupIdList:s=[]}=e,t=t||s[0]||"";return Xs({type:e,groupID:t})}function no(e){var{GroupId:e=""}=e;return Zs(e)}function io(e){return e.includes(eo)?e:(e=e.split(".")[1],to+"."+e)}function ro(){var e;return null==(e=Bt.store.get("login"))?void 0:e.userId}let ao=e=>v(e)||f(e),co=(s,r,n,o)=>{if(!ao(s)||!ao(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],!(g(r[a])||n&&n.includes(a)))if(ao(s[a])&&ao(r[a]))i+=co(s[a],r[a],n,o);else{if(o&&o.includes(r[a]))continue;s[a]!==r[a]&&(s[a]=r[a],i+=1)}return i},uo=(e,t)=>{if(g(t))return"";switch(e){case gs.MSG_TEXT:return t.text||"";case gs.MSG_IMAGE:return"[Image]";case gs.MSG_LOCATION:return"[Location]";case gs.MSG_AUDIO:return"[Voice]";case gs.MSG_VIDEO:return"[Video]";case gs.MSG_FILE:return"[File]";case gs.MSG_CUSTOM:return"[Custom Messages]";case gs.MSG_GRP_TIP:return"[Group Notification]";case gs.MSG_GRP_SYS_NOTICE:return"[Group System Message]";case gs.MSG_FACE:return"[Animated Sticker]";case gs.MSG_MERGER:return"[Chat Record]";default:return""}},lo=[{cmd:"ws_get_user_status",interval:5,count:20},{cmd:"ws_status_subscribe",interval:5,count:20},{cmd:"ws_status_unsubscribe",interval:5,count:20},{cmd:"get_group_self_member_info",interval:5,count:20},{cmd:"modify_group_base_info",interval:1,count:8},{cmd:"get_pendency",interval:1,count:15},{cmd:"set_group_attr",interval:5,count:10},{cmd:"modify_group_attr",interval:5,count:10},{cmd:"delete_group_attr",interval:5,count:10},{cmd:"clear_group_attr",interval:5,count:10},{cmd:"get_group_attr",interval:5,count:20},{cmd:"update_group_counter",interval:5,count:20},{cmd:"get_group_counter",interval:5,count:20},{cmd:"get_topic",interval:1,count:10},{cmd:"read_all_unread_msg",interval:1,count:1},{cmd:"query",interval:5,count:20}],po="im_sdk_config_mgr.fetch_config",ho="im_sdk_config_mgr.push_configv2",go="cloud-config",_o=2996;var mo=new class{constructor(){this._core=null,this._expirationTime=0,this._version=0,this._isFetching=!1,this._cmdFrequencyLimitMap=new Map,this._methodCallFrequencyMap=new Map}install(e){var{notificationCenter:e,InnerEvent:t,helper:s,constants:{WORKFLOW_NAME:r,WORKFLOW_STEP:n},channel:o}=this._core=e;e.subscribeInnerEvent(ho,this._handlePushedConfig,this),s.registerWorkflowStep(r.SYNC_SERVER_INFO_AFTER_LOGIN,n.CLOUD_CONFIG_SYNC,this._handleLoginSuccess,this),e.subscribeInnerEvent(t.LOGOUT,this._reset,this),e.subscribeInnerEvent(t.DESTROY,this._dispose,this),s.registerExperimentalAPI("getServerConfig",this),this._updateCmdFreqLimitMap(lo),o.registerBeforeSendInterceptor(this.checkMethodCallOverLimit,this)}getServerConfig(s){return h(this,void 0,void 0,function*(){var e,t={code:0,data:""};return s&&(t.data=(null==(e=this._core.store.get("cloudConfig"))?void 0:e[s])||""),t})}checkMethodCallOverLimit(e){if(this._cmdFrequencyLimitMap.has(e))if(this._methodCallFrequencyMap.has(e)){var{count:t,interval:s}=this._cmdFrequencyLimitMap.get(e),{startTime:r,methodCallCounter:n}=this._methodCallFrequencyMap.get(e);if(Date.now()-r>1e3*s)this._methodCallFrequencyMap.set(e,{startTime:Date.now(),methodCallCounter:1});else if(this._methodCallFrequencyMap.set(e,{startTime:r,methodCallCounter:n+=1}),t<n)throw new this._core.helper.ChatError({code:_o,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:po,data:{uint32_sdkappid:e,uint64_version:this._version}}),s=""+t.head.seq+po;return yield this._core.channel.sendPacket(t,{requestId:s})}catch(e){throw console.warn("fetch cloudControl fail: ",e),e}})}_handlePushedConfig(e){return h(this,void 0,void 0,function*(){yield this._updateCloudConfig(e)})}_handleLoginSuccess(){return h(this,void 0,void 0,function*(){try{var e;this._canFetch()&&(e=yield this._fetchCloudConfig(),yield this._updateCloudConfig(e)),this._core.helper.taskScheduler.addTask({id:go,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();yield this._updateCloudConfig(e)}catch(e){console.warn(e)}})}_updateCloudConfig(t){return h(this,void 0,void 0,function*(){var e=this._parseCloudConfig(t);e&&(this._core.store.set("cloudConfig",e),yield this._parseCmdFreqLimit(),this._core.notificationCenter.emitInnerEvent(this._core.InnerEvent.CLOUD_CONFIG_UPDATE,e),this._core.notificationCenter.emitOuterEvent(this._core.OuterEvent.SERVER_CONFIG_UPDATED,{name:this._core.OuterEvent.SERVER_CONFIG_UPDATED,data:{config:e}}))})}_canFetch(){var e=(this._core.store.get("login")||{})["isLoggedIn"];return e&&!this._isFetching&&Date.now()>=this._expirationTime}_parseCloudConfig(e){var{int32_error_code:t,str_json_config:s,uint32_expired_time:r,uint64_version:n}=e;let o=null;if(0===t){if(this._version!==n)try{o=JSON.parse(s),this._version=n}catch(e){}this._expirationTime=Date.now()+1e3*r}else this._expirationTime=void 0===t?Date.now()+36e5:Date.now()+12e4;return o}_parseCmdFreqLimit(){return h(this,void 0,void 0,function*(){var e,t=null==(e=yield this.getServerConfig("cmd_frequency_limit"))?void 0:e.data,s=this._core.utils["isEmpty"];if(!s(t))try{t=JSON.parse(t),this._updateCmdFreqLimitMap(t)}catch(e){console.warn(e)}})}_updateCmdFreqLimitMap(e){e.forEach(e=>{this._cmdFrequencyLimitMap.set(e.cmd,{interval:e.interval,count:e.count})})}_reset(){this._core.helper.taskScheduler.removeTask(go),this._core.store.clear("cloudConfig"),this._updateCmdFreqLimitMap(lo),this._methodCallFrequencyMap.clear(),this._expirationTime=0,this._version=0,this._isFetching=!1}_dispose(){var{notificationCenter:e,InnerEvent:t}=this._core;e.unSubscribeInnerEvent(ho,this._handlePushedConfig,this),e.unSubscribeInnerEvent(t.LOGOUT,this._reset,this),e.unSubscribeInnerEvent(t.DESTROY,this._dispose,this),this._reset()}};class vo{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 fo={SEARCH_GRP_SNS:new vo(0,Math.pow(2,1)).toString(),AV_HISTORY_MSG:new vo(0,Math.pow(2,2)).toString(),GRP_COMMUNITY:new vo(0,Math.pow(2,3)).toString(),MSG_TO_SPECIFIED_GRP_MBR:new vo(0,Math.pow(2,4)).toString(),AV_MBR_LIST:new vo(0,Math.pow(2,6)).toString(),USER_STATUS:new vo(0,Math.pow(2,7)).toString(),CONV_MARK:new vo(0,Math.pow(2,9)).toString(),CONV_GROUP:new vo(0,Math.pow(2,10)).toString(),AV_BAN_MBR:new vo(0,Math.pow(2,11)).toString(),MSG_EXT:new vo(0,Math.pow(2,13)).toString(),GRP_COUNTER:new vo(0,Math.pow(2,15)).toString(),PLUGIN_TRANSLATE:new vo(Math.pow(2,6)).toString(),PLUGIN_VOICE_TO_TEXT:new vo(Math.pow(2,7)).toString(),PLUGIN_CS:new vo(Math.pow(2,8)).toString(),PLUGIN_PUSH:new vo(Math.pow(2,9)).toString(),PLUGIN_BOT:new vo(Math.pow(2,10)).toString(),MSG_REACTION:new vo(Math.pow(2,16)).toString(),FOLLOW:new vo(Math.pow(2,20)).toString()},Io="CommercialConfig",So="commercial-config";var To,Oo,Eo=new class{constructor(){this._core=null,this._expirationTime=0,this._isFetching=!1,this._featureMap=new Map,this._methodKeyMap=new Map,this._purchaseBits="0"}install(e){var{helper:t,notificationCenter:s,constants:{WORKFLOW_NAME:r,WORKFLOW_STEP:n,InnerEvent:o}}=this._core=e;s.subscribeInnerEvent(o.COMMERCIAL_CONFIG_PUSH,this._handlePushedConfig,this),s.subscribeInnerEvent(o.LOGOUT,this._handleLogout,this),s.subscribeInnerEvent(o.DESTROY,this._dispose,this),t.registerWorkflowStep(r.SYNC_SERVER_INFO_AFTER_LOGIN,n.COMMERCIAL_CONFIG_UPDATE,this._syncCommercialConfig,this),e.helper.registerExperimentalAPI("isCommercialAbilityEnabled",this),e.helper.registerExperimentalAPI("queryCommercialAbility",this)}isCommercialAbilityEnabled(e){return h(this,void 0,void 0,function*(){var s=parseInt(e,10).toString(2),r=s["length"];let n,o=!0;for(let e=r-1,t=0;0<=e;e--,t++)if("1"===s.charAt(e)&&(n=(t<32?new vo(0,2**t):new vo(2**(t-32),0)).toString(),!this._featureMap.get(n))){o=!1;break}return console.log(`${Io}.isFeatureEnabled decimalNumber:${e} key:${n} ret:`+o),{code:0,data:{enabled:o}}})}queryCommercialAbility(){return this._purchaseBits}_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:So,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,n;"object"==typeof e&&({int32_error_code:t,str_error_message:s,str_purchase_bits:r,uint32_expired_time:n}=e,0===t?(this._parsePurchaseBits(r),this._expirationTime=Date.now()+1e3*n):void 0===t?(console.log(Io+"._parseCommercialConfig failed. Invalid message format:",e),this._expirationTime=Date.now()+36e5):(console.error(Io+`._parseCommercialConfig errorCode:${t} errorMessage:`+s),this._expirationTime=Date.now()+12e4))}_isValidPurchaseBits(e){return e&&"string"==typeof e&&1<=e.length&&e.length<=64&&/[01]{1,64}/.test(e)}_parsePurchaseBits(s){if(this._isValidPurchaseBits(s)){this._purchaseBits=s,this._featureMap.clear(),this._methodKeyMap.clear();var r;for(let e=s.length-1,t=0;0<=e;e--,t++)if(r=(t<32?new vo(0,2**t):new vo(2**(t-32),0)).toString(),"1"===s[e]){this._featureMap.set(r,!0);let e=this._getKeyByValue(fo,r);e&&this._methodKeyMap.set(e,!0)}else{this._featureMap.set(r,!1);let e=this._getKeyByValue(fo,r);e&&this._methodKeyMap.set(e,!1)}}else console.warn(Io+".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(So),this._core.store.set("commercialConfig",{}),this._expirationTime=0,this._isFetching=!1,this._featureMap.clear(),this._purchaseBits="0"}},Co=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)}},Mo=new class{constructor(){this.name="ConfigCenter"}install(e){mo.install(e),Eo.install(e),Co.install(e)}},yo=new class{constructor(){this.name="ErrorMessage",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={},n=new RegExp(/'/g);for(let t=0;t<s.length;t++){var o=s[t].indexOf(":"),i=s[t].slice(0,o);let e=s[t].slice(o+1);i.startsWith("//")||""!==e&&(e=e.replace(n,""),r[i]=e)}return r}}};function Ao(n,l){return h(this,void 0,void 0,function*(){let{cookie:e,syncFlag:t,syncTriggerEvent:s}=n,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:n,revokedMessageList:o}=function(e,S){let r=[],n=[];return null!=e&&e.forEach(I=>{var e,t,s=function(){var{From_Account:e,From_AccountHeadurl:t,From_AccountNick:s,IsNeedReadReceipt:r,MsgBody:n,MsgClientTime:o,MsgRandom:i,MsgSeq:a,MsgTimeStamp:l,SendMsgControl:c,SupportMessageExtension:u,To_Account:d,TinyId:h,MsgCheckResult:p,CloudCustomData:g,IsPeerRead:_,MsgFlagBits:m,MsgVersion:v,EventArray:f}=I;return{from:e,avatar:t,nick:s,needReadReceipt:1===r,readReceiptSentByPeer:_,clientTime:o,messageFlagBits:m,random:i,sequence:a,time:l,messageControlInfo:c,isSupportExtension:u,to:d,tinyID:h,checkResult:p,cloudCustomData:g,messageVersion:v,eventArray:f,elements:S.message.messageHelper.parseServerPushMessageElement(n)}}();if(null!=(t=null==(e=null==(e=null==I?void 0:I.EventArray)?void 0:e[0])?void 0:e.hasOwnProperty)&&t.call(e,"C2cNotifyMsgArray"))n.push(...function(){let e,t=[];return null!=(e=I.EventArray)&&e.forEach(e=>{var e=e["C2cNotifyMsgArray"],e=null==(e=null==(e=null==e?void 0:e[0])?void 0:e.WithdrawC2cMsgNotify)?void 0:e.C2cWithdrawInfoArray;Array.isArray(e)&&t.push(...e)}),t}());else{let e=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:n}}(e.MsgList,l);return{syncFlag:null==e?void 0:e.SyncFlag,unreadMessageList:n,revokedMessageList:o,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"}(To=To||{}),function(e){e[e.LOGIN_SUCCESS=0]="LOGIN_SUCCESS",e[e.NEW_MESSAGE_RECEIVED=1]="NEW_MESSAGE_RECEIVED"}(Oo=Oo||{});var Do=new class{constructor(){this.name="UnreadMessageSynchronizer",this._unreadDBMessageMap=new Map,this._cookie=""}install(e){var t=(this._core=e)["constants"];e.helper.registerWorkflowStep(t.WORKFLOW_NAME.SYNC_SERVER_INFO_AFTER_RE_ONLINE,t.WORKFLOW_STEP.UNREAD_MESSAGE_SYNC,this._syncUnreadDBMessageAfterReOnline,this),e.helper.registerWorkflowStep(t.WORKFLOW_NAME.RECEIVE_C2C_NEW_MESSAGE,t.WORKFLOW_STEP.UNREAD_MESSAGE_SYNC,this._syncUnreadDBMessageAfterNewMessageReceived,this),e.helper.registerWorkflowStep(t.WORKFLOW_NAME.SYNC_SERVER_INFO_AFTER_LOGIN,t.WORKFLOW_STEP.UNREAD_MESSAGE_SYNC,this._syncUnreadDBMessageAfterLogin,this),e.notificationCenter.subscribeInnerEvent(e.InnerEvent.LOGOUT,this._reset,this),e.notificationCenter.subscribeInnerEvent(e.InnerEvent.DESTROY,this._dispose,this)}_syncUnreadMessage(t){return h(this,void 0,void 0,function*(){let{isAfterReOnline:i=!1,isAfterNewMessageReceived:a=!1,isAfterLogin:e=!1}=t||{},l=To.START_SYNC;for(var c=[],u=[],d=[],h=[];this._canContinueSync({cookie:this._cookie,syncFlag:l});){let e=yield this._fetchUnreadDBMessage({cookie:this._cookie,syncFlag:l,syncTriggerEvent:a?Oo.NEW_MESSAGE_RECEIVED:Oo.LOGIN_SUCCESS});if(!e)break;let{unreadMessageList:t=[],revokedMessageList:s=[],overflowUnreadCountList:r,unreadCountList:n,groupTipList:o}=e;if(this._cookie=(null==e?void 0:e.cookie)||"",l=null==e?void 0:e.syncFlag,this._parseAndSaveUnreadMessageList(t),d.push(...s),this._updateConversationUnreadOptions({unreadCountList:n,overflowUnreadCountList:r,conversationUpdateFieldList:c}),Array.isArray(o)&&u.push(...o),i){let e=this._handleNewMessageList(t)["messages"];h.push(...e)}}return i?{conversationUpdateFieldList:c,revokedMessageList:d,unreadMessageMap:this._unreadDBMessageMap,groupTipList:u,messages:h}:{conversationUpdateFieldList:c,isInstantMessage:!e,isUnreadC2CMessage:!0,revokedMessageList:d,unreadMessageMap:this._unreadDBMessageMap,groupTipList:u}})}_syncUnreadDBMessageAfterLogin(){return h(this,void 0,void 0,function*(){return this._cookie="",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:n,CONV_SYSTEM:o}}=this._core["constants"];null!=t&&t.forEach(e=>{let{From_Account:t,UnreadCount:s}=e;if(t!==o){let e=r.find(({conversationID:e})=>e===""+n+t);e?e.unreadCount=s:r.push({conversationID:""+n+t,unreadCount:s,type:n})}}),null!=s&&s.forEach(e=>{let{From_Account:t,LastMsgTime:s}=e;t===o||r.find(({conversationID:e})=>e===""+n+t)||r.push({conversationID:""+n+t,type:n,lastMsgTime:s})})}_syncUnreadDBMessageAfterReOnline(){return h(this,void 0,void 0,function*(){return this._syncUnreadMessage({isAfterReOnline:!0})})}_updateMessageProfile(r){var e;let n=(this._core.message||{})["messageDataHandler"],t=null==(e=this._core.store.get("login"))?void 0:e.userId,{from:s,nick:o,avatar:i,conversationID:a=""}=r;if(s!==t){let s=n.getLatestMsgSentByPeer(a);if(s){let{nick:e,avatar:t}=s;o&&i?o===e&&i===t||n.updateNickAndAvatarOfSentMessage({conversationID:a,latestNick:o,latestAvatar:i,isSentByMe:!1}):(r.nick=e,r.avatar=t)}}else{let e=n.getLatestMsgSentByMe(a);!e||o===e.nick&&i===e.avatar||n.updateNickAndAvatarOfSentMessage({conversationID:a,latestNick:o,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:n,_isExcludedFromLastMessage:o}=a,i=o?"":a;l.has(e)?(l.get(e).lastMessage=i,"in"!==r||n||l.get(e).unreadCount++):l.set(e,{conversationID:e,type:t,subType:s,unreadCount:n||"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,n,o,i,a=yield Ao(l,this._core);return a?({syncFlag:e,unreadMessageList:t,revokedMessageList:s,cookie:r,unreadCountList:n,overflowUnreadCountList:o,groupTipList:i}=a,this._parseAndSaveUnreadMessageList(t),{syncFlag:e,cookie:r,unreadMessageList:t,revokedMessageList:s,unreadCountList:n,overflowUnreadCountList:o,groupTipList:i}):null}catch(e){console.log(e)}})}_canContinueSync({cookie:e,syncFlag:t}){return t===To.START_SYNC||t===To.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()}},Ro=new class{init(e){this._core=e,this._visibilityChangeHandler=this._handleVisibilityChange.bind(this),e.notificationCenter.subscribeInnerEvent(e.InnerEvent.DESTROY,this._dispose,this),null!==document&&void 0!==document&&document.addEventListener("visibilitychange",this._visibilityChangeHandler),null!=(e=this._core)&&e.store.set("activityMonitor",{isActive:!0})}_handleVisibilityChange(){var e,t="visible"===document.visibilityState;null!=(e=this._core)&&e.store.set("activityMonitor",{isActive:t}),null!=(e=this._core)&&e.notificationCenter.emitInnerEvent("activityStatusChange",{isActive:t})}_reset(){var e;null!=(e=this._core)&&e.store.clear("activityMonitor")}_dispose(){document.removeEventListener("visibilitychange",this._visibilityChangeHandler);var{notificationCenter:e,InnerEvent:t}=this._core;e.unSubscribeInnerEvent(t.DESTROY,this._dispose,this),this._reset()}},Lo=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()}},No=new class{init(e){var{IN_WX_MINI_APP:t,IN_WX_MINI_PLUGIN:s}=e.helper;s||(t?Lo:Ro).init(e)}};let bo="none",Go="online";var wo=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:Go})}_onOffline(){this._onNetworkStatusChange({isConnected:!1,networkType:bo})}_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()}},Po=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{var{MINI_APP_NAMESPACE:e}=this._core["utils"];this._mpNetworkStatusCallback=this._onNetworkStatusChange.bind(this),e.onNetworkStatusChange(this._onNetworkStatusChange.bind(this))}catch(e){console.error(e)}})}_deactivateNetworkMonitoring(){var e;null!==this._mpNetworkStatusCallback&&({MINI_APP_NAMESPACE:e}=this._core["utils"],e.offNetworkStatusChange&&e.offNetworkStatusChange(this._mpNetworkStatusCallback),this._mpNetworkStatusCallback=null)}_onNetworkStatusChange(e){var t,{isConnected:e,networkType:s}=e;null!=(t=this._core)&&t.store.set("netWorkMonitor",{isNetworkOnline:e,networkType:s}),null!=(t=this._core)&&t.notificationCenter.emitInnerEvent("networkStatusChange",{isNetworkOnline:e,networkType:s})}_reset(){var e;this._deactivateNetworkMonitoring(),null!=(e=this._core)&&e.store.clear("netWorkMonitor")}_dispose(){var e;null!=(e=this._core)&&e.notificationCenter.unSubscribeInnerEvent(null==(e=this._core)?void 0:e.InnerEvent.DESTROY,this._dispose,this),this._reset()}},Uo=new class{init(e){var t=e.utils["IN_MINI_APP"];(t?Po:wo).init(e)}},ko=new class{constructor(){this.name="SystemStateMonitor"}install(e){No.init(e),Uo.init(e)}};let Fo=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.*"]),$o="tui_room_svr.*";var qo=new class{constructor(){this.name="BusinessCommandTransfer",this._transferredCommands=Fo}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=$o}=s||{};if(this._isValidTransferredCommand(e))return{code:0,data:(yield function(o,i){return h(this,void 0,void 0,function*(){var{helper:e,channel:t}=i,{serviceCommand:s=$o,data:r}=o||{};let n={};try{n="string"==typeof r?JSON.parse(r):r}catch(e){console.warn(e)}r=e.generateProtocolData({servcmd:s,data:n}),e=""+r.head.seq+s;return t.sendPacket(r,{requestId:e})})}(s,this._core))||{}};throw new this._core.helper.ChatError({code:2995,functionName:t})}catch(e){throw console.warn(e),new this._core.helper.ChatError({code:null==e?void 0:e.errorCode,message:null==e?void 0:e.errorInfo,data:{},functionName:t})}})}_onCloudConfigUpdate(e={}){try{var t;"string"==typeof e.rtc_cmd&&(t=JSON.parse(e.rtc_cmd),Array.isArray(t))&&(this._transferredCommands=new Set([...this._transferredCommands,...t]))}catch(e){console.log(e)}}_isValidTransferredCommand(e=""){e=`${null==e?void 0:e.split(".")[0]}.*`;return this._transferredCommands.has(e)}_onServerPushBusinessCommand(e){var{OuterEvent:t,notificationCenter:s}=this._core,e=(e||{})["MsgContent"],t=t["ROOM_CUSTOM_DATA_RECEIVED"];s.emitOuterEvent(t,{name:t,data:e})}_reset(){this._transferredCommands=Fo}_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 xo=1,Vo=2,Bo=3,jo=4,Ko=5,Wo="TIMCustomElem",Ho="C2C",Yo="GROUP",zo="invite",Jo="accept",Qo="cancel",Xo="reject",Zo="modifyInvitation",en="signaling",tn=8010,sn="signaling-timeout";function on(e){return e.filter(e=>{var t,s;return e.type===Wo&&({cloudCustomData:e="",payload:{data:s=""}={}}=e,e=e.match(/"type":"tsignaling"/),t=s.match(/inviteID/),s=s.match(/actionType/),e||t&&s)})}function nn(e){var t=e.payload["data"];try{return JSON.parse(t)}catch(e){return console.error(e),null}}function rn(e,t){return e.toString(16).padStart(t,"0")}function an(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 cn=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=en+".isInvitationValid",{inviteID:e,groupID:s,inviter:r}=e,r=r===this._core.common.getCurrentUserID();if(!this._onlineSignalingMap.has(e))return!1;var n=this._onlineSignalingMap.get(e)["inviteeList"];if(console.log(t+` inviteID:${e} inviteeList:${n} groupID:`+s),s){if(r)return 0<n.length;let e=this._core.common.getCurrentUserID();return n.includes(e)}return!0}updateSignaling(e){let s=en+".updateSignaling",{inviteID:r,inviter:t,inviteeList:n,groupID:o}=e;if(console.log(s+` inviteID:${r} inviter:${t} groupID:`+o),o&&this.hasSignaling(r)){let e=n[0],t=this._onlineSignalingMap.get(r)["inviteeList"];t.includes(e)&&(t.splice(t.indexOf(e),1),console.log(s+` remove ${e}. localInviteeList.length:`+t.length)),0===t.length&&this.removeSignaling(r)}else this.removeSignaling(r)}setSignalingListenStatus(e){this._isSignalingListening=e}getSignalingListenStatus(){return this._isSignalingListening}_dispose(){var e;this._reset(),null!=(e=this._core)&&e.notificationCenter.unSubscribeInnerEvent(this._core.InnerEvent.DESTROY,this._dispose,this),null!=(e=this._core)&&e.notificationCenter.unSubscribeInnerEvent(this._core.InnerEvent.LOGOUT,this._reset,this),this._isSignalingListening=!1}_reset(){this._onlineSignalingMap.clear()}},un=new class{init(e){this._core=e}createInviteSignaling(e){var t=this._generateInviteID(),t=this._createInviteSignalingData(Object.assign(Object.assign({},e),{inviteID:t})),{groupID:s,inviteeList:r}=t,s=s||r[0];return{signaling:this._createSignaling(t,s),signalingData:t,signalingExtensionOptions:this._createSignalingExtensionOptions(e)}}createAcceptSignaling(e){var t=this._createAcceptSignalingData(e),{groupID:s,inviter:r}=t;return{signaling:this._createSignaling(t,s||r),signalingData:t,signalingExtensionOptions:this._createSignalingExtensionOptions(e)}}createCancelSignaling(e){var t=this._createCancelSignalingData(e),{groupID:s,inviteeList:r}=t,s=s||r[0];return{signaling:this._createSignaling(t,s),signalingData:t,signalingExtensionOptions:this._createSignalingExtensionOptions(e)}}createRejectSignaling(e){var t=this._createRejectSignalingData(e),{groupID:s,inviter:r}=t;return{signaling:this._createSignaling(t,s||r),signalingData:t,signalingExtensionOptions:this._createSignalingExtensionOptions(e)}}createTimeoutSignaling(e){var{isInviter:t=!1}=e,e=this._createTimeoutSignalingData(e),{groupID:s,inviteeList:r,inviter:n}=e,s=s||(t?r[0]:n);return{signaling:this._createSignaling(e,s),signalingData:e,signalingExtensionOptions:this._createSignalingExtensionOptions(e)}}_createSignalingExtensionOptions(e){var{data:e="",onlineUserOnly:t,inviteID:s="",offlinePushInfo:r,actionType:n}=e,s=(null==(s=null==(s=cn.getSignaling(s))?void 0:s.signaling)?void 0:s._onlineOnlyFlag)||!1;return{onlineUserOnly:t||s,offlinePushInfo:r,messageControlInfo:this._createMessageControlInfo(e,n)}}_createMessageControlInfo(e,t){t=t===Ko&&!!e.match(/excludeTimeoutSignalingFromHistoryMessage/),e=!!e.match(/excludeFromHistoryMessage/)||!!e.match(/excludeOriginalSignalingFromHistoryMessage/);return{excludedFromContentModeration:!0,excludedFromUnreadCount:t||e,excludedFromLastMessage:t||e}}_createInviteSignalingData(e){var t=en+"._createInviteSignalingData",{userID:s,timeout:r=0,groupID:n="",inviteeList:o=[]}=e,i=this._core.common.getCurrentUserID(),e=Object.assign(Object.assign({},this._generateBaseSignalData(e)),{actionType:xo,inviter:i,inviteeList:n?o:[s],timeout:r});return console.log(t+" signalingData:",e),e}_createAcceptSignalingData(e){var t=en+"._createAcceptSignalingData",s=e["inviteID"],r=this._core.common.getCurrentUserID(),{inviter:s,groupID:n}=cn.getSignaling(s),e=Object.assign(Object.assign({},this._generateBaseSignalData(e)),{actionType:Bo,groupID:n,inviter:s,inviteeList:[r]});return console.log(t+" signalingData:",e),e}_createCancelSignalingData(e){var t=en+"._createCancelSignalingData",s=e["inviteID"],r=this._core.common.getCurrentUserID(),{inviteeList:s,groupID:n}=cn.getSignaling(s),e=Object.assign(Object.assign({},this._generateBaseSignalData(e)),{actionType:Vo,groupID:n,inviter:r,inviteeList:s});return console.log(t+" signalingData:",e),e}_createRejectSignalingData(e){var t=en+"._createRejectSignalingData",s=e["inviteID"],r=this._core.common.getCurrentUserID(),{inviter:s,groupID:n}=cn.getSignaling(s),e=Object.assign(Object.assign({},this._generateBaseSignalData(e)),{actionType:jo,groupID:n,inviter:s,inviteeList:[r]});return console.log(t+" signalingData:",e),e}_createTimeoutSignalingData(e){var t=en+"._createTimeoutSignalingData",{isInviter:s=!1,inviteID:r}=e,{inviteeList:r,inviter:n}=cn.getSignaling(r),o=this._core.common.getCurrentUserID(),e=Object.assign(Object.assign({},this._generateBaseSignalData(e)),{actionType:Ko,inviter:n,inviteeList:s?r:[o]});return console.log(t+" signalingData:",e),e}_createSignaling(e,t){var{groupID:s=""}=e,t={to:t,conversationType:s?Yo:Ho,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[rn(an(32),8),rn(an(16),4),rn(16384|an(12),4),rn(32768|an(14),4),rn(an(48),12)].join("-")}_generateBaseSignalData(e){var{data:e="",inviteID:t="",groupID:s=""}=e;return{businessID:1,timeout:0,data:e,inviteID:t,groupID:s}}},ln=new class{constructor(){this._isProcessingSignaling=!1}init(e){(this._core=e).helper.registerApi({apiName:"invite",context:this}),e.helper.registerApi({apiName:"accept",context:this}),e.helper.registerApi({apiName:"cancel",context:this}),e.helper.registerApi({apiName:"reject",context:this}),e.helper.registerApi({apiName:"modifyInvitation",context:this}),e.helper.registerApi({apiName:"getSignalingInfo",context:this}),e.helper.registerApi({apiName:"addSignalingListener",context:this}),e.helper.registerApi({apiName:"removeSignalingListener",context:this}),e.notificationCenter.subscribeInnerEvent(e.InnerEvent.DESTROY,this._dispose,this),e.notificationCenter.subscribeInnerEvent(e.InnerEvent.LOGOUT,this._reset,this)}invite(t){return h(this,void 0,void 0,function*(){var s;console.log(en+".invite params:"+JSON.stringify(t));try{this._validateBeforeInvite(t);var{signaling:r,signalingData:n,signalingExtensionOptions:e}=un.createInviteSignaling(t),o=yield this._sendSignaling(r,e);if(0!==(null==o?void 0:o.code))return o;{let{inviteID:e,timeout:t}=n;return cn.saveSignaling(e,Object.assign(Object.assign({},n),{signaling:r})),0<t&&(null!=(s=this._core)&&s.helper.taskScheduler.addOnceTask({id:sn+"-"+e,intervalMs:1e3*(t+5),callback:this.handleInvitationExpiryTimer.bind(this,e)})),Object.assign(Object.assign({},o),{inviteID:e})}}catch(e){throw console.error(en+".invite error:"+e),e}})}accept(o){return h(this,void 0,void 0,function*(){console.log(en+".accept params:"+JSON.stringify(o));try{var e=o["inviteID"],{signaling:t,signalingData:s,signalingExtensionOptions:r}=(this._validateBeforeAccept(e),this._isProcessingSignaling=!0,un.createAcceptSignaling(o)),n=yield this._sendSignaling(t,r);return 0===(null==n?void 0:n.code)?(cn.updateSignaling(s),Object.assign(Object.assign({},n),{inviteID:e})):n}catch(e){throw console.error(en+".accept error:"+e),e}finally{this._isProcessingSignaling=!1}})}cancel(n){return h(this,void 0,void 0,function*(){console.log(en+".cancel params:"+JSON.stringify(n));try{var e=n["inviteID"],{signaling:t,signalingExtensionOptions:s}=(this._validateBeforeCancel(e),this._isProcessingSignaling=!0,un.createCancelSignaling(n)),r=yield this._sendSignaling(t,s);return 0===(null==r?void 0:r.code)?(cn.removeSignaling(e),Object.assign(Object.assign({},r),{inviteID:e})):r}catch(e){throw console.error(en+".cancel error:"+e),e}finally{this._isProcessingSignaling=!1}})}reject(n){return h(this,void 0,void 0,function*(){console.log(en+".reject params:"+JSON.stringify(n));try{var e=n["inviteID"],{signaling:t,signalingExtensionOptions:s}=(this._validateBeforeReject(e),this._isProcessingSignaling=!0,un.createRejectSignaling(n)),r=yield this._sendSignaling(t,s);return 0===(null==r?void 0:r.code)?(cn.removeSignaling(e),Object.assign(Object.assign({},r),{inviteID:e})):r}catch(e){throw console.error(en+".reject error:"+e),e}finally{this._isProcessingSignaling=!1}})}modifyInvitation(e){return h(this,void 0,void 0,function*(){console.log(en+".modifyInvitation params:"+JSON.stringify(e));var r,n,{inviteID:o,data:i}=e;let a="";try{this._validateBeforeModifyInvitation(o);let e=cn.getSignaling(o),t=e["signaling"],s=p(e,["signaling"]);a=t.payload.data,s.data=i,t.payload.data=JSON.stringify(s);var l=yield null==(n=null==(r=this._core)?void 0:r.message.messageAction)?void 0:n.modifyMessage(t);return cn.hasSignaling(o)&&cn.saveSignaling(o,Object.assign(Object.assign({},s),{signaling:t})),l}catch(e){if(a){let e=cn.getSignaling(o)["signaling"];e.payload.data=a}throw e}})}getSignalingInfo(e){if(0!==on([e]).length)return e={businessID:(e=nn(e)).businessID||1,inviteID:e.inviteID,groupID:e.groupID||"",inviter:e.inviter||"",inviteeList:e.inviteeList||[],data:e.data||"",actionType:e.actionType||xo,timeout:e.timeout||0},console.log(en+" getSignalingInfo ",e),e}addSignalingListener(e,t,s){var r;e===(null==(r=this._core)?void 0:r.SignalingEvent.NEW_INVITATION_RECEIVED)&&cn.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)&&cn.setSignalingListenStatus(!1),null!=(r=this._core)&&r.notificationCenter.unSubscribeOuterEvent(e,t,s)}handleInvitationExpiryTimer(e){var t=cn.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 n;console.log(en+"._sendTimeoutNotice params:"+JSON.stringify(s));let{isInviter:o,inviteID:i}=s,{signaling:a,signalingData:l,signalingExtensionOptions:e}=un.createTimeoutSignaling(s),t=yield this._sendSignaling(a,e);if(0===(null==t?void 0:t.code)){let{data:e,groupID:t,inviteeList:s,inviter:r}=l;null!=(n=this._core)&&n.notificationCenter.emitOuterEvent(null==(n=this._core)?void 0:n.SignalingEvent.INVITATION_TIMEOUT,{name:null==(n=this._core)?void 0:n.SignalingEvent.INVITATION_TIMEOUT,data:{data:e,groupID:t,inviteID:i,inviteeList:s,inviter:r,isSelfTimeout:!0,message:a}}),o?cn.removeSignaling(i):cn.updateSignaling(l)}})}_validateInviteId(e,t){if(!cn.hasSignaling(t))throw new this._core.helper.ChatError({functionName:e,code:tn})}_validateProcessStatus(e){if(this._isProcessingSignaling)throw new this._core.helper.ChatError({functionName:e,message:"processing other signaling operations"})}_validateBeforeInvite(e){var t=zo,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=Jo;this._validateInviteId(s,t),this._validateProcessStatus(s);let r=this._core.common.getCurrentUserID(),e=cn.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=Qo,s=(this._validateInviteId(t,e),this._validateProcessStatus(t),this._core.common.getCurrentUserID()),r=cn.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=Xo;this._validateInviteId(s,t),this._validateProcessStatus(s);let r=this._core.common.getCurrentUserID(),e=cn.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=Zo;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}},dn=new class{constructor(){this._actionProcessor=new Map([[xo,this._onNewInvitationReceived.bind(this)],[jo,this._onInviteeRejected.bind(this)],[Bo,this._onInviteeAccepted.bind(this)],[Vo,this._onInvitationCancelled.bind(this)],[Ko,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=nn(e);s&&null!=(t=this._actionProcessor.get(s.actionType))&&t(s,e)})}_handleMessageReceived(e){cn.getSignalingListenStatus()&&0!==(e=on(e.data)).length&&this.handleActionSignaling(e)}_handleMessageModified(e){cn.getSignalingListenStatus()&&0<(e=on(e.data)).length&&e.forEach(e=>{var t=nn(e);t&&this._onInvitationModified(t,e)})}_onNewInvitationReceived(t,s){var r=en+"._onNewInvitationReceived",{inviteID:n,inviteeList:o,groupID:i}=t,a=this._core.common.getCurrentUserID();if(console.log(r+` signalingData:${JSON.stringify(t)}}`),!i||o.includes(a)){let e=t["timeout"];var r=Date.now()/1e3-s.time,i=(0<e&&0<r&&e>r&&(e-=r),cn.getSignaling(n));i!==t&&(i||cn.saveSignaling(n,Object.assign(Object.assign({},t),{signaling:s})),0<e&&(null!=(a=this._core)&&a.helper.taskScheduler.addOnceTask({id:sn+"-"+n,intervalMs:1e3*e,callback:ln.handleInvitationExpiryTimer.bind(ln,n)})),this._emitEvent({name:null==(r=this._core)?void 0:r.SignalingEvent.NEW_INVITATION_RECEIVED,data:Object.assign(Object.assign({},this._generateBaseEmitData(t)),{inviteeList:o})}))}}_onInviteeRejected(e){var t=en+"._onInviteeRejected",{inviteID:s,inviter:r,groupID:n,inviteeList:o}=e,i=cn.hasSignaling(s);console.log(t+` inviteID:${s} hasInviteID:${i} inviter:${r} groupID:`+n),i&&(cn.updateSignaling(e),this._emitEvent({name:null==(t=this._core)?void 0:t.SignalingEvent.INVITEE_REJECTED,data:Object.assign(Object.assign({},this._generateBaseEmitData(e)),{invitee:o[0]})}))}_onInviteeAccepted(e){var t=en+"._onInviteeAccepted",{inviteID:s,inviter:r,groupID:n,inviteeList:o}=e,i=cn.hasSignaling(s);console.log(t+` inviteID:${s} hasInviteID:${i} inviter:${r} groupID:`+n),i&&(cn.updateSignaling(e),this._emitEvent({name:null==(t=this._core)?void 0:t.SignalingEvent.INVITEE_ACCEPTED,data:Object.assign(Object.assign({},this._generateBaseEmitData(e)),{invitee:o[0]})}))}_onInvitationCancelled(e){var t=en+"._onInvitationCancelled",{inviteID:s,inviter:r,groupID:n}=e,o=cn.hasSignaling(s);console.log(t+` inviteID:${s} hasInviteID:${o} inviter:${r} groupID:`+n),o&&(cn.removeSignaling(s),this._emitEvent({name:null==(t=this._core)?void 0:t.SignalingEvent.INVITATION_CANCELLED,data:this._generateBaseEmitData(e)}))}_onInvitationTimeout(e){var t=en+"._onInvitationTimeout",{inviteID:s,inviteeList:r}=e,n=cn.hasSignaling(s);console.log(t+` inviteID:${s} hasInviteID:${n} data:`+e.data),n&&(cn.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=en+"._onInvitationModified",{inviteID:r,data:n}=e,o=cn.hasSignaling(r);console.log(s+` inviteID:${r} data:`+n),o&&(cn.saveSignaling(r,Object.assign(Object.assign({},e),{signaling:t})),this._emitEvent({name:null==(s=this._core)?void 0:s.SignalingEvent.INVITATION_MODIFIED,data:{inviteID:r,data:n}}))}_emitEvent(e){var t;null!=(t=this._core)&&t.notificationCenter.emitOuterEvent(e.name,e)}_generateBaseEmitData(e){var{inviteID:e,inviter:t,groupID:s,data:r}=e;return{inviteID:e,inviter:t,groupID:s,data:r||""}}_dispose(){var e;null!=(e=this._core)&&e.notificationCenter.unSubscribeOuterEvent(this._core.OuterEvent.MESSAGE_RECEIVED,this._handleMessageReceived,this),null!=(e=this._core)&&e.notificationCenter.unSubscribeOuterEvent(this._core.OuterEvent.MESSAGE_MODIFIED,this._handleMessageModified,this),null!=(e=this._core)&&e.notificationCenter.unSubscribeOuterEvent(this._core.InnerEvent.DESTROY,this._dispose,this)}},pn=new class{constructor(){this._offlineSignalingMap=new Map}init(e){var{notificationCenter:e,helper:t,constants:{InnerEvent:s,WORKFLOW_STEP:r,WORKFLOW_NAME:n}}=this._core=e;e.subscribeInnerEvent(s.DESTROY,this._dispose,this),e.subscribeInnerEvent(s.LOGOUT,this._reset,this),t.registerWorkflowStep(n.SYNC_SERVER_INFO_AFTER_LOGIN,r.SIGNALING_MESSAGE_RECOVER,this._handleC2COfflineMessage,this)}_handleC2COfflineMessage(e){var{result:{unreadMessageMap:e}={}}=e||{};if(0!==(null==e?void 0:e.size)&&cn.getSignalingListenStatus()){e=on([...e.values()]);if(0!==e.length&&(e.forEach(e=>{this._handleC2CActionType(e)}),0<this._offlineSignalingMap.size)){let e=this._sortOfflineSignalingByTime();dn.handleActionSignaling(e)}}}_handleC2CActionType(e){var t,s=nn(e);s&&(t=s["actionType"],t===xo?this._saveValidOfflineInvite(s,e):this._removeOfflineInvite(s))}_saveValidOfflineInvite(e,t){var{inviteID:s,inviteeList:r=[],timeout:n=0}=e,o=this._core.common.getCurrentUserID();r.includes(o)&&(r=Date.now()/1e3-t.time,0<n&&n<r&&0!==n||this._offlineSignalingMap.set(s,Object.assign(Object.assign({},e),{signalingList:[t]})))}_removeOfflineInvite(e){var{inviteID:e=""}=e;this._offlineSignalingMap.has(e)&&this._offlineSignalingMap.delete(e)}_sortOfflineSignalingByTime(){let t=[];return this._offlineSignalingMap.forEach(e=>{t=[...t,...e.signalingList]}),t.sort((e,t)=>e.time-t.time)}_dispose(){var e;this._reset(),null!=(e=this._core)&&e.notificationCenter.unSubscribeInnerEvent(this._core.InnerEvent.LOGOUT,this._reset,this),null!=(e=this._core)&&e.notificationCenter.unSubscribeInnerEvent(this._core.InnerEvent.DESTROY,this._dispose,this)}_reset(){this._offlineSignalingMap.clear()}};let hn={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}}},gn={invite:!0,cancel:!0,accept:!0,reject:!0,modifyInvitation:!0};var vn,fn,kn,_n=new class{constructor(){this.name="Signaling"}install(e){ln.init(e),dn.init(e),un.init(e),cn.init(e),pn.init(e),e.helper.registerValidateConfig({auth:gn,params:hn})}};let mn=new class{init(e){this.core=e}},In=(!function(e){e.MSG_TEXT="TIMTextElem",e.MSG_CUSTOM="TIMCustomElem",e.MSG_LOCATION="TIMLocationElem",e.MSG_FACE="TIMFaceElem"}(vn=vn||{}),function(e){e[e.FORWARD=0]="FORWARD",e[e.BACKWARD=1]="BACKWARD"}(fn=fn||{}),"MSG_REACTION"),Sn="MSG_EXT",En=0,Cn=1,Mn={ZH_CN:"zh (cmn-Hans-CN)",EN_US:"en-US",YUE_HK:"yue-Hant-HK",JA_JP:"ja-JP",ZH_PY:"zh-PY"},yn="16k_zh",An="16k_en",Tn="16k_yue",On="16k_ja",Dn="16k_zh-PY",Rn={[Mn.ZH_CN]:yn,[Mn.EN_US]:An,[Mn.YUE_HK]:Tn,[Mn.JA_JP]:On,[Mn.ZH_PY]:Dn},Ln=/\.(wav|pcm|ogg-opus|speex|silk|mp3|m4a|aac|amr)/,Nn={READ:0,UNREAD:1},bn=1,Gn=2,wn=3,Pn=1,Un=2,Fn=(!function(e){e.IN="in",e.OUT="out"}(kn=kn||{}),2116),$n=2500,qn="C2C",xn="GROUP",Vn=20;function Bn(o){return h(this,void 0,void 0,function*(){var e,s=mn.core["appStore"],{messageList:t,conversationID:r}=o,s=s.conversationStore.getConversationMap();let n=null==(e=s.get(r))?void 0:e.peerReadTime;if(!n){let e=r.replace(qn,""),t=yield function(t){return h(this,void 0,void 0,function*(){var e={To_Account:t};return mn.core.common.buildAndSendPacket({servcmd:"openim.get_peer_read_time",data:e})})}([e]);if(t){let e=t["ReadTime"];n=null==e?void 0:e[0],s.has(r)&&(s.get(r).peerReadTime=n)}}t.forEach(e=>{e.time<=n&&!e.isPeerRead&&"out"===e.flow&&(e.isPeerRead=!0)})})}function jn(a){return h(this,void 0,void 0,function*(){var e;let{message:s,user:t,appStore:r,constants:{OuterConstant:n}}=mn.core,o=r.conversationStore.getConversationMap();if(o.has(a)){let s=null==(e=o.get(a))?void 0:e.userProfile;if(s&&a.startsWith(n.CONV_C2C)){let{avatar:e,nick:t}=s;mn.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 Kn(e){let t,s=mn.core["message"],{conversationID:r,messageID:n}=e;return t=(t=s.messageDataHandler.getLocalMessageList(r).find(e=>e.ID===n))||s.messageDataHandler.getSparseMessageList(r).find(e=>e.ID===n)}function Wn(e){return e.map(e=>{var{from:t,to:s,cloudCustomData:r,avatar:n,nick:o,ID:i,clientSequence:a,clientTime:l,messageRandom:c,messageSequence:u,time:d}=e;return{ClientSeq:a,CloudCustomData:r,From_Account:t,From_AccountHeadurl:n,From_AccountNick:o,Id:i,MsgBody:JSON.parse(JSON.stringify(e.transformElementsToServerFormat())),MsgClientTime:l,MsgRandom:c,Random:c,MsgSeq:u,MsgTimeStamp:d,ReceiverId:s,SenderId:t,To_Account:s}})}function Hn(e){var{From_Account:t,From_AccountHeadurl:s,From_AccountNick:r,GroupId:n,MsgClientTime:o,ClientSeq:i,To_Account:a,MsgTimeStamp:l,TinyId:c,MsgRandom:u,MsgSeq:d}=e;return{from:t,avatar:s,nick:r,clientTime:o,time:l,tinyID:c,random:u,sequence:d,to:a,groupID:n,clientSequence:i,_elements:null==(t=e.MsgBody)?void 0:t.map(e=>{var t=e["MsgType"];return mn.core.message.messageFactory.getElementClass(t).parseServerPushElement(e)})}}var Yn=new class{constructor(){this._reactionsMap=new Map}init(e){var{helper:e,notificationCenter:t,InnerEvent:{MESSAGE_PUSH:s},InnerEventSubType:{MESSAGE_REACTION_UPDATED:r,MESSAGE_REACTION_UPDATED_SYNC:n}}=this._core=e;e.registerApi({apiName:"addMessageReaction",context:this}),e.registerApi({apiName:"removeMessageReaction",context:this}),e.registerApi({apiName:"getMessageReactions",context:this}),e.registerApi({apiName:"getAllUserListOfMessageReaction",context:this}),t.subscribeInnerEvent(s,r,this._handleReactionUpdated,this),t.subscribeInnerEvent(s,n,this._handleReactionSync,this)}addMessageReaction(g,_){return h(this,void 0,void 0,function*(){let{OuterConstant:e,ssoLog:t,helper:r}=this._core;this._validateMessageReactionBusinessCapability();var n=t.createSSOLogData({method:"addMessageReaction"}),{conversationID:s,ID:o,conversationType:i,from:a,to:l,clientSequence:c,random:u,time:d,sequence:p}=g;try{return this._recordMessageReactedByMe(o,_),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:n,reactionID:o}=i,t={From_Account:e,To_Account:t,MsgKey:s+`_${r}_`+n,Reaction:o,Add_Account:[null==(e=a.store.get("login"))?void 0:e.userId]};return mn.core.common.buildAndSendPacket({servcmd:"openim_msg_ext_http_svc.reaction_add",data:t})})}({from:a,to:l,clientSequence:c,random:u,time:d,reactionID:_},this._core):i===e.CONV_GROUP&&(yield function(r,n){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=n.store.get("login"))?void 0:e.userId]};return mn.core.common.buildAndSendPacket({servcmd:"openim_msg_ext_http_svc.group_reaction_add",data:s})})}({to:l,reactionID:_,sequence:p},this._core)),n.setLogInfo({message:`conversationID:${s} messageID:${o} reactionID:`+_}).end(),{code:0}}catch(e){this._removeMyReactionRecord(o,_);let t=(e||{})["errorCode"],s=new r.ChatError({functionName:"addMessageReaction",code:t});n.setError(s).end(),console.error("addMessageReaction error: ",e)}})}removeMessageReaction(d,p){return h(this,void 0,void 0,function*(){let{OuterConstant:c,ssoLog:e,helper:r}=this._core;this._validateMessageReactionBusinessCapability();var u=e.createSSOLogData({method:"removeMessageReaction"});try{let{conversationID:e,ID:t,conversationType:s,from:r,to:n,clientSequence:o,random:i,time:a,sequence:l}=d;return this._removeMyReactionRecord(t,p),s===c.CONV_C2C?yield function(i,a){return h(this,void 0,void 0,function*(){var{from:e,to:t,clientSequence:s,random:r,time:n,reactionID:o}=i,t={From_Account:e,To_Account:t,MsgKey:s+`_${r}_`+n,Reaction:o,Del_Account:[null==(e=a.store.get("login"))?void 0:e.userId]};return mn.core.common.buildAndSendPacket({servcmd:"openim_msg_ext_http_svc.reaction_del",data:t})})}({from:r,to:n,clientSequence:o,random:i,time:a,reactionID:p},this._core):s===c.CONV_GROUP&&(yield function(r,n){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=n.store.get("login"))?void 0:e.userId]};return mn.core.common.buildAndSendPacket({servcmd:"openim_msg_ext_http_svc.group_reaction_del",data:s},n)})}({to:n,reactionID:p,sequence:l},this._core)),u.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});u.setError(s).end(),console.error("removeMessageReaction error: ",e)}})}getAllUserListOfMessageReaction(c){return h(this,void 0,void 0,function*(){this._validateMessageReactionBusinessCapability();let{message:e,reactionID:t,nextSeq:r=0}=c,s=100<c.count?100:c.count,n=e["conversationID"],{ssoLog:o,helper:i,constants:a}=this._core;try{var l;if(l=n.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:n,clientSequence:o,random:i,time:a}=e,s={Reaction:s,NextSeq:t,Count:r,From_Account:e,To_Account:n,MsgKey:o+`_${i}_`+a};return mn.core.common.buildAndSendPacket({servcmd:"openim_msg_ext_http_svc.reaction_iterate",data:s})})}({message:e,reactionID:t,nextSeq:r,count:s}):yield function(o){return h(this,void 0,void 0,function*(){var{message:e,nextSeq:t,reactionID:s,count:r}=o,{sequence:e,to:n}=e,s={Reaction:s,NextSeq:t,GroupId:n,Count:r,MsgSeq:e};return mn.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});o.createSSOLogData({method:"removeMessageReaction"}).setError(s).end(),console.error("getAllUserListOfMessageReaction error: ",e)}})}getMessageReactions(g){return h(this,void 0,void 0,function*(){var e=this._core["constants"],{messageList:t,maxUserCountPerReaction:s=10}=(this._validateMessageReactionBusinessCapability(),g),r=t[0];let n=null,o=new Map,{from:i,to:a,conversationType:l}=r,c=this._generateMessageKeyList(t,o),{Results:u=[]}=(l===e.OuterConstant.CONV_C2C?n=yield function(n){return h(this,void 0,void 0,function*(){var{from:e,to:t,messageKeyList:s,maxUserCountPerReaction:r}=n,e={From_Account:e,To_Account:t,MsgKeyList:s,Count:r};return mn.core.common.buildAndSendPacket({servcmd:"openim_msg_ext_http_svc.reaction_multi_stat",data:e})})}({from:i,to:a,messageKeyList:c,maxUserCountPerReaction:s}):l===e.OuterConstant.CONV_GROUP&&(n=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 mn.core.common.buildAndSendPacket({servcmd:"openim_msg_ext_http_svc.group_reaction_multi_stat",data:e})})}({groupId:a,messageSequenceList:c,maxUserCountPerReaction:s})),n||{}),d=this._extractUserIDsFromReactionResults(u),p=yield this._getUserProfileMap(d);return{code:0,data:{resultList:u.map(e=>{var{ReactionList:e,MsgSeq:t,MsgKey:s}=e;return{messageID:this._generateMessageID({messageSequence:t,messageKey:s,messageIDMap:o}),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(In))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(u=>h(this,void 0,void 0,function*(){let{C2CMsgInfo:e,GroupMsgInfo:t,MsgReactionSummary:s}=u,{TinyId:r,MsgClientTime:n,MsgRandom:o}=Object.assign(Object.assign({},e),t),i=r+`-${n}-`+o,a=this._extractUserIDsFromReactionResults([{ReactionList:s}]),l=yield this._getUserProfileMap(a),c=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:c}})}))}_handleReactionSync(e){var{notificationCenter:t,constants:s}=this._core,{C2CMsgInfo:e={},GroupMsgInfo:r={},Reaction:n,OperateType:o}=e.MsgReactionNotify,{TinyId:e="",MsgClientTime:r=0,MsgRandom:i=0}=Object.assign(Object.assign({},e),r),r=e+`-${r}-`+i,i=r+"-"+n;if(1===o?this._recordMessageReactedByMe(r,n):this._removeMyReactionRecord(r,n),null!=(e=this._reactionsMap.get(i))&&e.reactionID){let e=this._reactionsMap.get(i);e.reactedByMyself=1===o,t.emitOuterEvent(s.OuterEvent.MESSAGE_REACTIONS_UPDATED,{name:s.OuterEvent.MESSAGE_REACTIONS_UPDATED,data:{messageID:r,reactionList:[e]}})}}_generatePartialUserInfo({userIDList:e,userProfileMap:t}){let s=[];return null!=e&&e.forEach(e=>{t.has(e)&&s.push(t.get(e))}),s}_generateMessageID(e){var{messageSequence:e,messageKey:t,messageIDMap:s}=e;return t?s.get(t):s.get(e)}_generateMessageKeyList(e,n){var t=this._core["constants"],s=e[0]["conversationType"];let r=[];return s===t.OuterConstant.CONV_C2C?r=e.map(e=>{var{clientSequence:e,random:t,time:s,ID:r}=e,e=e+`_${t}_`+s;return n.set(e,r),e}):s===t.OuterConstant.CONV_GROUP&&(r=e.map(e=>{var{ID:e,sequence:t}=e;return n.set(t,e),t})),r}},zn=new class{init(e){var{helper:e,InnerEvent:{MESSAGE_PUSH:t},InnerEventSubType:{C2C_MESSAGE_READ_RECEIPT:s,GROUP_MESSAGE_READ_RECEIPT:r},notificationCenter:n}=this._core=e;e.registerApi({apiName:"sendMessageReadReceipt",context:this}),e.registerApi({apiName:"getMessageReadReceiptList",context:this}),e.registerApi({apiName:"getGroupMessageReadMemberList",context:this}),n.subscribeInnerEvent(t,s,this._handleC2CMessageReadReceipt,this),n.subscribeInnerEvent(t,r,this._handleGroupMessageReadReceipt,this)}sendMessageReadReceipt(e){return 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}=mn.core,t=r[0].conversationID.replace(t.OuterConstant.CONV_C2C,""),s=r.map(e=>{var{from:e,to:t,sequence:s,random:r,time:n,clientTime:o}=e;return{From_Account:e,To_Account:t,MsgSeq:s,MsgRandom:r,MsgTime:n,MsgClientTime:o}});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}=mn.core,t={GroupId:s[0].conversationID.replace(t.OuterConstant.CONV_GROUP,""),MsgSeqList:s.map(e=>({MsgSeq:e.sequence}))};return e.buildAndSendPacket({servcmd:"group_open_http_svc.group_msg_receipt",data:t})})}(s),{code:0,data:{}}}catch(e){let{errorCode:t,errorInfo:s}=e;throw new r.ChatError({code:t,message:s})}})}getMessageReadReceiptList(n){return h(this,void 0,void 0,function*(){let{common:r,constants:t}=this._core;try{let e=n[0]["conversationType"];if(e===t.OuterConstant.CONV_GROUP){let s=this._filterValidMessageSendByMe(n);if(0<(null==s?void 0:s.length)){let e=yield function(s){return h(this,void 0,void 0,function*(){var{common:e,constants:t}=mn.core,t={GroupId:s[0].conversationID.replace(t.OuterConstant.CONV_GROUP,""),MsgSeqList:s.map(e=>({MsgSeq:e.sequence}))};return e.buildAndSendPacket({servcmd:"group_open_http_svc.get_group_msg_receipt",data:t})})}(s),t=(e||{})["GroupMsgReceiptList"];this._updateGroupMessagesReadReceiptInfo({messageList:n,readReceiptList:t})}}return{code:0,data:{messageList:n}}}catch(e){let{errorCode:t,errorInfo:s}=e;throw new r.ChatError({code:t,message:s})}})}getGroupMessageReadMemberList(o){return h(this,void 0,void 0,function*(){let{constants:e,common:r}=this._core,{message:t,filter:i=Nn.READ,cursor:s=""}=o,{conversationID:n,sequence:a,ID:l}=t,c=n.replace(e.OuterConstant.CONV_GROUP,""),u=100<=o.count?100:o.count;try{let o=yield function(o){return h(this,void 0,void 0,function*(){var{sequence:e,groupID:t,filter:s,cursor:r,count:n}=o,e={MsgSeq:e,GroupId:t,Filter:s,Cursor:r,Num:n};return mn.core.common.buildAndSendPacket({servcmd:"group_open_http_svc.get_group_msg_receipt_detail",data:e})})}({groupID:c,sequence:a,filter:i,cursor:s,count:u});if(o){let{Cursor:e,IsFinish:t,UnreadList:s,ReadList:r}=o,n={cursor:e,isCompleted:1===t,messageID:l,unreadUserIDList:[],readUserIDList:[]};return i===Nn.READ?n.readUserIDList=r.map(e=>e.Read_Account):i===Nn.UNREAD&&(n.unreadUserIDList=s.map(e=>e.Unread_Account)),{code:0,data:n}}}catch(e){let{errorCode:t,errorInfo:s}=e;throw new r.ChatError({code:t,message:s})}})}_handleC2CMessageReadReceipt(e){let n=[],{constants:t,helper:s}=this._core,{C2cMsgInfo:o,PeerReadTime:i,Peer_Account:a}=e;if(!s.isEmpty(o)){let r=""+t.OuterConstant.CONV_C2C+a;null!=o&&o.forEach(e=>{var{TinyId:e,MsgClientTime:t,MsgRandom:s}=e,e=e+`-${t}-`+s,t=Kn({conversationID:r,messageID:e});t&&!t.readReceiptInfo.isPeerRead&&(t.readReceiptInfo.isPeerRead=!0,t.readReceiptInfo.timestamp=i,n.push({userID:a,messageID:e,isPeerRead:!0,timestamp:i}))}),this._emitReadReceiptEventIfNeed(n)}}_updateGroupMessagesReadReceiptInfo(e){let{messageList:t,readReceiptList:s}=e,r=new Map;t.forEach(e=>{r.set(e.sequence,e)}),null!=s&&s.forEach(e=>{var t,s;0===e.Code&&({MsgSeq:e,ReadNum:t,UnreadNum:s}=e,e=r.get(e))&&(e.readReceiptInfo.readCount=t,e.readReceiptInfo.unreadCount=s)})}_handleGroupMessageReadReceipt(e){let a=[],s=this._core["constants"],t=e["GroupTips"];t.forEach(e=>{let{MsgBody:{GroupMsgReceiptList:t},GroupInfo:{GroupId:o}}=e,i=""+s.OuterConstant.CONV_GROUP+o;null!=t&&t.forEach(e=>{var{TinyId:e,MsgClientTime:t,MsgRandom:s,ReadNum:r,UnreadNum:n}=e,e=e+`-${t}-`+s,t=Kn({conversationID:i,messageID:e}),s={groupID:o,messageID:e,readCount:0,unreadCount:0};t&&("number"==typeof r&&(t.readReceiptInfo.readCount=r,s.readCount=r),"number"==typeof n&&(t.readReceiptInfo.unreadCount=n,s.unreadCount=n),a.push(s))})}),this._emitReadReceiptEventIfNeed(a)}_emitReadReceiptEventIfNeed(e){var{notificationCenter:t,OuterEvent:s}=this._core;0<e.length&&t.emitOuterEvent(s.MESSAGE_READ_RECEIPT_RECEIVED,{name:s.MESSAGE_READ_RECEIPT_RECEIVED,data:e})}_filterValidMessageSendByOther(e){return this._filterNeedReadReceiptMessages(e).filter(e=>{e=e.from;return e!==this._core.common.getCurrentUserID()})}_filterValidMessageSendByMe(e){let s=this._core.constants["OuterConstant"];return this._filterNeedReadReceiptMessages(e).filter(e=>{var{from:e,status:t}=e;return e===this._core.common.getCurrentUserID()&&t===s.MessageStatus.SUCCESS})}_filterNeedReadReceiptMessages(e){return e.filter(e=>!0===e.needReadReceipt)}dispose(){var{InnerEvent:{MESSAGE_PUSH:e},InnerEventSubType:{C2C_MESSAGE_READ_RECEIPT:t,GROUP_MESSAGE_READ_RECEIPT:s},notificationCenter:r}=this._core;r.unSubscribeInnerEvent(e,t,this._handleC2CMessageReadReceipt,this),r.unSubscribeInnerEvent(e,s,this._handleGroupMessageReadReceipt,this)}};function Jn(i,a,l){return h(this,void 0,void 0,function*(){var{buildAndSendPacket:e}=mn.core["common"],{from:t,to:s,clientSequence:r,random:n,time:o}=i;return e({servcmd:"openim_msg_ext_http_svc.set_key_values",data:{From_Account:t,To_Account:s,MsgKey:r+`_${n}_`+o,OperateType:l,ExtensionList:a}})})}function Qn(r,n,o){return h(this,void 0,void 0,function*(){var{buildAndSendPacket:e}=mn.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:o,ExtensionList:n}})})}var Xn=new class{constructor(){this._messageExtensionsMap=new Map,this._extensionsLatestSequenceMap=new Map,this._completedFetchExtensions=new Set}init(e){var{notificationCenter:e,helper:{registerApi:t},InnerEvent:{MESSAGE_PUSH:s,LOGOUT:r},InnerEventSubType:{MESSAGE_EXTENSIONS_UPDATED:n}}=this._core=e;t({apiName:"setMessageExtensions",context:this}),t({apiName:"getMessageExtensions",context:this}),t({apiName:"deleteMessageExtensions",context:this}),e.subscribeInnerEvent(s,n,this._handleMessageExtensionsNotify,this),e.subscribeInnerEvent(r,this.reset,this)}setMessageExtensions(d,r){return h(this,void 0,void 0,function*(){this._validateMessageExtensionBusinessCapability("setMessageExtensions");let{constants:{OuterConstant:e},ssoLog:t}=this._core,{ID:n,conversationID:o,sequence:i,time:a,conversationType:s}=d,l=t.createSSOLogData({method:"setMessageExtensions"}),c=r;20<r.length&&(c=r.slice(0,20),console.warn("the length of extensions cannot exceed 20"));var u=this._generateServerExtensions(d,c);try{let r;if(s===e.CONV_C2C?r=yield Jn(d,u,bn):s===e.CONV_GROUP&&(r=yield Qn(d,u,bn)),r){let{resultList:e,successCount:t,failureCount:s}=this._handleModifyMessageExtensions(d,r);return l.setLogInfo({message:`convID:${o} messageID:${n} sequence:${i}
|
|
2
|
+
time:${a} count:${c.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:n}=(this._validateMessageExtensionBusinessCapability("getMessageExtensions"),i),o=this._core.ssoLog.createSSOLogData({method:"getMessageExtensions"});o.setLogInfo({message:`convID:${e} messageID:${r} sequence:${t} time:`+n});try{let e,t=(this._completedFetchExtensions.has(r)&&(e=this._extensionsLatestSequenceMap.get(r)),yield this._fetchMessageExtensions(i,e));return s(e)&&1<t.length&&this._completedFetchExtensions.add(r),o.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 o.setError(r).end(),r}})}deleteMessageExtensions(p,g){return h(this,void 0,void 0,function*(){this._validateMessageExtensionBusinessCapability("deleteMessageExtensions");let{utils:{isEmpty:e},constants:{OuterConstant:t},ssoLog:s}=this._core,{conversationType:n,conversationID:r,sequence:o,ID:i,time:a}=p,l=wn,c=[];e(g)||(l=Gn,null==g)||g.forEach(e=>{c.push({key:e,value:"",seq:0})});var u=s.createSSOLogData({method:"deleteMessageExtensions"}),d=(u.setLogInfo({message:`convID:${r} messageID:${i} sequence:${o} time:${a} operateType:`+l}),this._generateServerExtensions(p,c));try{let r;if(n===t.CONV_C2C?r=yield Jn(p,d,l):n===t.CONV_GROUP&&(r=yield Qn(p,d,l)),r){let{resultList:e,successCount:t,failureCount:s}=this._handleModifyMessageExtensions(p,r);return u.setMoreMessage(`success count:${t} fail count:`+s),u.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 u.setError(s).end(),s}})}reset(){this._messageExtensionsMap.clear(),this._extensionsLatestSequenceMap.clear(),this._completedFetchExtensions.clear()}dispose(){this.reset();var{notificationCenter:e,InnerEvent:{MESSAGE_PUSH:t,LOGOUT:s},InnerEventSubType:{MESSAGE_EXTENSIONS_UPDATED:r}}=this._core;e.unSubscribeInnerEvent(t,r,this._handleMessageExtensionsNotify,this),e.subscribeInnerEvent(s,this.reset,this)}_handleModifyMessageExtensions(e,t){let s=e["ID"],r=t["Seq"],n=t.ExtensionList||[],o=[],i=0,a=0,l=[];return n.forEach(e=>{var{ErrorCode:e,Extension:t}=e,{Key:t,Value:s,Seq:r}=t;o.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:o,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 o;var{conversationType:t,ID:a}=l;if(t===e.CONV_C2C?o=yield function(e,t){var s=mn.core["common"]["buildAndSendPacket"],{from:e,to:r,clientSequence:n,random:o,time:i}=e;return s({servcmd:"openim_msg_ext_http_svc.get_key_values",data:{From_Account:e,To_Account:r,MsgKey:n+`_${o}_`+i,StartSeq:t}})}(l,s):t===e.CONV_GROUP&&(o=yield function(e,t){var s=mn.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)),o){let{LatestSeq:e,ClearSeq:t,CompleteFlag:s}=o,r=(o.ExtensionList||[]).map(e=>({key:e.Key,value:e.Value,seq:e.Seq}));if(this._updateLocalExtensions(a,r),this._clearLocationExtensions(a,t),this._extensionsLatestSequenceMap.set(a,e),1!==s){let e=r[r.length-1].seq+1;return this._fetchMessageExtensions(l,e)}let n=[];if(this._messageExtensionsMap.has(a)){let e=this._messageExtensionsMap.get(a);null!=e&&e.forEach((e,t)=>{e=e.value;i(e)||n.push({key:t,value:e})})}return n}}catch(e){console.error(e)}})}_clearLocationExtensions(e,r){if(!(r<=0)&&this._messageExtensionsMap.has(e)){let s=this._messageExtensionsMap.get(e);null!=s&&s.forEach((e,t)=>{e.seq<=r&&s.delete(t)})}}_generateServerExtensions(e,t){var s=e["ID"];if(this._messageExtensionsMap.has(s)){let r=this._messageExtensionsMap.get(s);return t.map(e=>{var{key:e,value:t}=e;let s=0;return{Key:e,Value:t,Seq:s=null!=r&&r.has(e)?null==(t=r.get(e))?void 0:t.seq:s}})}return t.map(e=>({Key:e.key,Value:e.value,Seq:0}))}_validateMessageExtensionBusinessCapability(e){var{helper:t,constants:s}=this._core;if(!t.checkBusinessCapabilityBits(Sn))throw new t.ChatError({functionName:e,code:s.ERROR_CODE.NO_USE,replacement1:e})}_handleMessageExtensionsNotify(e){var{SetKVInfo:e,DeleteKVInfo:t,ClearKVInfo:s,MsgOptType:r,TinyId:n,MsgLastSeq:o,ExtensionC2cMsgInfo:i,ExtensionGroupMsgInfo:a}=(null==e?void 0:e.MsgExtensionNotify)||{},{MsgClientTime:i,MsgRandom:a}=i||a||{},n=n+`-${i}-`+a;this._extensionsLatestSequenceMap.set(n,o),r===bn?this._handleMessageExtensionsUpdated({messageID:n,updateMessageExtensionsInfo:e}):r===Gn?this._handleMessageExtensionsDeleted({messageID:n,deleteMessageExtensionsInfo:t}):r===wn&&this._handleMessageExtensionsCleared({messageID:n,clearMessageExtensionsInfo:s})}_handleMessageExtensionsUpdated(e){let{notificationCenter:t,OuterEvent:s}=this._core,{messageID:r,updateMessageExtensionsInfo:n=[]}=e,o=[];n.forEach(e=>{var{MsgKeyValue:e=[]}=e,e=e.map(e=>(o.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:o}})}_handleMessageExtensionsDeleted(e){let{notificationCenter:t,OuterEvent:s}=this._core,{messageID:r,deleteMessageExtensionsInfo:n=[]}=e,o=[];n.forEach(e=>{var{MsgKeyValue:e=[]}=e,e=e.map(e=>(o.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:o}})}_handleMessageExtensionsCleared(e){let{notificationCenter:t,OuterEvent:{MESSAGE_EXTENSIONS_DELETED:s},utils:{isEmpty:r}}=this._core,{messageID:n,clearMessageExtensionsInfo:o=[]}=e,i=[];o.forEach(e=>{let s=e["ClearMsgSeq"];this._messageExtensionsMap.has(n)&&(this._messageExtensionsMap.get(n)||[]).forEach((e,t)=>{e.seq<=s&&!r(e.value)&&i.push(t)}),this._clearLocationExtensions(n,s)}),t.emitOuterEvent(s,{name:s,data:{messageID:n,keyList:i}})}};let Zn={key:"message",required:!0,rules:["object"],allowEmpty:!1,customValidator:e=>{var{OuterConstant:t}=mn.core["constants"];return e.status!==t.MessageStatus.SUCCESS?"message is not success":!0===e.isSupportExtension||"message is not support extension"}},ei={setMessageExtensions:[Zn,{key:"extensions",required:!0,rules:["array"],allowEmpty:!1}],getMessageExtensions:[Zn],deleteMessageExtensions:[Zn]},ti=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}=mn.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}}}),ei),si=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 oi{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(o){return h(this,void 0,void 0,function*(){var{to:e,from:t,sequence:s,time:r,random:n}=o;return this._core.common.buildAndSendPacket({servcmd:"openim.msgwithdraw",data:{MsgInfo:{From_Account:t,To_Account:e,MsgSeq:s,MsgRandom:n,MsgTimeStamp:r}}})})}}class ni{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 ii{constructor(e){this._core=e}generateRevokeMessage(e){var{conversationID:e,sequence:t,random:s,tinyID:r,clientTime:n,revokeReason:o,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&&n&&s&&(a.ID=r+`-${n}-`+s)),a=Object.assign(Object.assign({},a),{revoker:i,revokeReason:o,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)}})}_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 ri=new class{constructor(){this._core=null,this._c2cMessageAction=null,this._groupMessageAction=null}init(e){this._core=e,this._groupMessageAction=new ni(e),this._c2cMessageAction=new oi(e),this._messageHelper=new ii(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=[],c=[],{conversationID:u,conversationType:d}=t[0],e=u.replace(d,"");if("@TIM#SYSTEM"===d)throw new this._core.helper.ChatError({code:Fn});if(t.forEach(e=>{var{conversationID:t,conversationType:s,status:r,_onlineOnlyFlag:n,sequence:o,random:i,time:a}=e||{};if("success"===r&&t===u&&s===d){if(!n){let e="C2C"===s?o+`_${i}_`+a:String(o);l.push(e)}c.push(e)}}),0===l.length)return this._handleDeleteMessageSuccess(c),{code:0,data:{messageList:c}};30<l.length&&(l=l.slice(0,30),c=c.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(c),{code:0,data:{messageList:c}}}catch(e){let t=e["errorCode"];throw new this._core.helper.ChatError({functionName:"deleteMessage",code:t})}})}revokeMessage(o){return h(this,void 0,void 0,function*(){var s;let r=this._core.ssoLog.createSSOLogData({method:"revokeMessage"}),{conversationType:e,isRevoked:t}=o;var n;if("@TIM#SYSTEM"===e)throw new this._core.helper.ChatError({message:"system message cannot be revoked"});if(t)throw new this._core.helper.ChatError({message:"message has been revoked"});r.setLogInfo({message:`type:${o.type} from:${o.from} to:`+o.to});try{if(n="C2C"===e?yield this._c2cMessageAction.revokeMessage(o):yield this._groupMessageAction.revokeMessage(o)){let e=n["RecallRetList"],t=(null==(s=null==e?void 0:e[0])?void 0:s.RetCode)||0;if(0!==t)throw new this._core.helper.ChatError({code:t});return r.end(),yield this._handleRevokeMessageSuccess(o),{code:0,data:{message:o}}}}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(n){if(0!==n.length){let{message:{messageDataHandler:s},common:{isTopic:e},notificationCenter:t,InnerEvent:r}=this._core;n.forEach(t=>{t.isDeleted=!0;var e=s.getLocalMessageList(t.conversationID);null!=e&&e.forEach(e=>{e.ID===t.ID&&(e.isDeleted=!0)})});var{conversationID:n=""}=n[0];e(n)?t.emitInnerEvent(r.TOPIC_MESSAGE_DELETED,n):t.emitInnerEvent(r.MESSAGE_DELETED,n)}}_handleRevokeMessageSuccess(n){return 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}=n;this._core.message.messageDataHandler.revokeMessage({conversationID:t,sequence:s,random:r,revoker:e}),yield this._messageHelper.updateRevokerInfo([n])})}};class ai{static parseServerPushElement(e){var{MsgContent:e={}}=e,{Index:e,Data:t}=e;return new ai({index:e,data:t})}constructor(e){this.type=vn.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 ci{static parseServerPushElement(e){var{MsgContent:e={}}=e,{Desc:e,Longitude:t,Latitude:s}=e;return new ci({description:e,longitude:t,latitude:s})}constructor(e){this.type=vn.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 ui=new class{init(e){(this._core=e).message.messageFactory.registerElementClass(vn.MSG_FACE,ai),e.message.messageFactory.registerElementClass(vn.MSG_LOCATION,ci),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 ai({index:t,data:s}),s=this._core.common.getCurrentUserID(),(e=this._core.message.messageFactory.createMessage(Object.assign(Object.assign({},e),{from:s}))).setElement(t),e):null}createTextAtMessage(e){let r=((null==e?void 0:e.payload)||{})["atUserList"],n=this._core.apiMap.createTextMessage(e),o=this._core["OuterConstant"];if(!n)return null;if(Array.isArray(r)){let t=[],s=[];r.forEach(e=>{e!==o.MSG_AT_ALL?(t.push({GroupAtAllFlag:En,GroupAt_Account:e}),s.push(e)):(t.push({GroupAtAllFlag:Cn}),s.push(o.MSG_AT_ALL))}),n._groupAtInfoList=t,n.atUserList=s}return n}createForwardMessage(e){var{helper:t,OuterConstant:s}=this._core,{to:e,conversationType:r,priority:n,payload:o,needReadReceipt:i,receiverList:a,cloudCustomData:l="",isSupportExtension:c=!1}=e;if(!Array.isArray(o._elements))throw new t.ChatError({functionName:"createForwardMessage",code:2454});if(o.type===s.MSG_GRP_TIP)throw new t.ChatError({functionName:"createForwardMessage",code:2453});s=this._core.common.getCurrentUserID(),t=this._core.message.messageFactory.createMessage({to:e,from:s,conversationType:r,isPlaceMessage:0,priority:n,payload:o,needReadReceipt:i,isSupportExtension:c,cloudCustomData:l,receiverList:a});return t.setRelayFlag(!0),t.setElement(o._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 ci({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 li=class{init(e){this._messageHelper=new ii(e);var{notificationCenter:e,InnerEvent:{MESSAGE_PUSH:t},InnerEventSubType:{C2C_REVOKED_MESSAGE:s},helper:{registerWorkflowStep:r},constants:{WORKFLOW_NAME:n,WORKFLOW_STEP:o}}=this._core=e;e.subscribeInnerEvent(t,s,this._handleC2CNotifyMessage,this),r(n.SYNC_SERVER_INFO_AFTER_RE_ONLINE,o.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 a=[],{notificationCenter:e,OuterEvent:t,common:{getCurrentUserID:l}}=this._core;s.forEach(e=>{var{MsgRand:t,MsgSeq:s,To_Account:r,From_Account:n,RevokerInfo:{Revoker_Account:o,Revoke_Reason:i}}=e,r=l()===n?"C2C"+r:"C2C"+n,e=(null==(n=null==e?void 0:e.RevokerInfo)?void 0:n.Reason)||i,n=this._messageHelper.generateRevokeMessage({conversationID:r,sequence:s,random:t,revoker:o,revokeReason:e});a.push(n)}),0<a.length&&(yield this._messageHelper.updateRevokerInfo(a),e.emitOuterEvent(t.MESSAGE_REVOKED,{name:t.MESSAGE_REVOKED,data:a}))})}_handleC2CRevokeMessagesFromUnreadMessageSync(t){return 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)}},di=class{init(e){this._messageHelper=new ii(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(o){return h(this,void 0,void 0,function*(){try{let{RevokerInfo:l,MsgBody:{GroupWithdrawInfoArray:e},GroupInfo:c}=o,u=[],d=[],{notificationCenter:t,OuterEvent:s,utils:{isEmpty:r},common:{isCommunity:n}}=this._core,h=!1;c&&(h=n({groupID:c.GroupId})||!r(c.TopicId)),e.forEach(e=>{var{Random:e,MsgSeq:t,GroupId:s,MsgClientTime:r,TinyId:n,TopicId:o,RevokerInfo:{Revoker_Account:i=(null==l?void 0:l.Revoker_Account)||"",Reason:a=(null==l?void 0:l.Reason)||""}}=e,o=this._messageHelper.generateRevokeMessage({conversationID:o?"GROUP"+o:"GROUP"+s,sequence:t,random:e,tinyID:n,clientTime:r,revoker:i,revokeReason:a});(h?(o.revokerInfo.nick=c.From_AccountNick,o.revokerInfo.avatar=c.From_AccountHeadurl,u):d).push(o)}),0<d.length&&(yield this._messageHelper.updateRevokerInfo(d),u.push(...d)),0!==u.length&&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 pi=new class{constructor(){this._c2cMessageReceiver=new li,this._groupMessageReceiver=new di}init(e){this._c2cMessageReceiver.init(e),this._groupMessageReceiver.init(e)}dispose(){this._c2cMessageReceiver.dispose(),this._groupMessageReceiver.dispose()}};class hi{constructor(e){var t=(this._core=e)["constants"];this._messageHelper=new ii(e),e.helper.registerWorkflowStep(t.WORKFLOW_NAME.SYNC_SERVER_INFO_AFTER_RE_ONLINE,t.WORKFLOW_STEP.GROUP_REVOKED_NOTICE_RECOVER,this._recoverGroupRevokeNotice,this)}getRoamingMessagesByAnchor(e){return this._core.message.messageHistory.getGroupRoamingMessagesByAnchor(e)}_recoverGroupRevokeNotice(e){let{recoverRevokeNoticeGroupIDList:t=[]}=e.result,r=this._filterValidGroupIDList(t);0!==r.length&&(e=Math.min(Math.ceil(r.length/10),5),Promise.all(Array.from({length:e},(e,t)=>{var t=10*t,s=Math.min(10+t,r.length);return this._fetchGroupRevokeNotice(r.slice(t,s))})).catch(e=>console.error(e)))}_fetchGroupRevokeNotice(s){return h(this,void 0,void 0,function*(){var e;try{var t=yield function(o){return h(this,void 0,void 0,function*(){let{appStore:e,constants:{OuterConstant:s},common:r}=mn.core,n=e.groupStore.getGroupMap(),t={NotifyReqList:o.map(e=>{var t=n.get(e);return{NotifyType:1,Limit:20,Type:r.isCommunity({type:t.type,groupID:e})?s.GRP_COMMUNITY:void 0,GroupId:e,BeginTime:(null==t?void 0:t._lastRevokedTime)||0,EndTime:1e3*mn.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:n=""}}=e,o="GROUP"+i,o=this._messageHelper.generateRevokeMessage({conversationID:o,sequence:t,random:s,clientTime:e,revoker:r,revokeReason:n});a.push(o)}),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 gi{constructor(e){this._historyMessageListFetchAnchors=new Map,this._core=e,this._messageHelper=new ii(e)}getRoamingMessagesByAnchor(_){return h(this,void 0,void 0,function*(){var n;try{var{conversationID:o,count:e,messageID:r,time:i,direction:a}=_;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(o)){let e=this._historyMessageListFetchAnchors.get(o);t=e.lastMessageTime,s=e.messageKey}}var l=o.replace(qn,""),c=yield function(o){return h(this,void 0,void 0,function*(){var{peerAccount:e,count:t,lastMessageTime:s,messageKey:r,direction:n}=o,e={Peer_Account:e,MaxCnt:t,WithRecalledMsg:1,LastMsgTime:s,MsgKey:r,GetDirection:n};return mn.core.common.buildAndSendPacket({servcmd:"openim.getroammsg",data:e})})}({count:e,lastMessageTime:t,messageKey:s,peerAccount:l,direction:a});if(c){let{MsgList:t=[],Complete:e,MsgKey:s,LastMsgTime:r}=c;this._historyMessageListFetchAnchors.set(o,{messageKey:s,lastMessageTime:r});var u=[];for(let e=0;e<t.length;e++){var d=t[e],p=this._parseMessage(d);u.push(p)}var g=this._core.message.messageHelper.filterValidMessages(u);return{messageList:g,nextReqMessageIDFromServer:null==(n=g[0])?void 0:n.ID,lastMessageTime:r,hasNoMoreHistoryMessage:1===e}}}catch(e){throw new this._core.helper.ChatError({code:null==e?void 0:e.code})}})}clearHistoryMessageListFetchAnchors(e){this._historyMessageListFetchAnchors.delete(e)}reset(){this._historyMessageListFetchAnchors.clear()}_parseMessage(e){var t=qn,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 _i=new class{constructor(){this._clearedConversations=new Set,this._fetchedCompleteConversations=new Set}init(e){this._core=e,this._groupMessageHistory=new hi(e),this._c2cMessageHistory=new gi(e),this._messageHelper=new ii(e),e.helper.registerApi({apiName:"getMessageList",context:this}),e.helper.registerApi({apiName:"getMessageListHopping",context:this}),e.helper.registerApi({apiName:"clearHistoryMessage",context:this})}getMessageList(e){return h(this,void 0,void 0,function*(){try{var{conversationID:t,nextReqMessageID:s}=e,r=Vn;if("@TIM#SYSTEM"===t)return{code:0,data:{messageList:[],isCompleted:!1,nextMessageSeq:""}};var n=this._core.ssoLog.createSSOLogData({method:"getMessageList"}),o=this._getAvailableLocalMessagesCount({conversationID:t,nextReqMessageID:s});if(this._needFetchHistoryMessageList({conversationID:t,availableLocalMessagesCount:o,targetCount:r})){let e=null;if(t.startsWith(xn)?e=yield this._groupMessageHistory.getRoamingMessagesByAnchor({conversationID:t,sequence:Number(s),count:r,direction:fn.FORWARD}):t.startsWith(qn)&&(e=yield this._c2cMessageHistory.getRoamingMessagesByAnchor({conversationID:t,messageID:s,count:r,direction:fn.FORWARD})),e){var{nextReqMessageIDFromServer:i,hasNoMoreHistoryMessage:a,messageList:l}=e,c=this._core.message.messageDataHandler.prependLocalMessageList({messageList:l,conversationID:t}),u=t,{appStore:d,message:h,OuterConstant:p}=mn.core,d=d.conversationStore.getConversation(u),g=h.messageDataHandler.getLocalMessageList(u);if(d&&0!==g.length&&u!==p.CONV_SYSTEM){var _=[];for(let e=0;e<g.length;e++)"in"!==g[e].flow?"out"!==g[e].flow||g[e].isRead||g[e].setIsRead(!0):_.push(g[e]);let t=0;if(d.type===p.CONV_C2C){let e=_.slice(-d.unreadCount).filter(e=>e.isRevoked).length;t=_.length-d.unreadCount-e}else t=_.length-d.unreadCount;for(let e=0;e<t&&!_[e].isRead;e++)_[e].setIsRead(!0)}yield jn(t),t.startsWith(qn)&&(yield Bn({messageList:l,conversationID:t}));var m=this._core.message.messageDataHandler.getLocalMessageList(t).slice(0,c.length+o),v=m.filter(e=>e.isRevoked),f=(yield this._messageHelper.updateRevokerInfo(v),a&&this._fetchedCompleteConversations.add(t),{nextReqMessageID:a?"":String(i),messageList:m,isCompleted:a}),I=m.map(e=>e.sequence);return n.setLogInfo({message:`conversationID: ${t} nextReqMessageID: ${s}
|
|
3
|
+
availableLocalMessagesCount: ${o} sequenceList: ${JSON.stringify(I)} `}).end(),{code:0,data:f}}return{code:0,data:{messageList:[],isCompleted:!1,nextReqMessageID:""}}}return n.setLogInfo({message:`conversationID: ${t} nextReqMessageID: ${s} availableLocalMessagesCount: ${o}}`}).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 o,i;let{conversationID:e,sequence:a,time:t,direction:l=fn.FORWARD}=r,c=this._core.helper["isEmpty"];if(![fn.BACKWARD,fn.FORWARD].includes(l))throw new this._core.helper.ChatError({message:"direction must be 0 or 1"});let{count:s=Vn}=r,u=(s=s>Vn?Vn:s,null);if(e.startsWith(xn)){if(u=yield this._groupMessageHistory.getRoamingMessagesByAnchor({conversationID:e,sequence:a,count:s,direction:l})){let{nextReqMessageIDFromServer:t,hasNoMoreHistoryMessage:s,messageList:r,invisibleSequenceList:n}=u;if(this._core.message.messageDataHandler.storeSparseMessageList(r),l===fn.FORWARD){let e=s&&t<1;return{code:0,data:{messageList:r,isCompleted:e,nextMessageSeq:e?"":t}}}if(l!==fn.BACKWARD)return{code:0,data:u};{if(c(r)&&c(n))return{code:0,data:{messageList:[],isCompleted:!0,nextMessageSeq:""}};let e=(null==(o=null==r?void 0:r[r.length-1])?void 0:o.sequence)||0,t=(null==(i=null==n?void 0:n[n.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(qn)&&(u=yield this._c2cMessageHistory.getRoamingMessagesByAnchor({conversationID:e,count:s+1,time:t,direction:l}))){let{messageList:e,lastMessageTime:t,hasNoMoreHistoryMessage:s}=u;return s||(l===fn.FORWARD?e.shift():e.pop()),this._core.message.messageDataHandler.storeSparseMessageList(e),{code:0,data:{messageList:e,isCompleted:s,nextMessageTime:s?"":t}}}})}clearHistoryMessage(g){return h(this,void 0,void 0,function*(){var t;let{appStore:e,common:{ChatError:s,getCurrentUserID:r},OuterConstant:{CONV_C2C:n,CONV_GROUP:o},message:i,apiMap:a,ssoLog:l}=this._core,c=e.conversationStore.getConversation(g);if(!c)throw new s({code:$n});var u=l.createSSOLogData({method:"clearHistoryMessage"}),d=(u.setLogInfo({message:"convID:"+g}),{fromAccount:r()}),p=c["type"];p===n?(d.type=Pn,d.toAccount=g.replace(n,"")):p===o&&(d.type=Un,d.toGroupID=g.replace(o,""));try{yield null==(t=null==a?void 0:a.setMessageRead)?void 0:t.call(a,{conversationID:g});let e=yield function(n){return h(this,void 0,void 0,function*(){var{fromAccount:e,type:t,toAccount:s,toGroupID:r}=n,e={From_Account:e,Type:t,To_Account:s,ToGroupid:r};return mn.core.common.buildAndSendPacket({servcmd:"recentcontact.clear_msg",data:e})})}(d);return e&&(u.end(),i.messageDataHandler.deleteConversationMessageList(g),this._clearedConversations.add(g),this._fetchedCompleteConversations.delete(g),this._c2cMessageHistory.clearHistoryMessageListFetchAnchors(g),this._updateConversationLastMessage(g)),{code:0,data:{conversationID:g}}}catch(e){let t=e["errorCode"],s=new this._core.helper.ChatError({functionName:"clearHistoryMessage",code:t});throw u.setError(s).end(),s}})}_updateConversationLastMessage(e){var t=this._core["appStore"];t.conversationStore.updateConversation(e,{lastMessage:this._generateLastMessage()},{needSort:!0})}_getAvailableLocalMessagesCount({conversationID:e,nextReqMessageID:t}){var s=this._core.message.messageDataHandler.getLocalMessageList(e),r=s["length"];if(!t)return r;let n=-1;return null!=e&&e.startsWith(qn)?n=s.findIndex(e=>e.ID===t):null!=e&&e.startsWith(xn)&&(n=s.findIndex(e=>t.includes("-")?e.ID===t:String(e.sequence)===t)),-1===n?0:n}_needFetchHistoryMessageList({conversationID:e,availableLocalMessagesCount:t,targetCount:s}){return!!this._clearedConversations.has(e)||t<s&&!this._fetchedCompleteConversations.has(e)}_getMessageListFromMemory(e){return h(this,arguments,void 0,function*({conversationID:t,nextReqMessageID:s,count:e}){var r=this._core.message.messageDataHandler.getLocalMessageList(t),n=r.length;let o=n,i={isCompleted:!1,nextReqMessageID:"",messageList:[]},a=0,l=n;return s?(l=r.findIndex(e=>t.startsWith(qn)?e.ID===s:String(e.sequence)===s),a=l>e?l-e:0,o=l):a=e<n?n-e:0,i.nextReqMessageID=0===a?"":this._generateNextReqMessageID({conversationID:t,targetIndex:a}),i.messageList=r.slice(a,l),i.isCompleted=o<=e,t.startsWith(qn)&&(yield jn(t),yield Bn({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)}_generateLastMessage(){return{lastTime:0,lastSequence:0,fromAccount:"",messageForShow:"",payload:null,type:"",isRevoked:!1,cloudCustomData:"",onlineOnlyFlag:!1,nick:"",nameCard:"",version:0,isPeerRead:!1,revoker:null}}reset(){this._clearedConversations.clear(),this._fetchedCompleteConversations.clear(),this._c2cMessageHistory.reset()}dispose(){this.reset()}},mi=new class{constructor(){this._core=null}init(e){e=(this._core=e).helper;e.registerApi({apiName:"translateText",context:this})}translateText(n){return h(this,void 0,void 0,function*(){try{var{sourceLanguage:t,sourceTextList:s,targetLanguage:e}=n,r=yield function(o,i){return h(this,void 0,void 0,function*(){var{sourceTextList:s,sourceLanguage:e,targetLanguage:t}=o,{store:r,common:n}=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 n.buildAndSendPacket({servcmd:"im_open_translate.ws_batch_trans_text",data:t});if(s){let{CmdErrorCode:e,TargetText:t}=s;return{cmdErrorCode:e,translatedTextList:t}}})}({sourceLanguage:t,sourceTextList:s,targetLanguage:e},this._core);if(r){let{cmdErrorCode:{ErrorCode:e,ErrorInfo:t},translatedTextList:s}=r;if(0===e)return{code:0,data:{translatedTextList:s}};throw{errorCode:e,errorInfo:t,message:t}}}catch(e){var{errorCode:t,errorInfo:s}=e||{};throw new this._core.helper.ChatError({functionName:"translateText",code:t,message:s})}})}},vi=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=Mn.ZH_PY}=s,r=(e.payload||{})["url"];var n=null==(n=this._core.store.get("login"))?void 0:n.userID,n=(e.from===n&&"out"===e.flow&&(r=e.payload.remoteAudioUrl),this._validateVoiceFormat(r),(null==(o=Ln.exec(r))?void 0:o[1])||"mp3"),o=Rn[t]||Dn;try{let s=yield function(e){var{store:t,common:s}=mn.core,{url:e,format:r,serverLanguageType:n}=e,n={BytesUrl:e,BytesEngServiceType:n,BytesVoiceFormat:r,Uint32Sdkappid:null==(e=t.get("instance"))?void 0:e.sdkAppId,Uint64SourceType:0};return s.buildAndSendPacket({servcmd:"im_open_speech.ws_sentence_recognition",data:n})}({url:r,format:n,serverLanguageType:o});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(!Ln.test(e))throw new this._core.common.ChatError({code:2119})}};class fi{constructor(e){var{constants:t,common:s,utils:r}=mn.core,{CONV_C2C:t,CONV_GROUP:n}=t.OuterConstant,{ID:e,tinyID:o,from:i,to:a,clientTime:s=s.timeManager.getServerTimeSeconds()||0,random:l,sequence:c,cloudCustomData:u="",nick:d="",avatar:h="",clientSequence:p,conversationType:g,groupID:_,_elements:m,time:v}=e,o=(this.ID=e||o+`-${s}-`+l,this.messageRandom=l,this.from=i,this.messageSender=i,this.time=v,this.messageSequence=c,this.clientSequence=p||c,this.clientTime=s,this.cloudCustomData=u,this.messageReceiver=a,this.avatar=h,this.nick=d,r.deepCopyWithMethods(m));o.forEach(e=>{e.payload=e.content,delete e.content}),this.messageBody=o,e?g.startsWith(t)?this.receiverUserID=a:g.startsWith(n)&&(this.receiverGroupID=a):_?(this.receiverGroupID=_,this.messageReceiver=_):a&&(this.receiverUserID=a,this.messageReceiver=a)}transformElementsToServerFormat(){return this.messageBody?Array.isArray(this.messageBody)?this.messageBody.map(e=>e.transformToServerFormat({isMergerMessage:!0})):this.messageBody.transformToServerFormat({isMergerMessage:!0}):null}}class Ii{static parseServerPushElement(e){var e=e["MsgContent"],{MsgList:e=[],CompatibleText:t,AbstractList:s,Title:r,PbMsgKey:n,JsonMsgKey:o}=e||{},e=e.map(e=>Hn(e));return new Ii({messageList:e,title:r,abstractList:s,compatibleText:t,pbDownloadKey:n,downloadKey:o})}constructor(e){this.type=mn.core.constants.OuterConstant.MSG_MERGER;let{messageList:t,title:s,abstractList:r,compatibleText:n,pbDownloadKey:o="",downloadKey:i="",version:a=0,layersOverLimit:l=!1}=e,c=[];t.forEach(e=>{e&&(e=new fi(e),c.push(e))}),this.content={messageList:c,title:s,abstractList:r,compatibleText:n,version:a,downloadKey:i,pbDownloadKey:o,layersOverLimit:l}}validateBeforeSend(){var e=mn.core.helper["isEmpty"];return e(this.content.messageList)?{isValid:!1,error:{message:"content is invalid"}}:{isValid:!0}}transformToServerFormat(e){var{isMergerMessage:e=!1}=e||{},{abstractList:e,compatibleText:t,downloadKey:s,layersOverLimit:r,pbDownloadKey:n,title:o,version:i,messageList:a}=e?this.payload:this.content;return{MsgType:this.type,MsgContent:{AbstractList:e,CompatibleText:t,JsonMsgKey:s,LayersOverLimit:r,PbMsgKey:n,Title:o,Version:i,MsgList:Wn(a)}}}}var Si=new class{init(e){let{message:t,helper:s,constants:{OuterConstant:r}}=this._core=e;t.messageFactory.registerElementClass(r.MSG_MERGER,Ii),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 Ii(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 o=function(t){let e="utf-8";mn.core.helper.IN_BROWSER&&document&&(e=document.charset.toLowerCase());let s,r=0,n;if(n=t.length,"utf-8"===e||"utf8"===e)for(let e=0;e<n;e++)(s=t.codePointAt(e))<=127?r+=1:s<=2047?r+=2:s<=65535?r+=3:(r+=4,e++);else if("utf-16"===e||"utf16"===e)for(let e=0;e<n;e++)(s=t.codePointAt(e))<=65535?r+=2:(r+=4,e++);else r=t.replace(/[^\x00-\xff]/g,"aa").length;return r}(JSON.stringify(a));let r=a,n=null;if(11264<o){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:Wn(e)};return mn.core.common.buildAndSendPacket({servcmd:"im_long_msg.save_relay_json_msg",data:e})})}(r),s=r["payload"];n=new Ii(Object.assign(Object.assign({},s),{messageList:[],downloadKey:e,pbDownloadKey:t})),r.setElement(n)}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 n&&i.setElement(a._elements),{code:0,data:{message:i}}}catch(e){throw console.error(e),e}})}downloadMergerMessage(o){return h(this,void 0,void 0,function*(){try{var e=o.payload,t=e["downloadKey"],s=p(e,["downloadKey","pbDownload","type","messageList"]),r=((yield function(e){return h(this,void 0,void 0,function*(){return mn.core.common.buildAndSendPacket({servcmd:"im_long_msg.get_relay_json_msg",data:{JsonMsgKey:e}})})}(t))||{})["MsgList"],n=null==r?void 0:r.map(e=>{e=Hn(e);return new fi(e)});return"function"==typeof o.isOnlineMessage?o.setElement({type:o.type,content:Object.assign({messageList:n},s)}):(o.payload.messageList=n,o.payload.downloadKey="",o.payload.pbDownloadKey=""),o}catch(e){console.error(e)}})}},Ei=new class{init(e){this._core=e,this._core.helper.registerExperimentalAPI("sendComboMessage",this)}sendComboMessage(a){return h(this,void 0,void 0,function*(){let{appStore:t,message:e,common:{getCurrentUserID:s},utils:{isArray:r}}=this._core,{GroupId:n,To_Account:o}=a,i=(a.From_Account=a.From_Account||s(),null);if(n){i=this._generateGroupMessage(Object.assign(Object.assign({},a),{ToGroupId:n}));let e=t.userStore.getUserProfile(s());i.level=(null==e?void 0:e.level)||0,r(o)&&0<o.length&&(i._receiverList=o)}else o&&(i=this._generateC2CMessage(a));return e.messageSender.sendMessage(i,a)})}_generateC2CMessage(e){var{message:t,OuterConstant:{CONV_C2C:s}}=this._core,e=t.messageHelper.parseServerPushMessage(e),t=t.messageFactory.createMessage(Object.assign(Object.assign({},e),{conversationType:s,flow:kn.OUT})),s=e["elements"];return t.setElement(s),t}_generateGroupMessage(e){var{message:t,OuterConstant:{CONV_GROUP:s}}=this._core,e=t.messageHelper.parseServerGroupMessage(e),t=t.messageFactory.createMessage(Object.assign(Object.assign({},e),{conversationType:s,flow:kn.OUT})),s=e["elements"];return t.setElement(s),t}},Ci=new class{constructor(){this.name="MessageEnhancer"}install(e){this._core=e,mn.init(e),ri.init(e),ui.init(e),pi.init(e),_i.init(e),Yn.init(e),mi.init(e),vi.init(e),zn.init(e),Si.init(e),Xn.init(e),Ei.init(e),e.helper.registerValidateConfig({auth:si,params:ti}),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),pi.dispose(),_i.dispose(),zn.dispose(),Xn.dispose()}_reset(){_i.reset()}},Mi=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:n,qs:o,headers:i={},resources:a,dataType:l="text",uploadByIP:c,uploadIP:u}=g,d=n;if(o){let e=this._queryString(o);e&&(d+=(d.includes("?")?"&":"?")+e)}let h=new XMLHttpRequest;h.open(r.toUpperCase(),d,!0),h.responseType=l;var p=Object.assign({},i);if(c&&u&&(p.host=u),!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,c&&u),e=this._buildResponse(h,e);if(200===h.status)_(null,e);else{if(u&&!d.includes(u))return g.url=this._domainName2IP(d,u),g.uploadByIP=!0,this.request(g,_);_({code:h.status,message:JSON.stringify(h.responseText)},e)}},h.onerror=()=>{var e=this._getResponseBody(h,s,c&&u),e=this._buildResponse(h,e),t={code:h.status,message:0===h.status?"CORS blocked or network error":JSON.stringify(h.responseText)};_(t,e)},g.onProgress&&h.upload&&(h.upload.onprogress=e=>{var{total:e,loaded:t}=e,s=Math.min(Math.floor(100*t/e),100);g.onProgress({total:e,loaded:t,percent:s/100})}),h.send(a),h})}_buildResponse(e,t){let s={};return e.getAllResponseHeaders().trim().split("\n").forEach(e=>{var t;e&&([e,t]=e.split(":").map(e=>e.trim()),s[e.toLowerCase()]=t)}),{statusCode:e.status,statusMessage:e.statusText,headers:s,data:t}}_getResponseBody(e,t,s){return 200===e.status&&t?{location:t,uploadIP:s}:{response:e.responseText,uploadIP:s}}_queryString(s,r="&",n="="){var{isEmpty:e,isPlainObject:t}=null==(e=this._core)?void 0:e.utils;return e(s)?"":t(s)?Object.keys(s).map(e=>{let t=encodeURIComponent(e)+n;return Array.isArray(s[e])?s[e].map(e=>t+encodeURIComponent(e)).join(r):t+encodeURIComponent(s[e])}).filter(Boolean).join(r):void 0}_domainName2IP(e,t){return e.replace(/^http(s)?:\/\/(.*?)\//,`https://${t}/`)}};let yi=["unknown","image","video","audio","log"];var Bi,Ai=new class{init(e){this._core=e}request(s,r){let e,{MINI_APP_NAMESPACE:n,IN_ALIPAY_MINI_APP:o,IN_UNI_IOS_APP:i}=null==(e=this._core)?void 0:e.utils,{resources:a="",headers:l={},url:c,downloadUrl:u=""}=s,d=c,h=null;var g=u?u.match(/^(https?:\/\/[^/]+\/)([^/]*\/?)(.*)$/):null;if(g){var g=decodeURIComponent(g[3]),g=g.includes("?")?g.split("?")[0]:g||"",g={key:s.fileKey||g,success_action_status:200,"Content-Type":""},_={};if(i){let[e,t]=c.split("?sign=");t&&(d=e+"?sign="+encodeURIComponent(t),_.sign=decodeURIComponent(t),_.signature=decodeURIComponent(t))}let t={url:d,header:l,name:"file",filePath:a,formData:Object.assign(Object.assign({},g),_),timeout:s.timeout||3e5};if(o){let e=p(t,["name"]);t=Object.assign(Object.assign({},e),{fileName:"file",fileType:s.fileType?yi[s.fileType]:"image"})}return(h=n.uploadFile(Object.assign(Object.assign({},t),{success:e=>{this._handleResponse({response:e,downloadUrl:u,callback:r})},fail:e=>{this._handleResponse({response:e,downloadUrl:u,callback:r})}}))).onProgressUpdate&&h.onProgressUpdate(e=>{s.onProgress&&s.onProgress({total:e.totalBytesExpectedToSend||0,loaded:e.totalBytesSent||0,percent:e.progress?Math.floor(e.progress)/100:0})}),h}console.warn("message Invalid download URL format")}_handleResponse(e){var{downloadUrl:e,response:t,callback:s}=e,r={};if(t.header)for(let e in t.header)t.header.hasOwnProperty(e)&&(r[e.toLowerCase()]=t.header[e]);var n=+t.statusCode;200==n?s(null,{statusCode:n,headers:r,data:Object.assign(Object.assign({},t.data),{location:e})}):s({code:n,message:JSON.stringify(t.data)},{statusCode:n,headers:r,data:void 0})}};function Ti(e){return"file"===Object.prototype.toString.call(e).match(/^\[object (.*)\]$/)[1].toLowerCase()}function Oi(e){e=e||99999999;return Math.round(Math.random()*e)}function Di(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 Ri(e){return Array.from({length:8},()=>Math.floor(65536*(1+Math.random())).toString(16).substring(1)).join("")+"-"+e}function Li(e,t){return Math.round(Number(e)*10**t)/10**t}function Ni(e){return e<1024?e+"B":e<1048576?Math.floor(e/1024)+"KB":Math.floor(e/1048576)+"MB"}function bi(e){return e<=1048576?Li(e/1024,1)+"KB/s":Li(e/1048576,1)+"MB/s"}let Gi="TIMImageElem",wi="TIMSoundElem",Pi="TIMFileElem",Ui="TIMVideoFileElem",ki="RichMediaMessagePlugin",Fi=["rich.my-imcloud.com","imrich.qcloud.com"],$i=1,qi=2,xi=3,Vi=255,ji=(!function(e){e.UNSENT="unSend",e.SUCCESS="success",e.FAIL="fail"}(Bi=Bi||{}),{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 Ki=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(ji).some(e=>e.test(t))}extractFileFromInput(e){var{isArray:t}=this._core["utils"];return Ti(e)?e:function(t){if("object"==typeof t&&null!==t){t=Object.getPrototypeOf(t);if(null===t)return 1;let e=t;for(;null!==Object.getPrototypeOf(e);)e=Object.getPrototypeOf(e);return t===e}}(e)&&"undefined"!=typeof uni?t(e.tempFiles)&&0<e.tempFiles.length?e.tempFiles[0]:t(e.files)?e.files[0]:e.tempFile||null:e instanceof HTMLInputElement&&e.files&&0<e.files.length?e.files[0]:null}probeImageWidthHeight(s){return 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=Fi;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=Fi}return t}getPlatform(){var e;return null==(e=this._core)?void 0:e.utils.platform}generateUUID(e,t){let s,r=`${this.getSDKAppID()}-${this.getCurrentUserID()}-`+(null==(s=this._core)?void 0:s.utils.randomString());return t?r+"."+t:(e=(t=e.name||e.value||e.url||e.tempFilePath)&&t.slice(t.lastIndexOf(".")+1),r=e?r+"."+e:r)}processResourceUrl(e){if(!e)return"";let t=e;var s=this.getFileDownloadProxy(),r=this.getAuthKey(),n=this.getFileDNList(),e=(s&&(e.startsWith("http://")?t=e.replace(/^http:\/\/[^/]+/,s):e.startsWith("https://")&&(t=e.replace(/^https:\/\/[^/]+/,s))),r&&-1===t.indexOf("authKey=")&&function(e,t){let s=!1;if(e){var e=e.match(/:\/\/([0-9]?\.)?(.[^/:]+)/),r=e&&e[2]||"";if(r.includes("rich-dev"))return!0;for(let e=0;e<t.length;e++)if(r.endsWith(t[e])){s=!0;break}}return s}(t,n));return t=e?-1<t.indexOf("?")?t+"&authKey="+r:t+"?authKey="+r:t}getCurrentUserID(){var e;return null==(e=null==(e=this._core)?void 0:e.store.get("login"))?void 0:e.userId}getSDKAppID(){var e;return null==(e=null==(e=this._core)?void 0:e.store.get("instance"))?void 0:e.sdkAppId}getFileDownloadProxy(){var e;return(null==(e=null==(e=this._core)?void 0:e.store.get("instance"))?void 0:e.fileDownloadProxy)||""}getFileUploadProxy(){var e;return(null==(e=null==(e=this._core)?void 0:e.store.get("instance"))?void 0:e.fileUploadProxy)||""}getAuthKey(){var e;return(null==(e=null==(e=this._core)?void 0:e.store.get("login"))?void 0:e.authKey)||""}isPrivateNetWork(){var e;return null==(e=null==(e=this._core)?void 0:e.store.get("instance"))?void 0:e.proxyServer}getPlatformFlags(){var{IN_BROWSER:e,IN_MINI_APP:t,IN_RN_APP:s,IN_UNI_NATIVE_APP:r}=null==(e=this._core)?void 0:e.utils;return{IN_BROWSER:e,IN_MINI_APP:t,IN_RN_APP:s,IN_UNI_NATIVE_APP:r}}isEmpty(e){var t=(null==(t=this._core)?void 0:t.utils)["isEmpty"];return t(e)}_probeImageDimensionsMiniApp(e){let t,s=((null==(t=this._core)?void 0:t.utils)||{}).MINI_APP_NAMESPACE;return new Promise(t=>{s.getImageInfo({src:e,success:e=>t({width:e.width,height:e.height}),fail:()=>t({width:0,height:0})})})}_shouldSkipProbing(){var{IN_RN_APP:e,IS_IE:t,IE_VERSION:s}=(null==(e=this._core)?void 0:e.utils)||{};return e||t&&9===s}_probeImageDimensionsWeb(r){return new Promise(e=>{let t=new Image,s=()=>{t.onload=null,t.onerror=null,t.src=""};t.onload=()=>{e({width:t.width,height:t.height}),s()},t.onerror=()=>{e({width:0,height:0}),s()},t.src=r})}},Wi=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?Ai:Mi,null!=(t=this.httpRequest)&&t.init(e)}uploadToCOS(l){return h(this,void 0,void 0,function*(){var t=ki+" uploadToCOS",e=l["file"];this.uploadFileType=l.uploadFileType,console.log(t+" options:",l);try{var s=Date.now(),r=yield this._createCosOptions(l),n=yield this._uploadFile(r),o=(this._handleUploadError(n,l),this._createUploadResult(e,n)),i=Date.now()-s,a=`size:${Ni(e.size)} time:${i}ms speed:`+bi(1e3*e.size/i);return console.log(t+` ok. name:${e.name} `+a),{uploadOptions:r,response:o}}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 Di(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:Di(Date.now(),!1),uploadSpeed:bi(1e3*e.size/Di(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 n=yield this._fetchCosSignatureUrl({fileType:this.uploadFileType,fileName:e,uploadMethod:s,duration:this.duration,userID:p.message.from,conversationType:r}),{uploadUrl:o,downloadUrl:i,requestSnapshotUrl:a,thumbUrl:l,largeUrl:c,fileKey:u}=n,d=!Ki.isPrivateNetWork()&&n.uploadIP;return{url:this._getRawOrUploadProxyUrl(o),fileType:this.uploadFileType,fileName:e,resources:t,downloadUrl:i,requestSnapshotUrl:a,thumbUrl:l,largeUrl:c,fileKey:u,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(ki+" prepareUploadParams:",e);var t=e["file"],{IN_MINI_APP:s,IN_RN_APP:r}=Ki.getPlatformFlags(),s=s||r,r=s&&e.message.type!==Pi,e=t["name"],e=e.slice(e.lastIndexOf(".")),e=""+Oi(999999)+e;return{fileName:Ri(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=ki+" fetchCosSignatureUrl",s=Ki.isSimpleCos(),r=this._prepareCosRequestData(e),n=s?"im_cos_msg.simple_sig":"im_cos_msg.pre_sig";try{let e=yield function(n,o,i){return h(this,void 0,void 0,function*(){try{var{helper:e,channel:t}=i,s=e.generateCosSpecifiedData({servcmd:n,data:o}),r=s.head.seq+n;return yield t.sendPacket(s,{requestId:r})}catch(e){throw console.warn("getCosSig error:",e),e}})}(n,r,this._core);this.fetchCosTryCount=0;var o=this._processResponse(e);return console.log(t+` ok. isSimpleCos:${s} data:`,o),o||{}}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=Ki.isSimpleCos(),l=s?null==(t=null==e?void 0:e.rpt_pre_sig)?void 0:t[0]:e;if(!l)return{};if(s){let{str_final_ip:e,rpt_pre_sig:t,uint32_file_id:s,uint32_exist_flag:r,str_download_url:n,str_upload_url:o,str_snapshot_url:i,str_file_key:a}=l;return{uploadIP:e,preSig:t,fileID:s,existFlag:r,downloadUrl:n,uploadUrl:o,requestSnapshotUrl:i,fileKey:a}}let{upload_url:r,download_url:n,snapshot_url:o,thumb_url:i,large_url:a,file_key:c}=l;return{uploadUrl:r,downloadUrl:n,requestSnapshotUrl:o,thumbUrl:i,largeUrl:a,fileKey:c}}_prepareCosRequestData(e){return Ki.isSimpleCos()?{uint32_upload_method:e.uploadMethod,uint32_platform:Ki.getPlatform(),uint32_sdkappid:Ki.getSDKAppID(),str_user_id:e.userID,uint32_scene:e.conversationType,rpt_upload_object:[{uint32_file_id:1,uint32_file_type:e.fileType,str_file_name:e.fileName}]}:{file_type:e.fileType,file_name:e.fileName,upload_method:e.uploadMethod,Duration:e.duration}}_uploadFile(n){return h(this,void 0,void 0,function*(){return new Promise((s,r)=>{this.httpRequest.request(n,(e,t)=>{e&&this.uploadFileTryCount<this.maxRetries&&this.shouldRetry(e)?(this.uploadFileTryCount++,this._uploadFile(n).then(s).catch(r)):(this.uploadFileTryCount=0,e?r(e):s(t))})})})}shouldRetry(e){return!(!e||5!==Math.floor(e.statusCode/100)&&(!this.isTimeRelatedError(e)||!this._isClockOutOfSync(e)||(this._syncSystemClock(e),0)))}isTimeRelatedError(e){var t,s;try{var r=null==(t=e.error)?void 0:t.Code,n=null==(s=e.error)?void 0:s.Message;return"RequestTimeTooSkewed"===r||"AccessDenied"===r&&"Request has expired"===n}catch(e){return!1}}_isClockOutOfSync(e){var t,e=(null==(t=e.headers)?void 0:t.date)||(null==(t=e.headers)?void 0:t.Date)||(null==(t=e.error)?void 0:t.ServerTime);return!!e&&(t=Date.now(),e=Date.parse(e),3e4<=Math.abs(t+this.systemClockOffset-e))}_syncSystemClock(e){var t,s=(null==(t=e.headers)?void 0:t.date)||(null==(t=e.headers)?void 0:t.Date)||(null==(t=e.error)?void 0:t.ServerTime);if(s){let e=Date.now(),t=Date.parse(s);this.systemClockOffset=t-e}}_getRawOrUploadProxyUrl(e){var t=Ki.getFileUploadProxy();let s=e;return s=t?e.replace(/^https:\/\/[^/]+/,t):s}_isC2CConversation(e){return"C2C"===e.slice(0,3)}};let Hi=2108,Yi=2251,zi=2252,Ji=["jpg","jpeg","gif","png","bmp","image","webp"],Qi=20971520,Xi={JPG:1,JPEG:1,GIF:2,PNG:3,BMP:4,UNKNOWN:255};class Zi{constructor(e,t){this.instanceID=Oi(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=Ki.addAuthToUrl(e.imageUrl||e.url||""),this.url=Ki.addAuthToUrl(e.url||t)}setSizeType(e){this.sizeType=e}setType(e){this.type=e}setImageUrl(e){e&&(this.imageUrl=Ki.addAuthToUrl(e))}getImageUrl(){return this.imageUrl}}function er(e){var{originUrl:t,originWidth:e,originHeight:s,min:r=198}=e,n=parseInt(e)||0,s=parseInt(s)||0,o={url:void 0,width:0,height:0};if((n<=s?n:s)<=r)o.url=t,o.width=n,o.height=s;else{s<=n?(o.width=Math.ceil(n*r/s),o.height=r):(o.width=r,o.height=Math.ceil(s*r/n));let e=t&&-1<t.indexOf("?")?t+"&":t+"?";o.url=198===r?e+"imageView2/3/w/198/h/198":e+"imageView2/3/w/720/h/720"}return void 0===t?p(o,["url"]):o}class tr{constructor(e){this._imageMemoryURL="",this._percent=0,this.type=Gi;var{uuid:e,file:t,imageFormat:s,imageInfoArray:r=[]}=e;this._imageMemoryURL=this.createImageDataAsURL(t),this.content={imageFormat:s,uuid:e,imageInfoArray:[]},this.initImageInfoArray(r),this.autoFixUrl()}static parseServerPushElement(e){let t=e["MsgContent"],{ImageFormat:s,ImageInfoArray:r,UUID:n}=t,o=r.map(e=>({size:e.Size,type:e.Type,width:e.Width,height:e.Height,url:e.URL}));return new tr({imageFormat:s,imageInfoArray:o,uuid:n})}createImageDataAsURL(e){let t="";var{IN_MINI_APP:s,IN_RN_APP:r,IN_BROWSER:n}=Ki.getPlatformFlags();return t=e&&((s||r)&&(t=e.url),n)?window.URL.createObjectURL(e):t}initImageInfoArray(t=[]){var s={type:0,size:0,width:0,height:0,url:""};for(let e=0;e<3;e++){var r=t[e]||Object.assign({},s),r=new Zi(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=Xi[e.toUpperCase()]||Xi.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],er({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:Ki.removeAuthToUrl(e.imageUrl)}))}}var sr=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(Gi,tr),e.subscribeInnerEvent(s.DESTROY,this._dispose,this)}createImageMessage(n){var o,i,a,e,t;try{let e=this._core.ssoLog.createSSOLogData({method:"createImageMessage"}),t=(console.log(ki+" createImageMessage options:",n),null==(o=this._core.store.get("login"))?void 0:o.userId),s=null==(a=null==(i=this._core)?void 0:i.message.messageFactory)?void 0:a.createMessage(Object.assign(Object.assign({},n),{from:t})),r=this._processImage(n);n.payload.file=r;var l={imageFormat:Xi.UNKNOWN,uuid:Ki.generateUUID(r),file:r,imageInfoArray:[]},c=new tr(l);return s.setElement(c),this._messageOptionsMap.set(s.clientSequence,n),console.log(ki+" createImageMessage OK imageMessage:",s),e.end(),s}catch(n){throw null!=(t=(e=this._core.ssoLog.getSSOLogData("createImageMessage")).setError)&&t.call(e,n).end(),console.error(ki+" createImageMessage error:",n),n}}upload(r){return h(this,void 0,void 0,function*(){console.log(ki+" uploadImage message:",r);var e=r.getElements()[0],t=this._messageOptionsMap.get(r.clientSequence).payload["file"],t=(this._validateBeforeUploadImage(t),yield this._performImageUpload(e,r,t)),s=this._generateImageInfo(t);return e.updateImageFormat(null==t?void 0:t.fileType),e.updateImageInfoArray(s),r})}_performImageUpload(r,n,s){return h(this,void 0,void 0,function*(){var e=n["to"],e={uploadFileType:$i,file:s,to:e,message:n,onProgress:e=>{var t,s;r.updatePercent(e),null!=(s=null==(t=this._messageOptionsMap.get(n.clientSequence))?void 0:t.onProgress)&&s.call(t,e)}},{uploadOptions:e,response:t}=yield Wi.uploadToCOS(e);return this._parseResponse(e,t)})}_generateImageInfo(e){console.log(ki+" generateImageInfo");var{location:e,fileSize:t,width:s,height:r,smallImageUrl:n,smallImageWidth:o,smallImageHeight:i,largeImageUrl:a,largeImageWidth:l,largeImageHeight:c,imageInfoArray:u}=e,e=Ki.addAuthToUrl(e),d={size:t,url:e,width:s,height:r};return 0<(null==u?void 0:u.length)?this._processImageInfoArray(u,t):n&&a?[Object.assign({},d),{largeImageUrl:a,largeImageWidth:l,largeImageHeight:c},{smallImageUrl:n,smallImageWidth:o,smallImageHeight:i}]:[Object.assign({},d),this._generateThumbInfo(e,s,r,720),this._generateThumbInfo(e,s,r,198)]}_generateThumbInfo(e,t,s,r){return er({originUrl:e,originWidth:t,originHeight:s,min:r})}_processImageInfoArray(e,t){let s,r,n;for(var o of e)1===o.type?(r=o,r.size=t):2===o.type?(n=o,n.size=t):(s=o,s.size=t);return[Object.assign({},s),Object.assign({},n),Object.assign({},r)]}_parseResponse(r,n){return h(this,void 0,void 0,function*(){console.log(ki+" parseResponse");try{var{thumbUrl:e,largeUrl:t,downloadUrl:s}=r;if(e&&t&&(yield this._getImageInfoByUrl(e,n,"thumb"),yield this._getImageInfoByUrl(t,n,"large")),Ki.isSimpleCos()&&!Ki.isPrivateNetWork()&&(yield this._getImageInfoArray(s,n),null!=n)&&n.uploadIP){let e=this._extractDomainFromUrl(s);e&&(yield this._getDownloadIP(e,n))}return n}catch(e){throw console.error("Failed to parse response:",e),e}})}_extractDomainFromUrl(e){try{var t=e.match(/:\/\/([^\/]+)/);return t?t[1]:null}catch(e){return console.warn("Failed to extract domain from URL:",e),null}}_getImageInfoByUrl(r,n,o){return h(this,void 0,void 0,function*(){try{var e=Ki.addAuthToUrl(r),{width:t=0,height:s=0}=yield Ki.probeImageWidthHeight(e);n.width=t,n.height=s,"thumb"===o?(n.smallImageUrl=r,n.smallImageWidth=t,n.smallImageHeight=s):(n.largeImageUrl=r,n.largeImageWidth=t,n.largeImageHeight=s)}catch(e){console.warn(`Failed to get ${o} image info:`,e)}})}_validateBeforeUploadImage(e){var t=(null==(t=this._core)?void 0:t.helper)["ChatError"];if(!e)throw new t({code:Yi});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(ki+" _processImage error:",e),e}}_processMiniAppImageFile(e){Ti(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=Ki.extractFileFromInput(e);if(e)return e;throw new t({message:"Invalid file. Pass either `e.target` (from file input) or a File object"})}_getDownloadIP(r,n){return h(this,void 0,void 0,function*(){var e=ki+" 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},n=e.generateProtocolData({servcmd:s,data:r}),o=n.head.seq+s;return yield t.sendPacket(n,{requestId:o})}catch(e){throw console.warn("getFinalIP error:",e),e}})}(r,this._core);s&&s.str_final_ip&&(console.log(e+" ok. downloadIP:"+s),(t=n.location.split("/"))[0]=s.str_final_ip,n.location=t.join("/"))}catch(e){console.warn(e)}})}_getImageInfoArray(s,r){return h(this,void 0,void 0,function*(){var t=ki+"._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},n=e.generateProtocolData({servcmd:s,data:r}),o=n.head.seq+s;return yield t.sendPacket(n,{requestId:o})}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)),Ji.indexOf(r.toLowerCase())<0)throw new s.ChatError({code:zi})}_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:Hi});if(r>=Qi)throw new s.ChatError({message:"File size exceeds limit: "+Ni(Qi)})}_reset(){this._messageOptionsMap.clear()}_dispose(){this._reset();var{notificationCenter:e,InnerEvent:t}=this._core;e.unSubscribeInnerEvent(t.DESTROY,this._dispose,this)}};let or=2108,nr=2401,ir="2.5.0",rr="1.18.0",ar=104857600;function cr(e,t){let r=e.split("."),n=t.split("."),o=Math.max(r.length,n.length);for(;r.length<o;)r.push("0");for(;n.length<o;)n.push("0");for(let s=0;s<o;s++){let e=parseInt(r[s]),t=parseInt(n[s]);if(e>t)return 1;if(e<t)return-1}return 0}let ur=new class{init(e){this.core=e}};class lr{constructor(e){this.type=Pi,this.uploadProgress=0;var t=this._getFileInfo(e);this.content={downloadFlag:2,fileUrl:Ki.addAuthToUrl(e.url||e.fileUrl)||"",uuid:e.uuid,fileName:t.name||"",fileSize:t.size||0}}static parseServerPushElement(e){var e=e["MsgContent"],{Download_Flag:e,Url:t,FileName:s,FileSize:r,UUID:n}=e;return new lr({downloadFlag:e,url:t,fileName:s,fileSize:r,uuid:n})}updatePercent(e){this.uploadProgress=Math.min(e,1)}updateFileUrl(e){this.content.fileUrl=e}validateBeforeSend(){var e=""!==this.content.fileUrl&&""!==this.content.fileName&&0<this.content.fileSize;return{isValid:e,error:e?null:{message:"content can not be empty"}}}transformToServerFormat(e){var{isMergerMessage:e=!1}=e||{},{uuid:e,downloadFlag:t,fileUrl:s,fileName:r,fileSize:n}=e?this.payload:this.content;return{MsgType:this.type,MsgContent:{Download_Flag:t,Url:Ki.removeAuthToUrl(s),FileName:r,FileSize:n,UUID:e}}}_getFileInfo(e){var t=ur.core["utils"]["IN_UNI_NATIVE_APP"];return e.fileName&&e.fileSize?{size:e.fileSize,name:e.fileName}:(e=e["file"],e?(t&&this._processNativeAppFile(e),{size:e.size,name:e.name}):{size:0,name:""})}_processNativeAppFile(e){var t;e.path&&e.path.includes(".")&&(t=e.path.slice(e.path.lastIndexOf(".")+1).toLowerCase(),e.type=t,e.name||(e.name=Oi(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 dr=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(Pi,lr),e.subscribeInnerEvent(s.DESTROY,this._dispose,this)}createFileMessage(s){var r,n,o,e,t;try{let e=this._core.ssoLog.createSSOLogData({method:"createFileMessage"}),t=(console.log(ki+" 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==(o=null==(n=this._core)?void 0:n.message.messageFactory)?void 0:o.createMessage(Object.assign(Object.assign({},s),{from:i})),l={uuid:Ki.generateUUID(t),file:t},c=new lr(l);return a.setElement(c),this._messageOptionsMap.set(a.clientSequence,s),console.log(ki+" 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(ki+" createFileMessage error:",s),s}}upload(s){return h(this,void 0,void 0,function*(){console.log(ki+" 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=Ki.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:nr});if(e.size>ar)throw new t({message:"File size exceeds limit: "+Ni(ar)});if(0===e.size)throw new t({code:or})}_performFileUpload(r,n,t){return h(this,void 0,void 0,function*(){var e=n["to"],e={uploadFileType:Vi,file:t,to:e,message:n,onProgress:e=>{var t,s;r.updatePercent(e),null!=(s=null==(t=this._messageOptionsMap.get(n.clientSequence))?void 0:t.onProgress)&&s.call(t,e)}},e=(yield Wi.uploadToCOS(e))["response"];return e})}_processFile(t){var{IN_BROWSER:e,IN_RN_APP:s,IN_WX_MINI_APP:r,IN_QQ_MINI_APP:n,IN_UNI_NATIVE_APP:o}=null==(e=this._core)?void 0:e.utils,i=(null==(i=this._core)?void 0:i.helper)["ChatError"];if(e||o){let e=Ki.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||n){let e=t["tempFiles"];return Object.assign(Object.assign({},e[0]),{url:e[0].path})}return s?Object.assign(Object.assign({},t),{url:t.uri}):t}_checkVersion(){var{MINI_APP_NAMESPACE:t,IN_MINI_APP:e,IN_WX_MINI_APP:s,IN_QQ_MINI_APP:r,IN_UNI_NATIVE_APP:n}=null==(e=this._core)?void 0:e.utils,o=(null==(o=this._core)?void 0:o.helper)["ChatError"];if(e){if(!(s||r||n))throw new o({message:"Unsupported mini app environment"});let e=t.getSystemInfoSync().SDKVersion;if(s&&cr(e,ir)<0)throw new o({message:`WXChooseMessageFile requires SDK version ${ir} or higher`});if(r&&cr(e,rr)<0)throw new o({message:`QQChooseMessageFile requires SDK version ${rr} or higher`})}}_reset(){this._messageOptionsMap.clear()}_dispose(){this._reset();var{notificationCenter:e,InnerEvent:t}=this._core;e.unSubscribeInnerEvent(t.DESTROY,this._dispose,this)}};let pr=2108,hr=2352,gr=["mp4","quicktime","mov"],_r=104857600;class mr{constructor(e){this.type=Ui,this.uploadProgress=0;var t="number"==typeof(null==e?void 0:e.videoSecond)?null==e?void 0:e.videoSecond:0;this.content={remoteVideoUrl:Ki.addAuthToUrl(e.remoteVideoUrl||e.videoUrl||""),videoFormat:e.videoFormat,videoSecond:parseInt(null==t?void 0:t.toString(),10),videoSize:e.videoSize,videoUrl:Ki.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:Ki.addAuthToUrl(e.thumbUrl),snapshotUrl:Ki.addAuthToUrl(e.thumbUrl)}}static parseServerPushElement(e){var e=e["MsgContent"],{VideoUrl:e,VideoFormat:t,VideoSecond:s,VideoSize:r,VideoDownloadFlag:n,VideoUUID:o,ThumbUUID:i,ThumbFormat:a,ThumbWidth:l,SnapshotWidth:c,ThumbHeight:u,SnapshotHeight:d,ThumbSize:h,SnapshotSize:p,ThumbDownloadFlag:g,ThumbUrl:_,SnapshotUrl:m}=e;return new mr({videoUrl:e,videoFormat:t,videoSecond:s,videoSize:r,videoDownloadFlag:n,videoUUID:o,thumbUUID:i,thumbFormat:a,thumbWidth:l,snapshotWidth:c,thumbHeight:u,snapshotHeight:d,thumbSize:h,snapshotSize:p,thumbDownloadFlag:g,thumbUrl:_,snapshotUrl:m})}updatePercent(e){this.uploadProgress=Math.min(e,1)}updateVideoUrl(e){e&&(this.content.remoteVideoUrl=e)}updateSnapshotInfo(e){var{snapshotUrl:e,snapshotWidth:t,snapshotHeight:s}=e;Ki.isEmpty(e)||(this.content.thumbUrl=this.content.snapshotUrl=e),Ki.isEmpty(t)||(this.content.thumbWidth=this.content.snapshotWidth=Number(t)),Ki.isEmpty(s)||(this.content.thumbHeight=this.content.snapshotHeight=Number(s))}validateBeforeSend(){var e=""!==this.content.remoteVideoUrl;return{isValid:e,error:e?null:{message:"content can not be empty"}}}transformToServerFormat(e){var{isMergerMessage:e=!1}=e||{},{remoteVideoUrl:e,videoFormat:t,videoSecond:s,videoSize:r,videoDownloadFlag:n,videoUUID:o,thumbUUID:i,thumbFormat:a,thumbWidth:l,snapshotWidth:c,thumbHeight:u,snapshotHeight:d,thumbSize:h,snapshotSize:p,thumbDownloadFlag:g,thumbUrl:_,snapshotUrl:m}=e?this.payload:this.content;return{MsgType:this.type,MsgContent:{VideoUrl:Ki.removeAuthToUrl(e),VideoFormat:t,VideoSecond:s,VideoSize:r,VideoDownloadFlag:n,VideoUUID:o,ThumbUUID:i,ThumbFormat:a,ThumbWidth:l,SnapshotWidth:c,ThumbHeight:u,SnapshotHeight:d,ThumbSize:h,SnapshotSize:p,ThumbDownloadFlag:g,ThumbUrl:Ki.removeAuthToUrl(_),SnapshotUrl:Ki.removeAuthToUrl(m)}}}}var vr=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(Ui,mr),e.subscribeInnerEvent(s.DESTROY,this._dispose,this)}createVideoMessage(s){var r,n,o,e,t;try{let e=this._core.ssoLog.createSSOLogData({method:"createVideoMessage"}),t=(console.log(ki+" 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==(o=null==(n=this._core)?void 0:n.message.messageFactory)?void 0:o.createMessage(Object.assign(Object.assign({},s),{from:i})),l={videoFormat:t.videoFile.type,videoSecond:Li(t.videoFile.second,0),videoSize:t.videoFile.size,remoteVideoUrl:"",videoUrl:t.videoFile.url,videoUUID:Ki.generateUUID(t.videoFile),thumbUUID:Ki.generateUUID(t.videoFile,"jpg"),thumbWidth:t.width||200,thumbHeight:t.height||200,thumbUrl:t.thumbUrl,thumbSize:t.thumbSize,thumbFormat:"jpg"},c=new mr(l);return a.setElement(c),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(ki+" createVideoMessage error:",s),s}}upload(r){return h(this,void 0,void 0,function*(){console.log(ki+" 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=Ki.addAuthToUrl(t);return e.updateVideoUrl(t),Ki.isEmpty(s)||e.updateSnapshotInfo(s),r})}_validateBeforeUploadVideo(e){var t=(null==(t=this._core)?void 0:t.helper)["ChatError"];if(e.videoFile.size>_r)throw new t({message:"File size exceeds limit: "+Ni(_r)});if(0===e.videoFile.size)throw new t({code:pr});if(-1===gr.indexOf(e.videoFile.type))throw new t({code:hr})}_performVideoUpload(r,n,s){return h(this,void 0,void 0,function*(){var e=n["to"],e={uploadFileType:qi,file:s,to:e,message:n,onProgress:e=>{var t,s;r.updatePercent(e),null!=(s=null==(t=this._messageOptionsMap.get(n.clientSequence))?void 0:t.onProgress)&&s.call(t,e)}},{response:e,uploadOptions:t}=yield Wi.uploadToCOS(e);return{snapshotInfo:yield this._getSnapshotInfoByUrl(t.requestSnapshotUrl),location:e.location}})}_processVideo(e){var r,n;try{var o=(null==(r=this._core)?void 0:r.helper)["ChatError"],{IN_MINI_APP:i,IN_BROWSER:a}=null==(n=this._core)?void 0:n.utils;let t=e.payload["file"],s={};if(i&&(s=this._processMiniVideoFile(t),t.name=s.name,t.url=s.url,t.type=s.type),a){let e=Ki.extractFileFromInput(t);if(!e)throw new o({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(ki+" _processFile error:",e),e}}_processMiniVideoFile(e){var{IN_ALIPAY_MINI_APP:t,IN_UNI_NATIVE_APP:s}=null==(t=this._core)?void 0:t.utils,r=(null==(r=this._core)?void 0:r.helper)["ChatError"];if(t)throw new r({message:"VideoUnsupportedInAlipay"});if(Ti(e))throw new r({message:"FileUnsupportedInMiniApp"});let n=(e=Array.isArray(e.tempFiles)?e.tempFiles[0]:e).tempFilePath.slice(e.tempFilePath.lastIndexOf(".")+1).toLowerCase();return s&&(n=e.fileType||n),{url:e.tempFilePath,name:e.tempFilePath.slice(e.tempFilePath.lastIndexOf("/")+1),size:e.size||1,second:e.duration||0,type:n}}_processWebVideoFile(e){var{name:t,size:s=1,duration:r=0,type:n}=e,n=n.split("/")[1];return{url:window.URL.createObjectURL(e),name:t,size:s,second:r,type:n}}_getSnapshotInfoByUrl(n){return h(this,void 0,void 0,function*(){try{console.log(ki+" _getSnapshotInfoByUrl url:",n);var e,t,s,r=((yield function(o,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:o}),n=r.head.seq+e;return yield s.sendPacket(r,{requestId:n})}catch(e){throw console.warn("getSnapshotInfo error:",e),e}})}({version:1,platform:Ki.getPlatform(),cover_name:Ri(Oi(99999)),snapshot_url:n},this._core))||{})["download_url"];return(console.log(ki+" _getSnapshotInfoByUrl OK snapshotUrl:",r),Ki.isEmpty(r))?{}:(e=Ki.addAuthToUrl(r),{width:t=0,height:s=0}=yield Ki.probeImageWidthHeight(e),{snapshotUrl:e,snapshotWidth:t,snapshotHeight:s})}catch(e){throw console.error(ki+" _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 fr{constructor(e){this.uploadProgress=0,this.type=wi,this.content={downloadFlag:2,second:e.second,size:e.size,url:Ki.addAuthToUrl(e.url),remoteAudioUrl:Ki.addAuthToUrl(e.url||""),uuid:e.uuid}}static parseServerPushElement(e){var e=e["MsgContent"],{Url:e,Download_Flag:t,Second:s,Size:r,UUID:n}=e;return new fr({url:e,downloadFlag:t,second:s,size:r,uuid:n})}updatePercent(e){this.uploadProgress=Math.min(e,1)}updateAudioUrl(e){this.content.remoteAudioUrl=e}validateBeforeSend(){var e=""!==this.content.remoteAudioUrl;return{isValid:e,error:e?null:{message:"content can not be empty"}}}transformToServerFormat(e){var{isMergerMessage:e=!1}=e||{},{uuid:e,downloadFlag:t,remoteAudioUrl:s,size:r,second:n}=e?this.payload:this.content;return{MsgType:this.type,MsgContent:{Url:Ki.removeAuthToUrl(s),Download_Flag:t,Second:n,Size:r,UUID:e}}}}let Ir=2108,Sr=2300,Er=20971520;var Cr=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(wi,fr),e.subscribeInnerEvent(s.DESTROY,this._dispose,this)}createAudioMessage(t){var s,r,e,n;try{let e=this._core.ssoLog.createSSOLogData({method:"createAudioMessage"});console.log(ki+" createAudioMessage options:",t);t.payload["file"];var o=this._processAudioFile(t.payload.file),i=(t.payload.file=o,null==(n=this._core.store.get("login"))?void 0:n.userId),a=null==(r=null==(s=this._core)?void 0:s.message.messageFactory)?void 0:r.createMessage(Object.assign(Object.assign({},t),{from:i})),l={second:Math.floor((o.duration||o.second)/1e3),size:o.fileSize||o.size||1,url:o.tempFilePath||o.uri||o.url,uuid:Ki.generateUUID(o)},c=new fr(l);return a.setElement(c),this._messageOptionsMap.set(a.clientSequence,t),e.end(),a}catch(t){throw null!=(n=(e=this._core.ssoLog.getSSOLogData("createAudioMessage")).setError)&&n.call(e,t).end(),console.error(ki+" createAudioMessage error:",t),t}}upload(s){return h(this,void 0,void 0,function*(){console.log(ki+" 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=Ki.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>Er)throw new t({message:"File size exceeds limit: "+Ni(Er)});if(0===e.size)throw new t({code:Ir})}_performAudioUpload(r,n,t){return h(this,void 0,void 0,function*(){var e=n["to"],e={uploadFileType:xi,file:t,to:e,message:n,onProgress:e=>{var t,s;r.updatePercent(e),null!=(s=null==(t=this._messageOptionsMap.get(n.clientSequence))?void 0:t.onProgress)&&s.call(t,e)}},e=(yield Wi.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 Mr={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}},yr={createImageMessage:Mr,createAudioMessage:Mr,createVideoMessage:Mr,createFileMessage:Mr},Ar={createImageMessage:!0,createAudioMessage:!0,createVideoMessage:!0,createFileMessage:!0},Tr={[Gi]:sr,[Pi]:dr,[Ui]:vr,[wi]:Cr};var kr,Fr,$r,Or=new class{constructor(){this.name="RichMediaMessage"}install(e){let{OuterConstant:{MSG_AUDIO:t,MSG_FILE:s,MSG_IMAGE:r,MSG_VIDEO:n}}=(this._core=e)["constants"];ur.init(e),sr.init(e),dr.init(e),vr.init(e),Cr.init(e),Wi.init(e),Ki.init(e),e.helper.registerApi({apiName:"sendMessage",context:this,matcher:e=>[t,s,r,n].includes(e[0].type)}),e.helper.registerValidateConfig({auth:Ar,params:yr})}sendMessage(r,n){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,n)}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=Tr[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=Bi.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 Dr=new class{init(e){this.core=e}},Rr=e=>{var{OuterConstant:t,utils:{isString:s}}=Dr["core"];return s(e)&&e.slice(0,3)===t.CONV_C2C},Lr=e=>{var{OuterConstant:t,utils:{isString:s}}=Dr["core"];return s(e)&&e.slice(0,5)===t.CONV_GROUP},Nr=e=>{var{OuterConstant:t,utils:{isString:s}}=Dr["core"];return s(e)&&e===t.CONV_SYSTEM},br=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:Dr.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(e){var t=Dr.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 wr(e){var t=Dr.core["OuterConstant"];let s;return"@TLS#ERROR"===(s=e.startsWith(t.CONV_C2C)?e.replace(t.CONV_C2C,""):s)||"@TLS#NOT_FOUND"===s}function Pr(e,t){var s=Dr.core["helper"],s=new s.ChatError({functionName:e,code:(null==t?void 0:t.errorCode)||(null==t?void 0:t.code),message:(null==t?void 0:t.errorInfo)||(null==t?void 0:t.message)});throw console.error(e+" fail:",s),s}class Ur{constructor(e){this.conversationID=e.conversationID||"",this.unreadCount=e.unreadCount||0,this.type=e.type||"",this.lastMessage=br(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}}=Dr["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}}=Dr["core"],{nextUnreadCount:e,isFromGetConversations:r,isUnreadC2CMessage:n}=e;s(e)||(this.subType!==t.GRP_AVCHATROOM?r&&this.type===t.CONV_GROUP||n&&this.type===t.CONV_C2C?this.unreadCount=e:this.unreadCount+=e:this.unreadCount=0)}updateLastMessage(e){this.lastMessage=br(e)}reduceUnreadCount(){return 1<=this.unreadCount&&(--this.unreadCount,!0)}isLastMessageRevoked(e){var t=Dr["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}}=Dr["core"];t(e,this.groupAtInfoList)}clearGroupAtInfoList(){this.groupAtInfoList.length=0}getProfileCompleted(){return this._isInfoCompleted}setProfileCompleted(){this._isInfoCompleted=!0}}!function(e){e[e.OFF=0]="OFF",e[e.ON=1]="ON"}(kr=kr||{}),function(e){e[e.ONLY_CONVERSATIONID=1]="ONLY_CONVERSATIONID"}(Fr=Fr||{}),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"}($r=$r||{});let qr=0,xr=1;var Vr=new class{constructor(){this._name="ConversationDataHandler",this._totalUnreadCount=0,this._groupAtTipsList=[]}init(e){var{helper:e,notificationCenter:t,appStore:{conversationStore:s},constants:{WORKFLOW_NAME:r,WORKFLOW_STEP:n},InnerEvent:{SYNC_CONVERSATION_LIST:o,MESSAGE_PUSH:i,NEW_MESSAGE:a,MESSAGE_DELETED:l,MESSAGE_REVOKED:c,MESSAGE_MODIFIED:u,CONVERSATION_UPDATED:d,LOGOUT:h,DESTROY:p}}=this._core=e,s=(this._conversationStore=s,e.registerWorkflowStep(r.SYNC_SERVER_INFO_AFTER_LOGIN,n.CONVERSATION_UPDATE_AFTER_UNREAD_SYNC_FINISHED,this._handleUnreadSyncFinished,this),e.registerWorkflowStep(r.SYNC_SERVER_INFO_AFTER_LOGIN,n.CONVERSATION_UPDATE_AFTER_GROUP_LIST_SYNC_FINISHED,this._handleGroupListSyncFinished,this),e.registerWorkflowStep(r.RECEIVE_C2C_NEW_MESSAGE,n.CREATE_OR_UPDATE_CONVERSATION_BY_RECEIVE_NEW_MESSAGE,this._handleNewMessage,this),e.registerWorkflowStep(r.RECEIVE_C2C_NEW_MESSAGE,n.CONVERSATION_UPDATE_AFTER_UNREAD_SYNC_FINISHED,this._handleUnreadSyncFinished,this),e.registerWorkflowStep(r.RECEIVE_GROUP_NEW_MESSAGE,n.CREATE_OR_UPDATE_CONVERSATION_BY_RECEIVE_NEW_MESSAGE,this._handleNewMessage,this),e.registerWorkflowStep(r.SYNC_SERVER_INFO_AFTER_RE_ONLINE,n.CONVERSATION_UPDATE_AFTER_UNREAD_SYNC_FINISHED,this._handleUnreadSyncFinished,this),t)["InnerEventSubType"]["GROUP_AT_TIPS"];t.subscribeInnerEvent(o,this._handleConversationSynced,this),t.subscribeInnerEvent(a,this._handleNewMessage,this),t.subscribeInnerEvent(i,s,this._handleNewGroupAtTips,this),t.subscribeInnerEvent(l,this._handleMessageDeleted,this),t.subscribeInnerEvent(c,this._handleMessageRevoked,this),t.subscribeInnerEvent(u,this._handleMessageModified,this),t.subscribeInnerEvent(d,this._handleConversationUpdated,this),t.subscribeInnerEvent(h,this._reset,this),t.subscribeInnerEvent(p,this._dispose,this),console.log(this._name+".init")}_handleConversationSynced(e){this.updateLocalConversationList({conversationUpdateFieldList:e.conversationUpdateFieldList||[],isFromGetConversations:!0,updateUnreadCount:!0}),this.emitConversationListUpdate()}_handleUnreadSyncFinished(e){let{WORKFLOW_STEP:t}=this._core["constants"],{conversationUpdateFieldList:s=[],groupTipList:r=[],isUnreadC2CMessage:n}=e.result[t.UNREAD_MESSAGE_SYNC]||{},o=!1;s.forEach(e=>{var{conversationID:e,unreadCount:t}=e,e=this.getLocalConversation(e);e&&e.unreadCount!==t&&(e.updateUnreadCount({nextUnreadCount:t,isUnreadC2CMessage:n}),o=!0)}),o&&this.emitConversationListUpdate(),this._handleGroupAtTipsSynced(r)}_handleGroupAtTipsSynced(t){var s;for(let e=0;e<t.length;e++)if(12===t[e].Event){if(null!=(s=t[e].GroupTips[0].MsgBody)&&s.TopicId)continue;this._handleNewGroupAtTips(t[e])}}_handleGroupListSyncFinished(e){let r,{WORKFLOW_STEP:t}=this._core.constants,n=e.result[t.GROUP_LIST_SYNC]||[],{CONV_GROUP:o}=this._core.OuterConstant,i=!1;for(let s=0;s<n.length;s++){let e=n[s],t=""+o+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:n=!0}=e.result||{};0===e.length||({isTopic:t}=this._core["common"],t(e[0].conversationID))||(this.updateLocalConversationList({conversationUpdateFieldList:e,isInstantMessage:s,isUnreadC2CMessage:r,isFromGetConversations:!1,updateUnreadCount:n}),0<e.filter(e=>this._isConversationNeedShow(e.conversationID)).length&&this.emitConversationListUpdate())}_handleNewGroupAtTips(e){var{GroupTips:e=[]}=e;e.forEach(e=>{var{GroupAtTips:t,MsgBody:s,MsgRandom:r,ClientSeq:n}=e;let o={};t?o=this._convertGroupAtTipsKey(t):s?o=Object.assign({},this._convertGroupAtTipsKey(s)):e.groupAtType&&(o=Object.assign({},e)),o.__random=r,o.__sequence=n,this._groupAtTipsList.push(o)}),console.log(this._name+"._handleNewGroupAtTips groupAtTipsList: "+JSON.stringify(this._groupAtTipsList)),this._updateGroupAtInfoList()}_convertGroupAtTipsKey(e){var{From_Account:e,GroupId:t,MsgSeq:s,GroupAtType:r}=e;return{from:e,groupID:t,sequence:s,groupAtType:r}}_updateGroupAtInfoList(){if(0!==this._groupAtTipsList.length){let{common:e,OuterConstant:r}=this._core,n=e.getCurrentUserID(),o=!1;this._groupAtTipsList.forEach(t=>{var{groupID:s,from:e}=t;if(e!==n){let e=this.getLocalConversation(""+r.CONV_GROUP+s);e&&(e.updateGroupAtInfoList(t),o=!0)}}),o&&this.emitConversationListUpdate(),this._groupAtTipsList.length=0}}_handleMessageDeleted(t){console.log(this._name+"._handleMessageDeleted, conversationID:",t);var s,{message:{messageDataHandler:r},OuterConstant:n}=this._core,o=(null==r?void 0:r.getLocalMessageList(t))||[];let i={};for(let e=(o.length||0)-1;0<=e;e--)if(!o[e].isDeleted){i=o[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(n.CONV_C2C)&&this.updateUnreadCount(t),e&&(this.emitConversationListUpdate(),console.log(this._name+`._handleMessageDeleted. update conversationID:${t} with lastMessage:`,r.lastMessage))}}_handleMessageRevoked(e){let{messageList:r=[],updateUnreadCount:n=!0}=e;if(console.log(this._name+"._handleMessageRevoked messageList:"+r.length),0!==r.length){let t=null,s=!1;r.forEach(e=>{(t=this.getLocalConversation(e.conversationID))&&(n&&t.reduceUnreadCount()&&(s=!0),t.isLastMessageRevoked({sequence:e.sequence,time:e.time}))&&(t.setLastMessageRevoked(!0),t.setLastMessageRevoker(e.revoker),s=!0)}),s&&this.emitConversationListUpdate()}}_handleMessageModified(e){console.log(this._name+"._handleMessageModified",JSON.stringify(e));var{conversationID:t,messageList:s}=e,e=this.getLocalConversation(t),{utils:{isEmpty:r},common:{getMessagePreviewText:n}}=this._core;if(!r(e)){r=e["lastMessage"];if(r){let e=(null==s?void 0:s[0])||{};r.lastTime===e.time&&r.lastSequence===e.sequence&&r.version!==e.version&&(r.type=e.type,r.payload=e.payload,r.messageForShow=n(e.type,e.payload),r.cloudCustomData=e.cloudCustomData,r.version=e.version,this.emitConversationListUpdate(),console.log(this._name+` conversationID:${t} lastMessage updated`))}}}_handleConversationUpdated(e){this.emitConversationListUpdate(null==e?void 0:e.needSort)}updateLocalConversationList(e){var t=e["isFromGetConversations"],e=this._getTmpConversationListMapping(e)["newConversationList"];this._sortConversationList(),t||this._updateNewConversationProfile(e),console.log(this._name+".updateLocalConversationList newConversationList: "+e.length)}_getTmpConversationListMapping(e){let o=this._core["OuterConstant"],{conversationUpdateFieldList:i,isFromGetConversations:a,isInstantMessage:l,isUnreadC2CMessage:c=!1,updateUnreadCount:u}=e,d=[],t=null==i?void 0:i.length;for(let n=0;n<t;n++){let t=new Ur(i[n]),{conversationID:s,type:r}=t;if(!wr(s))if(this.hasLocalConversation(s)){let e=this.getLocalConversation(s);a?(this.setLocalConversation(s,t),r===o.CONV_C2C?t.unreadCount=(null==e?void 0:e.unreadCount)||0:r===o.CONV_GROUP&&(t.groupProfile=JSON.parse(JSON.stringify(null==e?void 0:e.groupProfile)))):(this._mergeConversationInfo({conversationID:s,tmpConversation:t,lastMessage:i[n].lastMessage,isFromGetConversations:a,isInstantMessage:l}),this._patchLastMessage({conversationID:s,lastMessage:i[n].lastMessage,isInstantMessage:l}),!0===u&&null!=e&&e.updateUnreadCount({nextUnreadCount:t.unreadCount,isFromGetConversations:a,isUnreadC2CMessage:c}))}else d.push(t),this.setLocalConversation(s,t)}return{newConversationList:d}}_mergeConversationInfo(e){var{conversationID:e,tmpConversation:t,lastMessage:s,isFromGetConversations:r,isInstantMessage:n}=e,e=this.getLocalConversation(e),o=["unreadCount","allowType","adminForbidType","payload"],{utils:{isUndefined:r,isEmpty:i},common:{deepMerge:a}}=(!1===n&&o.push("lastMessage"),r&&o.push("isPinned"),this._core);r(n)&&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,o,[null,void 0,"",0,NaN])}_patchLastMessage(e){let n=this._core["OuterConstant"],{conversationID:t,lastMessage:o,isInstantMessage:i}=e,a=this.getLocalConversation(t);if(a&&o){let{payload:e,nameCard:t,nick:s,cloudCustomData:r=""}=o;i&&(e&&(a.lastMessage.payload=e),a.type===n.CONV_GROUP)&&(a.lastMessage.nameCard=t,a.lastMessage.nick=s),a.lastMessage.cloudCustomData!==r&&(a.lastMessage.cloudCustomData=r)}}_sortConversationList(){let{isEmpty:t}=this._core["utils"],e=[...this._conversationStore.getConversationMap()],s=[],r=[],n=[],o=[];e.forEach(e=>{(!0===e[1].isPinned?t(e[1].lastMessage.lastTime)?r:s:t(e[1].lastMessage.lastTime)?o:n).push(e)});var i=s.sort((e,t)=>t[1].lastMessage.lastTime-e[1].lastMessage.lastTime).concat(r).concat(n.sort((e,t)=>t[1].lastMessage.lastTime-e[1].lastMessage.lastTime)).concat(o);this._updateConversationMapFromList(i)}_updateNewConversationProfile(e){if(0!==e.length){let s=[],r=[],{CONV_GROUP:n,CONV_C2C:o}=this._core["OuterConstant"];e.forEach(e=>{var{conversationID:t,type:e}=e;if(e===o){let e=t.replace(o,"");s.push(e)}else if(e===n){let e=t.replace(n,"");r.push(e)}}),0<s.length&&this._updateC2CConversation(s),0<r.length&&this._updateGroupConversation(r)}}_updateC2CConversation(e){let t,{OuterConstant:{CONV_C2C:n},appStore:{userStore:o},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(""+n+s);if(r){let e=(null==(s=o.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,n=!1;e.forEach(e=>{var t=r.getGroup(e),e=this.getLocalConversation(""+s+e);t&&e&&(e.groupProfile=t,n=!0)}),n&&this.emitConversationListUpdate()}_isConversationNeedShow(e){var{OuterConstant:{CONV_GROUP:t,GRP_ROOM:s,GRP_LIVE:r},utils:{isUndefined:n}}=this._core,e=this.getLocalConversation(e);return!(!n(e)&&(n=e.type===t&&(null==(n=e.groupProfile)?void 0:n.type)===s,t=e.type===t&&(null==(s=e.groupProfile)?void 0:s.type)===r,n||t))}updateUnreadCount(e,t=!0){let s,r,n=!1;var o,i=this.getLocalConversation(e),a=null==(r=null==(s=this._core)?void 0:s.message.messageDataHandler)?void 0:r.getLocalMessageList(e);return i&&(o=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:${o} newUnreadCount:`+a),o!==a)&&(i.unreadCount=a,(n=!0)===t)&&this.emitConversationListUpdate(),n}emitConversationListUpdate(e=!1){e&&this._sortConversationList();var e=this._core["OuterEvent"]["CONVERSATION_LIST_UPDATED"],t=this.getLocalConversationList();this._emitEvent({name:e,data:t}),this._emitTotalUnreadCountUpdate()}_emitTotalUnreadCountUpdate(){var e,t=this.getTotalUnreadMessageCount();this._totalUnreadCount!==t&&(console.log(`${this._name}._emitTotalUnreadCountUpdate from ${this._totalUnreadCount} to `+t),this._totalUnreadCount=t,this._emitEvent({name:null==(e=this._core)?void 0:e.OuterEvent.TOTAL_UNREAD_MESSAGE_COUNT_UPDATED,data:t}))}_emitEvent(e){var t;null!=(t=this._core)&&t.notificationCenter.emitOuterEvent(e.name,e)}getTotalUnreadMessageCount(){let{OuterConstant:t,utils:{isEmpty:s}}=this._core,e=this.getLocalConversationList(),r=0;return e.forEach(e=>{e.type===t.CONV_SYSTEM||!s(e.messageRemindType)&&e.messageRemindType!==t.MSG_REMIND_ACPT_AND_NOTE||(r+=e.unreadCount)}),r}getLocalConversationList(){return[...this._conversationStore.getConversationMap().values()].filter(e=>this._isConversationNeedShow(e.conversationID))}hasLocalConversation(e){return this._conversationStore.getConversationMap().has(e)}getLocalConversation(e){return this._conversationStore.getConversationMap().get(e)}setLocalConversation(e,t){return this._conversationStore.getConversationMap().set(e,t)}deleteLocalConversation(e){this._conversationStore.getConversationMap().delete(e)}_updateConversationMapFromList(e){this._clearConversationMap();for(var[t,s]of e)this.setLocalConversation(t,s)}_clearConversationMap(){this._conversationStore.getConversationMap().clear()}patchMessageRemindType(e,t){let s=!1;e.forEach(e=>{e=this.getLocalConversation(e);(null==e?void 0:e.messageRemindType)!==t&&(e.messageRemindType=t,s=!0)}),console.log(this._name+`.patchMessageRemindType conversationIDList:${e} messageRemindType:${t} hasUpdated:`+s),s&&this.emitConversationListUpdate()}markMessageAsRead(e){let{messageDataHandler:t}=this._core["message"],{conversationID:s,lastReadTime:n=0,lastReadSequence:o=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=n&&e.time>n,s=o&&e.sequence>o;if(!t&&!s){if("in"===e.flow&&e.isRead)break;e.setIsRead(!0)}}}}appendToPinnedConversation(e){var t=[...this._conversationStore.getConversationMap().entries()],s=t.findIndex(e=>!1===e[1].isPinned);t.splice(s,0,[e.conversationID,e]),this._updateConversationMapFromList(t),this.emitConversationListUpdate()}_reset(){this._clearConversationMap(),this._totalUnreadCount=0,this._groupAtTipsList=[]}_dispose(){var{notificationCenter:e,InnerEvent:{NEW_MESSAGE:t,MESSAGE_DELETED:s,MESSAGE_REVOKED:r,MESSAGE_MODIFIED:n,CONVERSATION_UPDATED:o,LOGOUT:i,DESTROY:a,SYNC_CONVERSATION_LIST:l}}=this._core,{GROUP_AT_TIPS:c}=e["InnerEventSubType"];e.unSubscribeInnerEvent(t,this._handleNewMessage,this),e.unSubscribeInnerEvent(t,c,this._handleNewGroupAtTips,this),e.unSubscribeInnerEvent(s,this._handleMessageDeleted,this),e.unSubscribeInnerEvent(r,this._handleMessageRevoked,this),e.unSubscribeInnerEvent(n,this._handleMessageModified,this),e.unSubscribeInnerEvent(o,this._handleConversationUpdated,this),e.unSubscribeInnerEvent(l,this._handleConversationSynced,this),e.unSubscribeInnerEvent(i,this._reset,this),e.unSubscribeInnerEvent(a,this._dispose,this)}},Br=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:this._core.conversation.syncConversationHandler.isSyncCompleted()}}})}_getConversationList(i){let{isUndefined:e,isArray:t,isPlainObject:s}=this._core["utils"];if(e(i))return Vr.getLocalConversationList();if(t(i))return 0===i.length?[]:Vr.getLocalConversationList().filter(e=>i.includes(e.conversationID));if(s(i)){let{type:t,markType:s,groupName:r,hasUnreadCount:n,hasGroupAtInfo:o}=i;return Vr.getLocalConversationList().filter(e=>this._filterType(e,t)&&this._filterMarkType(e,s)&&this._filterGroupName(e,r)&&this._filterUnreadCount(e,n)&&this._filterGroupAtInfo(e,o))}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}},jr=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=Gr(t);Vr.patchMessageRemindType([e],t)})}catch(e){console.error(this._name+".get fail:",e)}})}},Kr=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;Vr.patchMessageRemindType([e],t)})}catch(e){console.error(this._name+".get fail:",e)}})}},Wr=new class{constructor(){this._name="GetConversationProfile"}init(e){e=(this._core=e).helper;e.registerApi({apiName:"getConversationProfile",context:this})}getConversationProfile(c){return h(this,void 0,void 0,function*(){let{OuterConstant:{CONV_C2C:s,CONV_GROUP:r,GRP_AVCHATROOM:n},appStore:{groupStore:o},utils:{isEmpty:e}}=this._core,i={code:0,data:{}},a=Vr.getLocalConversation(c);if(Nr(c))i.data.conversation=a;else{let t=!1;var l=Rr(c)?s:r;if(e(a)&&(t=!0,a=new Ur({conversationID:c,type:l})),console.log(this._name+`.getConversationProfile conversationID:${c} isNewConversation:`+t),null==(i.data.conversation=a)||!a.getProfileCompleted()){if(l===s){let e=c.replace(s,"");yield this._handleC2CConversation(a,e),t&&(yield jr.get([e]))}if(l===r){let e=c.replace(r,"");if(!o.getGroup(e))return i;yield this._handleGroupConversation(a,e),t&&a.groupProfile.type!==n&&(yield Kr.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:n}}=this._core,o=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:$r.USER_OR_GRP_NOT_FOUND});i.userProfile=null==e?void 0:e.data[0];e=null==(t=n.getFriend(a))?void 0:t.remark,s(e)||i.remark===e||(i.remark=e),i.setProfileCompleted(),n=Vr.hasLocalConversation(o);console.log(this._name+`._handleC2CConversation conversationID:${o} hasLocalConversation: `+n),n?r.updateConversation(o,i):Vr.appendToPinnedConversation(i)})}_handleGroupConversation(r,n){return h(this,void 0,void 0,function*(){var{apiMap:{getGroupProfile:e},appStore:{conversationStore:t}}=this._core,s=r["conversationID"],e=yield e({groupID:n}),e=(r.groupProfile=null==e?void 0:e.data.group,r.setProfileCompleted(),Vr.hasLocalConversation(s));console.log(this._name+`._handleGroupConversation conversationID:${s} hasLocalConversation: `+e),e?t.updateConversation(s,r):Vr.appendToPinnedConversation(r)})}},Hr=new class{init(e){e=e.helper;e.registerApi({apiName:"getTotalUnreadMessageCount",context:this})}getTotalUnreadMessageCount(){return Vr.getTotalUnreadMessageCount()}},Yr=new class{constructor(){this._serverGroupConversationLastReadSeqMap=new Map,this._name="SetMessageRead"}init(e){let{helper:t,common:{isTopic:s},notificationCenter:r,InnerEvent:{MESSAGE_PUSH:n},InnerEventSubType:{ALL_MESSAGE_READ:o}}=this._core=e;t.registerApi({apiName:"setMessageRead",context:this,matcher:e=>!s(e[0].conversationID)}),t.registerApi({apiName:"setAllMessageRead",context:this}),r.subscribeInnerEvent(n,o,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),Vr.markMessageAsRead({conversationID:e,lastReadTime:t}),Vr.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),Vr.markMessageAsRead({conversationID:e,lastReadSequence:t}),Vr.updateUnreadCount(e),this._clearGroupAtInfoList(e)})})}setMessageRead(l){return h(this,void 0,void 0,function*(){let e=this._core["OuterConstant"],t=l["conversationID"],s={code:0,data:{}},r=Vr.getLocalConversation(t);if(console.log(this._name+`.setMessageRead conversationID:${t} unreadCount:`+((null==r?void 0:r.unreadCount)||0)),r){var n=!(null!=(o=null==(n=this._core)?void 0:n.helper)&&o.isEmpty(r.groupAtInfoList));if(r.type===e.CONV_GROUP&&n&&this._deleteGroupAtTips(t),0!==r.unreadCount){var{ssoLog:o,helper:{ChatError:i}}=this._core,a=o.createSSOLogData({method:"setMessageRead"});a.setLogInfo({message:"conversationID:"+t});try{if(r.type===e.CONV_C2C){let e=this._getLocalMessageMaxTime(r);yield this._setC2CMessageRead(t,e),a.setLogInfo({moreMessage:"lastMessageTime:"+e}).end()}if(r.type===e.CONV_GROUP){let e=this._getLocalMessageMaxSequence(r);yield this._setGroupMessageRead(t,e),a.setLogInfo({moreMessage:"lastMessageSequence:"+e}).end()}}catch(e){let{errorCode:t,errorInfo:s}=e,r=new i({functionName:"setMessageRead",code:t,message:s});throw a.setError(r).end(),r}r.type===e.CONV_SYSTEM&&(r.unreadCount=0),Vr.emitConversationListUpdate()}}return s})}setAllMessageRead(){return h(this,arguments,void 0,function*(s={}){let{OuterConstant:{READ_ALL_MSG:e},ssoLog:t}=this._core,n=t.createSSOLogData({method:"setAllMessageRead"}),o=(s.scope||(s.scope=e),s)["scope"],i=this._generateSetAllMessageReadRequestData(o);if(i.allC2CMessageReadStatus===qr&&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 Dr.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})&&Vr.emitConversationListUpdate(),n.setLogInfo({message:`scope:${o} failureGroups:`+JSON.stringify(s)}).end()}return{code:0}}catch(s){let e=s["errorCode"],t=new this._core.helper.ChatError({functionName:"setAllMessageRead",code:e});throw n.setError(t).end(),t}})}_handleAllMessageRead(e){var{GroupReadInfoArray:e,C2CReadAllMsg:t}=e;this._parseGroupReadInfo(e),0<this._updateAllConversationReadStatus({allC2CMessageReadStatus:t})&&Vr.emitConversationListUpdate()}_updateAllConversationReadStatus(e){let{OuterConstant:{CONV_C2C:r,CONV_GROUP:n},appStore:t}=this._core,o=t.conversationStore.getConversationMap(),i=e["allC2CMessageReadStatus"],a=0;for(let[s,t]of o)if(1<=t.unreadCount){if(i===xr&&t.type===r){let e=this._getLocalMessageMaxTime(t);Vr.markMessageAsRead({conversationID:s,lastReadTime:e})}else if(t.type===n){let t=s.replace(n,"");if(this._serverGroupConversationLastReadSeqMap.has(t)){let e=this._serverGroupConversationLastReadSeqMap.get(t);Vr.markMessageAsRead({conversationID:s,lastReadSequence:e})}}Vr.updateUnreadCount(s,!1)&&(a+=1)}return a}_generateSetAllMessageReadRequestData(r){let{OuterConstant:{CONV_C2C:n,CONV_GROUP:o,READ_ALL_C2C_MSG:i},appStore:e}=this._core,a={allC2CMessageReadStatus:qr,groupMessageReadInfoList:[]},t=e.conversationStore.getConversationMap();for(let[,s]of t){let{type:e,unreadCount:t}=s;if(this._shouldSetAllMessageRead({scope:r,type:e,unreadCount:t}))if(e===n&&a.allC2CMessageReadStatus===qr){if(a.allC2CMessageReadStatus=xr,r===i)break}else if(e===o){let e=this._getLocalMessageMaxSequence(s),t=s.groupProfile["groupID"];a.groupMessageReadInfoList.push({GroupId:t,MsgSeq:e})}}return a}_parseGroupReadInfo(e){let{isUndefined:n}=this._core["utils"],o=[];return null!=e&&e.forEach(e=>{var{GroupId:e,MsgSeq:t,RetCode:s,LastReadMsgSeq:r}=e;n(s)?this._serverGroupConversationLastReadSeqMap.set(e,r):(this._serverGroupConversationLastReadSeqMap.set(e,t),0!==s&&o.push(e+`-${t}-`+s))}),o}_deleteGroupAtTips(i){return h(this,void 0,void 0,function*(){console.log(this._name+"._deleteGroupAtTips conversationID:"+i);let e=Vr.getLocalConversation(i);if(e){var o=(null==e?void 0:e.groupAtInfoList)||[];if(0!==o.length)try{let{common:{getCurrentUserID:t,isCommunity:e},OuterConstant:{CONV_GROUP:s,CONV_AT_ALL:r}}=this._core,n=[...o];e({groupID:i.replace(s,"")})&&0===(n=o.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:n.map(e=>({From_Account:e.from,To_Account:t(),MsgSeq:e.__sequence,MsgRandom:e.__random,GroupId:e.groupID}))},this._core),console.log(this._name+"._deleteGroupAtTips ok. count:"+o.length),this._clearGroupAtInfoList(i))}catch(e){console.error(this._name+"._deleteGroupAtTips fail:",e)}}})}_clearGroupAtInfoList(e,t=!0){var s=Vr.getLocalConversation(e);s&&(0<s.groupAtInfoList.length&&(s.clearGroupAtInfoList(),console.log(this._name+`._clearGroupAtInfoList conversationID:${e} needEmitConversationUpdate:`+t)),t)&&Vr.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),Vr.markMessageAsRead({conversationID:e,lastReadTime:t}),Vr.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),Vr.markMessageAsRead({conversationID:e,lastReadSequence:t}),Vr.updateUnreadCount(e)}catch(e){throw console.warn(this._name+"._setGroupMessageRead fail:",e),e}})}_shouldSetAllMessageRead(e){var{CONV_C2C:t,CONV_GROUP:s,READ_ALL_MSG:r,READ_ALL_C2C_MSG:n,READ_ALL_GROUP_MSG:o}=this._core["OuterConstant"],{type:e,scope:i,unreadCount:a}=e;return!(a<=0||(e!==t||![r,n].includes(i))&&(e!==s||![r,o].includes(i)))}},zr=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 n=this._core["OuterConstant"],o=!1;e.forEach(e=>{var{Type:e,To_Account:t,GroupId:s}=e;let r;1===e?r=Vr.getLocalConversation(""+n.CONV_C2C+t):2===e&&(r=Vr.getLocalConversation(""+n.CONV_GROUP+s)),r&&(console.log(`${this._name}.handleConversationPinned conversationID:${r.conversationID} localPinned:${r.isPinned} remotePinned:`+i),i&&!r.isPinned&&(r.isPinned=!0,o=!0),!i)&&r.isPinned&&(r.isPinned=!1,o=!0)}),o&&Vr.emitConversationListUpdate(!0)}}pinConversation(t){return h(this,void 0,void 0,function*(){let{OuterConstant:s,common:r,ssoLog:e,helper:{ChatError:n}}=this._core,{conversationID:o,isPinned:i}=t,a={code:0,data:{conversationID:o}},l=Vr.getLocalConversation(o);if(l&&l.isPinned===i)return a;if(Nr(o))return l&&(l.isPinned=i),Vr.emitConversationListUpdate(!0),a;var c=e.createSSOLogData({method:"pinConversation"});c.setLogInfo({message:`conversationID:${o} isPinned:`+i});try{let e=null,t=(Rr(o)?e={Type:1,To_Account:o.replace(s.CONV_C2C,"")}:Lr(o)&&(e={Type:2,GroupId:o.replace(s.CONV_GROUP,"")}),yield function(r,n){return h(this,void 0,void 0,function*(){var{fromAccount:e,operationType:t,itemList:s}=r;return n.common.buildAndSendPacket({servcmd:"recentcontact.top",data:{From_Account:e,OperationType:t,RecentContactItem:s}})})}({fromAccount:r.getCurrentUserID(),operationType:!0===i?1:2,itemList:[e]},this._core));if(c.end(),console.log(this._name+`.pinConversation ok, conversationID:${o} isPinned:${i}.`),t){if(l)l.isPinned!==i&&(l.isPinned=i);else{let e=new Ur({conversationID:o,type:Rr(o)?s.CONV_C2C:s.CONV_GROUP,isPinned:i});Vr.setLocalConversation(o,e)}Vr.emitConversationListUpdate(!0)}return a}catch(e){let{errorCode:t,errorInfo:s}=e,r=new n({functionName:"pinConversation",code:t,message:s});throw c.setError(r).end(),console.error(this._name+".pinConversation fail:",r),r}})}},Jr=new class{constructor(){this._name="DeleteConversation"}init(e){e=(this._core=e).helper;e.registerApi({apiName:"deleteConversation",context:this})}handleConversationDeleted(e){var{isArray:t}=this._core["utils"];if(t(e)){let r=this._core["OuterConstant"],n=[];e.forEach(e=>{var{Type:e,Peer_Account:t,GroupId:s}=e;1===e&&n.push(""+r.CONV_C2C+t),2===e&&n.push(""+r.CONV_GROUP+s)}),console.log(this._name+".handleConversationDeleted conversationIDList:"+n),this._deleteLocalConversationList(n)}}deleteConversation(t){return 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:Fr.ONLY_CONVERSATIONID})):(100<(e=Object.assign({},t)).conversationIDList.length&&(e.conversationIDList=e.conversationIDList.slice(0,100)),yield this._deleteConversation(e))})}_deleteConversation(a){return h(this,void 0,void 0,function*(){let{conversationIDList:s,clearHistoryMessage:r=!0,flag:n=0}=a,{ssoLog:e,helper:{ChatError:o}}=this._core,t=`conversationIDList:${s} clearHistoryMessage:`+r,i=e.createSSOLogData({method:"deleteConversation"});i.setLogInfo({message:t}),console.log(this._name+"._deleteConversation "+t);try{let e=yield Promise.all([this._deleteConversationFromLocal(s),this._deleteConversationFromServer(s,r)]),t=[...e[0],...e[1]];if(0===t.length)throw new this._core.helper.ChatError({code:$r.CONV_NOT_FOUND});return i.end(),console.log(this._name+"._deleteConversation ok."),{code:0,data:n===Fr.ONLY_CONVERSATIONID?{conversationID:t[0]}:{conversationIDList:t}}}catch(e){let{errorCode:t,errorInfo:s}=e,r=new o({functionName:"deleteConversation",code:t,message:s});throw i.setError(r).end(),console.error(this._name+"._deleteConversation fail:",r),r}})}_deleteConversationFromLocal(e){let s=this._core["OuterConstant"];return e.filter(e=>{var t;return!!Vr.hasLocalConversation(e)&&((t=null==(t=Vr.getLocalConversation(e))?void 0:t.type)===s.CONV_GROUP&&!this._hasLocalGroup(e)||t===s.CONV_SYSTEM)&&(this._deleteLocalConversation(e),!0)})}_deleteConversationFromServer(t,o){return h(this,void 0,void 0,function*(){let{OuterConstant:r,common:e}=this._core,n={fromAccount:e.getCurrentUserID(),conversationList:[],clearHistoryMessage:o?1:0};if(t.forEach(e=>{var t,s;Vr.hasLocalConversation(e)&&(t=(null==(t=Vr.getLocalConversation(e))?void 0:t.type)||"",s=e.replace(t,""),t===r.CONV_C2C?n.conversationList.push({To_Account:s,Type:1}):t===r.CONV_GROUP&&this._hasLocalGroup(e)&&n.conversationList.push({ToGroupid:s,Type:2}))}),0!==n.conversationList.length){var s=yield function(r,n){return h(this,void 0,void 0,function*(){var{fromAccount:e,conversationList:t,clearHistoryMessage:s}=r;return n.common.buildAndSendPacket({servcmd:"recentcontact.batch_delete",data:{From_Account:e,ContactItem:t,ClearRamble:s}})})}(n,this._core);if(s){let{ResultItem:e=[]}=s,t=[];return 0<e.length&&e.forEach(e=>{0===e.ResultCode&&(e=1===e.type?""+r.CONV_C2C+e.To_Account:""+r.CONV_GROUP+e.ToGroupid,t.push(e))}),this._deleteLocalConversationList(t),t}}return[]})}_deleteLocalConversationList(e){let t=!1;e.forEach(e=>{Vr.hasLocalConversation(e)&&(this._deleteLocalConversation(e,!1),t=!0)}),console.log(this._name+"._deleteLocalConversationList isUpdate:"+t),t&&Vr.emitConversationListUpdate()}_deleteLocalConversation(e,t=!0){var s=Vr.hasLocalConversation(e);console.log(this._name+`._deleteLocalConversation conversationID:${e} has:`+s),s&&(Vr.deleteLocalConversation(e),this._deleteConversationLocalMessage(e),t)&&Vr.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)}},Qr=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),Vr.hasLocalConversation(e))return null!=(e=Vr.getLocalConversation(e))&&e.setDraftText(t),Vr.emitConversationListUpdate(),{code:0,data:{conversation:e}};throw new this._core.helper.ChatError({code:$r.CONV_NOT_FOUND})})}},Xr=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}=Dr.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=[],n=(s.forEach(e=>{var{Peer_Account:e,ErrorCode:t}=e,t=(r.push({userID:e,code:t}),a.indexOf(e));-1<t&&a.splice(t,1)}),[]),o=[],i=this._core["OuterConstant"];return a.forEach(e=>{o.push(""+i.CONV_C2C+e),n.push({userID:e})}),Vr.patchMessageRemindType(o,l),{code:0,data:{successUserIDList:n,failureUserIDList:r}}})}},Zr=new class{constructor(){this._name="SetGroupMessageRemindType"}init(e){this._core=e}set(r,n){return h(this,void 0,void 0,function*(){let{common:{getCurrentUserID:e,isTopic:t},OuterConstant:s}=this._core;if(yield function(r,n){return h(this,void 0,void 0,function*(){var{groupID:e,userID:t,receiveMessageOption:s}=r;return n.common.buildAndSendPacket({servcmd:"group_open_http_svc.modify_group_member_info",data:{GroupId:e,Member_Account:t,MsgFlag:s}})})}({groupID:r,userID:e(),receiveMessageOption:n},this._core),!t(r)){let e=""+s.CONV_GROUP+r;Vr.patchMessageRemindType([e],n)}return{code:0,data:{groupID:r,messageRemindType:n}}})}},ea=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:o}=this._core;e.forEach(e=>{var n=e["MuteNotificationsSync"];if(!t(n)){let{To_Account:e,MuteNotifications:t}=n,s=e.map(e=>""+o.CONV_C2C+e),r=Gr(t);console.log(this._name+`.handleC2CMessageRemindTypeSync conversationIDList:${s} messageRemindType:`+r),Vr.patchMessageRemindType(s,r)}})}setMessageRemindType(i){return h(this,void 0,void 0,function*(){let s="setMessageRemindType",{groupID:e,userIDList:t,messageRemindType:r}=i,{helper:n,utils:{isUndefined:o}}=this._core;try{if(!o(e))return console.log(`${this._name}.${s} groupID:${e} messageRemindType:`+r),yield Zr.set(e,r);if(o(t))throw new n.ChatError({functionName:s,message:"userIDList or groupID is required"});return console.log(this._name+`.${s} userIDList:${t} messageRemindType:`+r),yield Xr.set(t,r)}catch(e){let t=new n.ChatError({functionName:s,code:null==e?void 0:e.errorCode,message:null==e?void 0:e.errorInfo});throw console.error(this._name+`.${s} fail:`,t),t}})}},ta=new class{init(e){console.log("ConversationAction.init"),this._core=e,Br.init(e),Wr.init(e),Hr.init(e),Yr.init(e),zr.init(e),Jr.init(e),Qr.init(e),ea.init(e);var{notificationCenter:e,InnerEvent:{MESSAGE_PUSH:t,DESTROY:s}}=this._core,{CONV_MODIFIED:r,C2C_MESSAGE_READ_SYNC:n,GROUP_MESSAGE_READ_SYNC:o,C2C_REMIND_TYPE_SYNC:i}=e["InnerEventSubType"];e.subscribeInnerEvent(t,r,this._onConversationModified,this),e.subscribeInnerEvent(t,n,this._onC2CMessageReadSync,this),e.subscribeInnerEvent(t,i,this._onC2CMessageRemindTypeSync,this),e.subscribeInnerEvent(t,o,this._onGroupMessageReadSync,this),e.subscribeInnerEvent(s,this._dispose,this)}_onConversationModified(e){let{ConvModifyPushType:s}=this._core["constants"],{RecentContactMod:t=[]}=e;t.forEach(t=>{var e=t["PushType"];if(e===s.CONV_DELETED){let e=t.RecentContactDeleteItem["RecentContactList"];Jr.handleConversationDeleted(e)}if(e===s.CONV_PINED){let e=t.RecentContactTopItem["RecentContactList"];zr.handleConversationPinned(e,!0)}if(e===s.CONV_UNPINED){let e=t.RecentContactTopItem["RecentContactList"];zr.handleConversationPinned(e,!1)}})}_onC2CMessageReadSync(e){var{C2cNotifyMsgArray:e=[]}=e;Yr.handleC2CMessageReadSync(e)}_onC2CMessageRemindTypeSync(e){var{C2cNotifyMsgArray:e=[]}=e;ea.handleC2CMessageRemindTypeSync(e)}_onGroupMessageReadSync(e){var{GroupTips:e=[]}=e;Yr.handleGroupMessageReadSync(e)}_dispose(){var{notificationCenter:e,InnerEvent:{MESSAGE_PUSH:t,DESTROY:s}}=this._core,{CONV_MODIFIED:r,C2C_MESSAGE_READ_SYNC:n,GROUP_MESSAGE_READ_SYNC:o,C2C_REMIND_TYPE_SYNC:i}=e["InnerEventSubType"];e.unSubscribeInnerEvent(t,r,this._onConversationModified,this),e.unSubscribeInnerEvent(t,n,this._onC2CMessageReadSync,this),e.unSubscribeInnerEvent(t,i,this._onC2CMessageRemindTypeSync,this),e.unSubscribeInnerEvent(t,o,this._onGroupMessageReadSync,this),e.unSubscribeInnerEvent(s,this._dispose,this)}},sa=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:n=0}=this._calcStartAndEndTime(i),o=yield function(o){return h(this,void 0,void 0,function*(){var e=Dr.core["common"],{startTime:t,endTime:s,isRepeated:r,messageRemindType:n}=o;return e.buildAndSendPacket({servcmd:"im_msg_db_logic.ws_set_do_not_disturb",data:{StartTime:t,EndTime:s,IsRepeated:r,Level:n}})})}({messageRemindType:this._getType(t),startTime:r,endTime:n,isRepeated:s?kr.ON:kr.OFF});return{code:0,data:{errorCode:o.ErrorCode,errorInfo:o.ErrorInfo}}}catch(e){Pr("setAllReceiveMessageOpt",e)}})}_calcStartAndEndTime(e){var{startHour:e=0,startMinute:t=0,startSecond:s=0,duration:r=0,isRepeated:n=!0}=e,o=new Date,o=new Date(o.getFullYear(),o.getMonth(),o.getDate(),e,t,s),e=Math.round(o.getTime()/1e3);let i=n&&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]}},oa=new class{init(e){var{helper:e,notificationCenter:t,InnerEvent:s}=this._core=e;e.registerApi({apiName:"getAllReceiveMessageOpt",context:this}),t.subscribeInnerEvent(s.MESSAGE_PUSH,t.InnerEventSubType.ALL_RECEIVE_MESSAGE_OPTION,this.onAllReceiveMsgOptionNotify,this)}onAllReceiveMsgOptionNotify(e){var e=this._handleResult(e),{notificationCenter:t,OuterEvent:{ALL_RECEIVE_MESSAGE_OPT_UPDATED:s}}=this._core;t.emitOuterEvent(s,{name:s,data:e})}getAllReceiveMessageOpt(){return h(this,void 0,void 0,function*(){try{var e=yield function(){return h(this,void 0,void 0,function*(){var e=Dr.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){Pr("getAllReceiveMessageOpt",e)}})}_handleResult(e){var t=this._core["OuterConstant"],{MSG_REMIND_ACPT_AND_NOTE:t,MSG_REMIND_DISCARD:s,MSG_REMIND_ACPT_NOT_NOTE:r}=t,{Level:e,StartTime:n,EndTime:o,IsRepeated:i}=e;return{messageRemindType:{0:t,1:s,2:r}[e]||t,startTime:n,endTime:o,isRepeated:i===kr.ON}}},na=new class{init(e){console.log("ReceiveMessageOptions.init"),this._core=e,Xr.init(e),Zr.init(e),jr.init(e),Kr.init(e),sa.init(e),oa.init(e)}};let ia=e=>!Rr(e)&&!Lr(e)&&!Nr(e),ra={getConversationProfile:[{key:"conversationID",required:!0,rules:["string"],allowEmpty:!1,customValidator:e=>!ia(e)||"conversationID is invalid."}],setMessageRead:{conversationID:{required:!0,rules:["string"],allowEmpty:!1,customValidator:e=>!ia(e)||"conversationID is invalid."}},pinConversation:{conversationID:{required:!0,rules:["string"],allowEmpty:!1,customValidator:e=>!ia(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}}=Dr["core"];if(!r(e)&&!s(e))return"options is String or Object.";if(r(e)&&ia(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(ia(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=>!(!Rr(e)&&!Lr(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}}},aa={getConversationList:!0,getConversationProfile:!0,getTotalUnreadCount:!0,setMessageRead:!0,pinConversation:!0,deleteConversation:!0,setConversationDraft:!0,setMessageRemindType:!0,getAllReceiveMessageOpt:!0,setAllReceiveMessageOpt:!0};var ca=new class{constructor(){this.name="Conversation"}install(e){Dr.init(e),ta.init(e),na.init(e),Vr.init(e),e.helper.registerValidateConfig({auth:aa,params:ra})}};let ua=new class{init(e){this.core=e}},la="AVChatRoom",da="AV_HISTORY_MSG",pa="GRP_COUNTER",ha="Set",ga="Increase",_a="Decrease",ma=0,va=1,fa=2,Ia=["Type","Name","Introduction","Notification","FaceUrl","Owner_Account","CreateTime","InfoSeq","LastInfoTime","LastMsgTime","MemberNum","MaxMemberNum","ApplyJoinOption","NextMsgSeq","ShutUpAllMember","InviteJoinOption","LastRecallTime"],Sa=["Type","Name","Introduction","Notification","FaceUrl","CreateTime","Owner_Account","LastInfoTime","LastMsgTime","NextMsgSeq","MemberNum","MaxMemberNum","ApplyJoinOption","InviteJoinOption"],Ea=["Role","JoinTime","MsgFlag","MsgSeq"],Ca=["Role","JoinTime","MsgSeq","MsgFlag","NameCard"],Ma=0,ya=1,Aa="notStart",Ta="resolved",Oa="rejected",Da=10018,Ra=11e3,La=2,Na=["Owner","Admin","Member"],ba=["Role","JoinTime","NameCard","ShutUpUntil","OnlineStatus"],Ga=0,wa=1,Pa=2,Ua=4,ka=1,Fa=2,$a=3,qa=4,xa=5,Va=1,Ba=0,ja=4,Ka=6,Wa=400,Ha=300,Ya={from:!0,groupID:!0,groupName:!0,to:!0},za={from:!0,groupID:!0,groupName:!0,to:!0,type:!0},Ja=2,Qa=4,Xa=5,Za=7,ec=8,tc=15,sc=20,oc=21,nc=2600,ic=2602,rc=2603,ac=2620,cc=2621,uc=2623,lc=2660,dc=2661,pc=2681,hc=2683,gc=2684,_c=2685,mc=2687,vc=3122,fc=10018,Ic=e=>e===ua.core.OuterConstant.GRP_PUBLIC,Sc=e=>e===ua.core.OuterConstant.GRP_AVCHATROOM,Ec=(r,e)=>{var t=ua.core.utils["isArray"];if(!t(r)||!t(e))return!1;let n=!1;return e.forEach(({key:t,value:e})=>{var s=r.find(e=>e.key===t);s?s.value!==e&&(s.value=e,n=!0):(r.push({key:t,value:e}),n=!0)}),n},Cc=s=>{var r=[];if(s)for(let e=0,t=s.length;e<t;e++){var{Key:n,Value:o}=s[e];r.push({key:n,value:o})}return r},Mc=s=>{var r=[];for(let e=0,t=s.length;e<t;e++){var{key:n,value:o}=s[e];r.push({Key:n,Value:o})}return r};function yc(e,t){var s=ua.core["helper"];if(!s.checkBusinessCapabilityBits(t))throw new s.ChatError({functionName:e,code:vc,replacement1:e})}function Ac(e,t){var s=ua.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 Tc=["groupID","name","avatar","type","introduction","notification","ownerID","selfInfo","createTime","infoSequence","lastInfoTime","lastMessage","nextMessageSeq","memberCount","maxMemberCount","memberList","joinOption","groupCustomField","muteAllMembers","isSupportTopic","inviteOption","_lastRevokedTime","_groupAtInfoList"];class Oc{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}=ua.core["utils"];for(t in e)Tc.indexOf(t)<0||("selfInfo"!==t?"isSupportTopic"!==t?"muteAllMembers"===t&&s(e[t])?this.muteAllMembers="On"===e[t]:this[t]=e[t]:this.isSupportTopic=1===e[t]:this.updateSelfInfo(e[t]))}updateGroup(e){let{utils:{isArray:t,isUndefined:s,isNumber:r,isString:n},common:{deepMerge:o}}=ua.core;e.appid=void 0,e.grossTopicNextMsgSeq=void 0,e.selfInfo&&(e.selfInfo.grossTopicReadSeq=void 0);e=JSON.parse(JSON.stringify(e));e.lastMsgTime&&(this.lastMessage.lastTime=e.lastMsgTime),n(e.muteAllMembers)&&(e.muteAllMembers="On"===e.muteAllMembers),e.groupCustomField&&Ec(this.groupCustomField,e.groupCustomField),s(e.isSupportTopic)||(this.isSupportTopic=r(e.isSupportTopic)?1===e.isSupportTopic:e.isSupportTopic),o(this,e,["members","errorCode","lastMsgTime","groupCustomField","isSupportTopic"]),t(e.members)&&0<e.members.length&&e.members.forEach(e=>{e.userID===this.selfInfo.userID&&o(this.selfInfo,e,["sequence"])})}updateSelfInfo(e){var{nameCard:e,joinTime:t,role:s,messageRemindType:r,readedSequence:n,excludedUnreadSequenceList:o}=e,i=ua.core["common"]["deepMerge"];i(this.selfInfo,{nameCard:e,joinTime:t,role:s,messageRemindType:r,readedSequence:n,excludedUnreadSequenceList:o},[],["",null,void 0,0,NaN])}setSelfNameCard(e){this.selfInfo.nameCard=e}}var Dc=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 Oc(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 Rc(i,a){return h(this,void 0,void 0,function*(){var{type:e,limit:t,offset:s,supportTopic:r=0,memberAccount:n,responseFilter:o}=i;return a.common.buildAndSendPacket({servcmd:"group_open_http_svc.get_joined_group_list",data:{Type:e,Limit:t,Offset:s,Member_Account:n,ResponseFilter:o,SupportTopic:r,NeedAppDefineData:1}})})}let Lc=function(e){return{code:0,data:e||{}}};var Nc=new class{constructor(){this._name="GetGroupList",this._pagingStatus=Aa,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}),Dc.updateLocalGroup(e),Dc.getLocalGroupList()}return console.log(this._name+".getGroupList pagingStatus:"+this._pagingStatus),this._pagingStatus===Oa||this._pagingStatus===Aa?this._syncGroupList().then(()=>{var e=Dc.getLocalGroupList();return Lc({groupList:e,isSyncCompleted:this._isSyncCompleted()})}).catch(e=>{throw console.error(this._name+".getGroupList fail:",e),e}):(e=Dc.getLocalGroupList(),console.log(this._name+".getGroupList return group count:"+e.length),Lc({groupList:e,isSyncCompleted:this._isSyncCompleted()}))})}_syncGroupList(){return h(this,void 0,void 0,function*(){this._pagingStatus===Aa&&Dc.clearLocalGroup();var e=this.PAGING_GRP_COUNT_LIMIT,t=[];try{yield this._pagingGetGroupList({limit:e,offset:0,groupList:t}),this._pagingStatus=Ta,this._groupListTreeShaking(t),Dc.updateLocalGroup(t);var s=Dc.getLocalGroupList();return console.log(this._name+"._syncGroupList ok, count:"+s.length),Dc.emitGroupListUpdate(),s}catch(e){throw this._pagingStatus=Oa,console.error(this._name+"._syncGroupList fail:",e),e}})}_pagingGetGroupList(e){return h(this,void 0,void 0,function*(){var{isCommunityRelay:n=!1,groupList:o}=e;let i,{limit:a,offset:l}=e;var c=[...Ia];n&&(i=this._core.OuterConstant.GRP_COMMUNITY,c.push("AtInfoList"));try{let e=yield Rc({type:i,limit:a,offset:l,memberAccount:this._core.store.get("login").userId,responseFilter:{GroupBaseInfoFilter:c,SelfInfoFilter:[...Ea]}},this._core),{GroupIdList:t=[],TotalCount:s=0}=e||{},r=this._convertGroupKey(t);o.push(...r);var u=l+a,d=!(u<s),h=`offset:${l} limit:${a} total:${s} isCompleted:${d} current:${o.length} isCommunityRelay:`+n;return console.log(this._name+"._pagingGetGroupList ok. "+h),n?d?o:(l=u,this._pagingGetGroupList({isCommunityRelay:!0,limit:a,offset:l,groupList:o})):d?(console.log(this._name+"._pagingGetGroupList start to get community list"),l=0,this._pagingGetGroupList({isCommunityRelay:!0,limit:a,offset:l,groupList:o})):(l=u,this._pagingGetGroupList({limit:a,offset:l,groupList:o}))}catch(e){if(e.ErrorCode===Da)return console.warn(this._name+"._pagingGetGroupList response size exceeds the limit, request count:"+a),this._pagingGetGroupList({isCommunityRelay:n,limit:50,offset:l,groupList:o});if(n)return e.code===Ra&&console.log(this._name+"._pagingGetGroupList ok. community unavailable"),o;throw e}})}_pagingGetJoinedCommunityList(e){return h(this,void 0,void 0,function*(){var{common:{getCurrentUserID:n},OuterConstant:o}=this._core,i=e["groupList"];let{limit:a,offset:l}=e;try{let e=yield Rc({limit:a,offset:l,type:o.GRP_COMMUNITY,memberAccount:n(),supportTopic:1,responseFilter:{GroupBaseInfoFilter:[...Ia],SelfInfoFilter:[...Ea]}},this._core),{GroupIdList:t=[],TotalCount:s=0}=e||{},r=this._convertGroupKey(t);i.push(...r);var c=l+a,u=!(c<s),d=`offset:${l} limit:${a} total:${s} isCompleted:${u} current:`+i.length;return console.log(this._name+"._pagingGetJoinedCommunityList ok. "+d),u?i:(l=c,this._pagingGetJoinedCommunityList({limit:a,offset:l,groupList:i}))}catch(e){if(e.code===fc)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([...Dc.getLocalGroupList()]);for(let e=0,t=s.length;e<t;e++)r.delete(s[e].groupID);var n=[...r.keys()];for(let e=0,t=n.length;e<t;e++)Dc.deleteLocalGroup(n[e])}_isSyncCompleted(){return this._pagingStatus===Ta}_convertGroupKey(s){var r=[];for(let e=0,t=s.length;e<t;e++){var{AppDefinedData:n,ApplyJoinOption:o,CreateTime:i,FaceUrl:a,GroupId:l,Introduction:c,InviteJoinOption:u,LastInfoTime:d,LastMsgTime:h,MemberNum:p,MaxMemberNum:g,MuteAllMember:_,Name:m,NextMsgSeq:v,Notification:f,Owner_Account:I,Type:S,LastRecallTime:E,SelfInfo:C,AtInfoList:M=[],SupportTopic:y}=s[e],n=Cc(n),C=this._convertSelfInfo(C),M=this._convertAtInfoList(l,M);r.push({groupCustomField:n,joinOption:o,createTime:i,avatar:a,groupID:l,introduction:c,inviteOption:u,lastInfoTime:d,lastMsgTime:h,memberCount:p,maxMemberCount:g,muteAllMembers:_,name:m,nextMessageSeq:v,notification:f,ownerID:I,type:S,selfInfo:C,_lastRevokedTime:E,_groupAtInfoList:M,isSupportTopic:y})}return r}_convertSelfInfo(e){var{JoinTime:e,MsgFlag:t,MsgSeq:s,NoUnreadSeqList:r,Role:n}=e;return{joinTime:e,messageRemindType:t,readedSequence:s,excludedUnreadSequenceList:r,role:n}}_convertAtInfoList(r,e){if(0===e.length)return[];let n=[];return e.forEach(e=>{var{AtFlagList:e,AtMsgSeq:t,From_Account:s}=e;n.push({groupID:r,groupAtType:e,sequence:t,from:s})}),n}},bc=new class{constructor(){this._name="CreateGroup"}init(e){e=(this._core=e).helper;e.registerApi({apiName:"createGroup",context:this})}createGroup(l){return h(this,void 0,void 0,function*(){var o;this._preCheckParams(l);let{ssoLog:e,helper:{ChatError:r}}=this._core,i=e.createSSOLogData({method:"createGroup"});try{let{utils:{isEmpty:e},common:{getCurrentUserID:t}}=this._core,s=yield function(p,g){return h(this,void 0,void 0,function*(){var{name:e,type:t,groupID:s,introduction:r,notification:n,avatar:o,maxMemberNum:i,joinOption:a,inviteOption:l,memberList:c,groupCustomField:u,isSupportTopic:d}=p;let h;e={Name:e,Type:t,GroupId:s,Introduction:r,Notification:n,FaceUrl:o,MaxMemberCount:i,ApplyJoinOption:a,InviteJoinOption:l,MemberList:h=c?c.map(e=>{var{userID:e,memberCustomField:t}=e;return{Member_Account:e,AppMemberDefinedData:t?Mc(t):void 0}}):h,AppDefinedData:u,SupportTopic:d,webPushFlag:1};return g.common.buildAndSendPacket({servcmd:"group_open_http_svc.create_group",data:e})})}(Object.assign(Object.assign({},l),{ownerID:t()}),this._core),{GroupId:r,OverJoinedGroupLimit_Account:n=[]}=s||{};i.setLogInfo({message:"groupID:"+r}).end(),console.log(`${this._name}.createGroup ok, type:${l.type} groupID:${r} overLimitUserIDList:`+n),e(l.memberList)||e(n)||(l.memberList=null==(o=l.memberList)?void 0:o.filter(e=>n.includes(e.userID))),Dc.updateLocalGroup([Object.assign(Object.assign({},l),{groupID:r})]);var a=Dc.getLocalGroup(r);return this._notNeedSendCustomMessage(l)||(this._sendCustomMessage(r,l.type),Dc.emitGroupListUpdate()),Lc({group:a})}catch(o){let{errorCode:e,errorInfo:t}=o,s=new r({functionName:"createGroup",code:e,message:t});throw i.setLogInfo({message:"groupID:"+(l.groupID||"")}).setError(s).end(),console.error(this._name+".createGroup fail:",s),s}})}_preCheckParams(e){var{type:t,groupID:s}=e,{utils:{isEmpty:r,isUndefined:n},common:{isCommunity:o}}=this._core,r=!r(s);if(!(()=>{var{GRP_PUBLIC:e,GRP_WORK:t,GRP_MEETING:s,GRP_AVCHATROOM:r,GRP_COMMUNITY:n}=ua.core.OuterConstant;return[e,t,s,r,n]})().includes(t))throw new this._core.helper.ChatError({code:nc});if(!o({type:t})){if(r&&o({groupID:s}))throw new this._core.helper.ChatError({code:ic});n(e.isSupportTopic)||(e.isSupportTopic=void 0)}if(this._canIUseMemberList(t)||n(e.memberList)||(e.memberList=void 0),this._canIUseJoinOption(t)||n(e.joinOption)||(e.joinOption=void 0),o({type:t})){if(r&&!o({groupID:s}))throw new this._core.helper.ChatError({code:ic});e.isSupportTopic=this._canIUseTopic(e)?1:0}}_canIUseMemberList(e){return!Sc(e)}_canIUseJoinOption(e){return Ic(e)||this._core.common.isCommunity({type:e})}_canIUseTopic(e){e=e.isSupportTopic;return!0===e}_notNeedSendCustomMessage(e){var{type:e,isSupportTopic:t}=e,{GRP_AVCHATROOM:s,GRP_COMMUNITY:r}=this._core["OuterConstant"];return e===s||e===r&&1===t}_sendCustomMessage(e,t){var s=this._core["OuterConstant"];let r="Create Group",n=Ma;t===s.GRP_COMMUNITY&&(r="Create Community",n=ya);var t={to:e,conversationType:"GROUP",payload:{data:JSON.stringify({businessID:"group_create",content:r,cmd:n,opUser:this._core.store.get("login").userId,version:4})}},e=null==(s=null==(e=null==(s=this._core)?void 0:s.message)?void 0:e.messageFactory)?void 0:s.createCustomMessage(t);null!=(s=null==(t=null==(s=this._core)?void 0:s.message)?void 0:t.messageSender)&&s.sendMessage(e,{})}},Gc=new class{constructor(){this._name="AttributesDataHandler",this._groupAttributesCache=new Map,this._groupAttributesCacheValuesCopy={}}init(e){var{helper:e,constants:t}=this._core=e;e.registerWorkflowStep(t.WORKFLOW_NAME.SYNC_SERVER_INFO_AFTER_RE_ONLINE,t.WORKFLOW_STEP.GROUP_ATTRIBUTE_CACHE_CLEAR,this.clearLocalMainSequence,this)}clearLocalMainSequence(){this._groupAttributesCache.forEach(e=>{e.localMainSequence=0})}isGroupAttributesUpdated(e){var e=e["elements"]["newGroupProfile"],{isEmpty:t,isUndefined:s}=this._core["utils"];return!s(e)&&!t(e.groupAttributeOption)}handleGroupAttributesUpdated(e){var{groupID:e,groupAttributeOption:t}=e,{serverMainSequence:t,groupAttributeList:s=[],operation:r}=t,n=(console.log(this._name+`.handleGroupAttributesUpdated groupID:${e} operation:`+r),this._core)["utils"]["isUndefined"];n(r)||(this.refreshGroupAttributesCache({groupID:e,serverMainSequence:t,groupAttributeList:s,operation:r}),this.emitGroupAttributesUpdated(e))}initGroupAttributesCache(e){var{groupID:e,avChatRoomKey:t}=e;this._groupAttributesCache.set(e,{lastUpdateTime:0,localMainSequence:0,serverMainSequence:0,avChatRoomKey:t,values:new Map}),console.log(this._name+`.initGroupAttributesCache. groupID:${e} avChatRoomKey:`+t)}hasGroupAttributesCache(e){return this._groupAttributesCache.has(e)}getGroupAttributesCache(e){return this.hasGroupAttributesCache(e)||this.initGroupAttributesCache({groupID:e}),this._groupAttributesCache.get(e)}deleteGroupAttributesCache(e){this.hasGroupAttributesCache(e)&&this._groupAttributesCache.delete(e)}refreshGroupAttributesCache(e){var{groupID:s,serverMainSequence:r,groupAttributeList:n,operation:o}=e;if(this.hasGroupAttributesCache(s)){let e=this.getGroupAttributesCache(s),t=e["localMainSequence"];o!==xa&&r-t!=1||(e.serverMainSequence=r,e.localMainSequence=r,e.lastUpdateTime=Date.now(),this._updateGroupAttributesCacheValues({groupAttributes:e,groupAttributeList:n,operation:o})),1<r-t&&(e.serverMainSequence=r),this._groupAttributesCache.set(s,e),console.log(this._name+`.refreshGroupAttributesCache. operation:${o} localMainSequence:${t} serverMainSequence:`+r)}}_updateGroupAttributesCacheValues(e){let{groupAttributes:r,groupAttributeList:t=[],operation:s}=e;s!==$a?s!==qa?(s===ka&&r.values.clear(),t.forEach(e=>{var{key:e,value:t,sequence:s}=e;r.values.set(e,{value:t,sequence:s})})):t.forEach(e=>{r.values.delete(e.key)}):r.values.clear()}getGroupAttributesCacheValues(e){let s,{groupID:r,keyList:n=[]}=e,o={};if(this.hasGroupAttributesCache(r)){let t=this.getGroupAttributesCache(r)["values"];if(0===n.length)for(let e of t.keys())o[e]=(null==(s=t.get(e))?void 0:s.value)||"";else n.forEach(e=>{t.has(e)&&(o[e]=(null==(e=t.get(e))?void 0:e.value)||"")})}return o}saveGroupAttributesCacheValuesCopy(e){this._groupAttributesCacheValuesCopy=this.getGroupAttributesCacheValues({groupID:e})}emitGroupAttributesUpdated(e){var t,s=this.getGroupAttributesCacheValues({groupID:e}),{updatedKeyList:r,deletedKeyList:n}=this._computeValuesChangedData(s);console.log(`${this._name}.emitGroupAttributesUpdated update count:${r.length}, delete count:`+n.length),0===r.length&&0===n.length||this._emitEvent({name:null==(t=this._core)?void 0:t.OuterEvent.GROUP_ATTRIBUTES_UPDATED,data:{groupID:e,groupAttributes:s,updatedKeyList:r,deletedKeyList:n}})}_computeValuesChangedData(t){let{isUndefined:s}=this._core["utils"],r=[],n=[];return Object.keys(t).forEach(e=>{t[e]!==this._groupAttributesCacheValuesCopy[e]&&r.push(e)}),Object.keys(this._groupAttributesCacheValuesCopy).forEach(e=>{s(t[e])&&n.push(e)}),this._groupAttributesCacheValuesCopy={},{updatedKeyList:r,deletedKeyList:n}}_emitEvent(e){var t;null!=(t=this._core)&&t.notificationCenter.emitOuterEvent(e.name,e)}convertKeyValueMapToList(t){let s=[];return Object.keys(t).forEach(e=>{s.push({key:e,value:t[e]})}),s}reset(){this._groupAttributesCache.clear(),this._groupAttributesCacheValuesCopy={}}},wc=new class{constructor(){this._name="DismissGroup"}init(e,t){e=(this._core=e).helper;e.registerApi({apiName:"dismissGroup",context:this,matcher:()=>!t.getInstalledSubPlugins().includes(la)})}dismissGroup(t){return h(this,void 0,void 0,function*(){console.log(this._name+".dismissGroup groupID:"+t);let{ssoLog:e,helper:{ChatError:n}}=this._core,o=e.createSSOLogData({method:"dismissGroup"});o.setLogInfo({message:"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),o.end(),console.log(this._name+".dismissGroup ok.");let e=Dc.getLocalGroup(t)["type"];return Dc.deleteLocalGroup(t),Dc.emitGroupListUpdate(),Gc.deleteGroupAttributesCache(t),Lc({groupID:t,type:e})}catch(e){let{errorCode:t,errorInfo:s}=e,r=new n({functionName:"dismissGroup",code:t,message:s});throw o.setError(r).end(),console.error(this._name+".dismissGroup fail:",r),r}})}},Pc=new class{constructor(){this._name="GetGroupProfile"}init(e){e=(this._core=e).helper;e.registerApi({apiName:"getGroupProfile",context:this})}getGroupProfile(s){return h(this,void 0,void 0,function*(){let{groupID:n,groupCustomFieldFilter:e}=s,o={groupIDList:[n],responseFilter:{GroupBaseInfoFilter:[...Ia],AppDefinedDataFilter_Group:e,MemberInfoFilter:[...Ca]}},{ssoLog:t,helper:{ChatError:i}}=this._core,a=t.createSSOLogData({method:"getGroupProfile"});a.setLogInfo({message:"groupID:"+n});try{let e=yield this.getGroupProfileAdvance(o),{successGroupList:t,failureGroupList:s}=e;if(0<s.length)throw s[0];let r;return(r=!Dc.hasLocalGroup(n)&&Sc(t[0].type)?new Oc(t[0]):(Dc.updateLocalGroup(t),Dc.getLocalGroup(n))).isSupportTopic||Dc.updateConversationGroupProfile(n),a.end(),console.log(this._name+".getGroupProfile ok."),Lc({group:r})}catch(e){let{code:t,message:s}=e,r=new i({functionName:"getGroupProfile",code:t,message:s});throw a.setError(r).end(),console.error(this._name+".getGroupProfile fail:",r),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})),n=(50<s.length&&(s.length=50),50<r.length&&(r.length=50),yield Promise.all([this._getGroupProfileAdvance(Object.assign(Object.assign({},a),{groupIDList:s})),this._getGroupProfileAdvance(Object.assign(Object.assign({},a),{groupIDList:r,isCommunityProfile:!0}))])),o=[],i=[];return n.forEach(e=>{o.push(...e.successGroupList),i.push(...e.failureGroupList)}),{successGroupList:o,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"],n=s.filter(e=>r(e.errorCode)||0===e.errorCode),o=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:n,failureGroupList:o}}catch(e){if(t)return{successGroupList:[],failureGroupList:[]};throw e}})}_convertGroupProfileKey(s){var r=[];for(let e=0,t=s.length;e<t;e++){var{AppDefinedData:n,ApplyJoinOption:o,CreateTime:i,FaceUrl:a,GroupId:l,InfoSeq:c,Introduction:u,InviteJoinOption:d,LastInfoTime:h,LastMsgTime:p,MaxMemberNum:g,MemberNum:_,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],n=Cc(n),y=this._convertMembers(y);r.push({groupCustomField:n,joinOption:o,createTime:i,avatar:a,groupID:l,infoSequence:c,introduction:u,inviteOption:d,lastInfoTime:h,lastMsgTime:p,maxMemberCount:g,memberCount:_,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:n,JoinTime:o,Member_Account:i,MsgFlag:a,MsgSeq:l,NameCard:c,Role:u}=s[e],n=Cc(n);r.push({memberCustomField:n,joinTime:o,userID:i,messageRemindType:a,sequence:l,nameCard:c,role:u})}return r}},Uc=new class{constructor(){this._groupCountersMap=new Map}init(e){this._core=e}getLocalGroupCounters(e){return this._hasLocalGroupCounters(e)||this.initGroupCountersCache({groupID:e}),this._groupCountersMap.get(e)}updateLocalGroupCounters(e){var{groupID:r,counterList:n=[],groupCounterSeq:o}=e;if(this._hasLocalGroupCounters(r)){let{counters:s,avChatRoomKey:e,groupCounterSeq:t}=this.getLocalGroupCounters(r);0<o&&o<t||(n.forEach(e=>{var{Key:e,Value:t=0}=e;s.set(e,t)}),this._groupCountersMap.set(r,{lastUpdateTime:Date.now(),groupCounterSeq:o,counters:s,avChatRoomKey:e}))}}initGroupCountersCache(e){var{groupID:e,avChatRoomKey:t}=e;this._groupCountersMap.set(e,{lastUpdateTime:0,groupCounterSeq:0,counters:new Map,avChatRoomKey:t})}getLocalCounters(e,s){let r={};if(this._hasLocalGroupCounters(e)){let t=this.getLocalGroupCounters(e)["counters"];if(0<s.length)s.forEach(e=>{t.has(e)&&(r[e]=t.get(e))});else for(let e of t.keys())r[e]=t.get(e)}return r}deleteLocalGroupCounters(e){var{groupID:s,counterList:r=[],groupCounterSeq:n}=e;if(this._hasLocalGroupCounters(s)){let{counters:t,avChatRoomKey:e}=this.getLocalGroupCounters(s);r.forEach(e=>{t.delete(e.key)}),this._groupCountersMap.set(s,{lastUpdateTime:Date.now(),groupCounterSeq:n,counters:t,avChatRoomKey:e})}}setGroupCounters(t,n){if(this._hasLocalGroupCounters(t)){let e=this.getLocalGroupCounters(t),s=e["counters"],r=!1;Object.entries(n).forEach(([e,t])=>{s.has(e)&&s.get(e)!==t&&(s.set(e,t),r=!0)}),r&&this._groupCountersMap.set(t,Object.assign(Object.assign({},e),{lastUpdateTime:Date.now(),counters:s}))}}_hasLocalGroupCounters(e){return this._groupCountersMap.has(e)}reset(){this._groupCountersMap.clear()}},kc=new class{constructor(){this._name="JoinGroup"}init(e,t){e=(this._core=e).helper;e.registerApi({apiName:"joinGroup",context:this,matcher:()=>!t.getInstalledSubPlugins().includes(la)})}joinGroup(i){return h(this,void 0,void 0,function*(){let t=i["groupID"],{ssoLog:s,helper:{ChatError:n},OuterConstant:r}=this._core,o=s.createSSOLogData({method:"joinGroup"});try{if(Dc.hasLocalGroup(t))try{return yield Pc.getGroupProfile({groupID:t}),o.setLogInfo({message:`groupID:${t} joinedStatus:`+r.JOIN_STATUS_ALREADY_IN_GROUP}).end(),Lc({status:r.JOIN_STATUS_ALREADY_IN_GROUP,group:Dc.getLocalGroup(t)})}catch(s){console.warn(`${this._name}.joinGroup ${t} was unjoined, start to join!`),Dc.deleteLocalGroup(t);let e=yield this._applyJoinGroup(i);return o.setLogInfo({message:"groupID:"+t}).end(),e}let e=yield this._applyJoinGroup(i);return o.setLogInfo({message:"groupID:"+t}).end(),e}catch(e){let{errorCode:t,errorInfo:s}=e,r=new n({functionName:"joinGroup",code:t,message:s});throw o.setError(r).end(),console.error(this._name+".joinGroup fail:",r),r}})}_applyJoinGroup(d){return h(this,void 0,void 0,function*(){var{OuterConstant:e,helper:t}=this._core,s=d["groupID"],r=Object.assign({},d),t=t.checkBusinessCapabilityBits(da),r=(t&&(r.historyMessageFlag=1),yield function(r,n){return h(this,void 0,void 0,function*(){var{groupID:e,applyMessage:t,historyMessageFlag:s}=r;return n.common.buildAndSendPacket({servcmd:"group_open_http_svc.apply_join_group",data:{GroupId:e,ApplyMsg:t,HugeGroupHistoryMsgFlag:s}})})}(r,this._core)),{Type:r,JoinedStatus:n,LongPollingKey:o,StartSeq:i,HugeGroupFlag:a,AVChatRoomKey:l,RspMsgList:c=[]}=r||{},t=`groupID:${s} joinedStatus:${n} longPollingKey:${o} startSeq:${i} avChatRoomFlag:${a} canGetAVChatRoomHistoryMsg:${t}, historyMessageCount:`+c.length;console.log(this._name+"._applyJoinGroup ok, "+t);let u=new Oc({groupID:s,type:r});if(n===e.JOIN_STATUS_WAIT_APPROVAL)return Lc({status:e.JOIN_STATUS_WAIT_APPROVAL,group:u});if(n!==e.JOIN_STATUS_SUCCESS)throw new this._core.helper.ChatError({code:lc});try{u=(yield Pc.getGroupProfile({groupID:s})).data.group}catch(e){console.warn(this._name+`._applyJoinGroup getGroupProfile failed, groupID: ${s}, errorCode:`,null==e?void 0:e.code)}return this._handleJoinResult({group:u,avChatRoomFlag:a,longPollingKey:o,startSequence:i,avChatRoomKey:l,historyMessageList:c})})}_handleJoinResult(e){var{group:t,avChatRoomFlag:s,avChatRoomKey:r}=e;return 1===s?(Gc.initGroupAttributesCache({groupID:t.groupID,avChatRoomKey:r}),Uc.initGroupCountersCache({groupID:t.groupID,avChatRoomKey:r}),Lc(e)):(Dc.updateLocalGroup([t]),Dc.emitGroupListUpdate(),Lc({status:this._core.OuterConstant.JOIN_STATUS_SUCCESS,group:t}))}},Fc=new class{constructor(){this._name="QuitGroup"}init(e,t){e=(this._core=e).helper;e.registerApi({apiName:"quitGroup",context:this,matcher:()=>!t.getInstalledSubPlugins().includes(la)})}quitGroup(t){return h(this,void 0,void 0,function*(){if(!Dc.hasLocalGroup(t))throw new this._core.helper.ChatError({code:uc});let{ssoLog:e,helper:{ChatError:n}}=this._core,o=e.createSSOLogData({method:"quitGroup"});o.setLogInfo({message:"groupID:"+t});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),o.end(),console.log(this._name+".quitGroup ok, groupID:"+t);let e=Dc.getLocalGroup(t)["type"];return Dc.deleteLocalGroup(t),Dc.emitGroupListUpdate(),Gc.deleteGroupAttributesCache(t),Lc({groupID:t,type:e})}catch(e){let{errorCode:t,errorInfo:s}=e,r=new n({functionName:"quitGroup",code:t,message:s});throw o.setError(r).end(),console.error(this._name+".quitGroup fail:",r),r}})}},$c=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:[...Sa]};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:n,FaceUrl:o,Introduction:i,InviteJoinOption:a,MaxMemberNum:l,MemberNum:c,Name:u,Owner_Account:d,Type:p,ErrorCode:g,ErrorInfo:_}=t[0];if(0!==g)throw new this._core.helper.ChatError({code:g,message:_});console.log(this._name+".searchGroupByID ok.");var m=Cc(s),v=new Oc({groupID:f,name:u,avatar:o,introduction:i,joinOption:r,inviteOption:a,maxMemberCount:l,memberCount:c,type:p,ownerID:d,createTime:n,groupCustomField:m});return Lc({group:v})}catch(e){throw console.error(this._name+".searchGroupByID fail:",e),e}})}},qc=new class{constructor(){this._name="UpdateGroupProfile"}init(e){e=(this._core=e).helper;e.registerApi({apiName:"updateGroupProfile",context:this})}updateGroupProfile(n){return h(this,void 0,void 0,function*(){let t=n["groupID"],{isUndefined:s}=this._core["utils"],r=Dc.getLocalGroup(t);if(r){let e=r["type"];this._canIUseJoinOption(e)||s(n.joinOption)||(console.warn(this._name+".updateGroupProfile joinOption is unavailable for Work/Meeting/AVChatRoom"),n.joinOption=void 0)}s(n.muteAllMembers)||(n.muteAllMembers=!0===n.muteAllMembers?"On":"Off");try{return yield function(c,u){return h(this,void 0,void 0,function*(){var{groupID:e,name:t,avatar:s,introduction:r,notification:n,muteAllMembers:o,joinOption:i,inviteOption:a,groupCustomField:l}=c,e={GroupId:e,Name:t,FaceUrl:s,Introduction:r,Notification:n,ShutUpAllMember:o,ApplyJoinOption:i,InviteJoinOption:a,AppDefinedData:l?Mc(l):void 0};return u.common.buildAndSendPacket({servcmd:"group_open_http_svc.modify_group_base_info",data:e})})}(n,this._core),console.log(`${this._name}.updateGroupProfile groupID:${t} ok.`),r?(r.updateGroup(n),Dc.emitGroupListUpdate()):r=new Oc(n),Lc({group:r})}catch(e){throw console.error(`${this._name}.updateGroupProfile groupID:${t} fail:`,e),e}})}_canIUseJoinOption(e){return Ic(e)||this._core.common.isCommunity({type:e})}},xc=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=Dc.getLocalGroup(e),{helper:n,OuterConstant:o,common:{getCurrentUserID:i}}=this._core;if((null==r?void 0:r.type)===o.GRP_AVCHATROOM)throw new n.ChatError({functionName:s,code:ac});if(t===i())throw new n.ChatError({functionName:s,code:cc});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,Dc.emitGroupListUpdate(),Lc({group:r})}catch(e){let t=new n.ChatError({functionName:s,code:null==e?void 0:e.errorCode,message:null==e?void 0:e.errorInfo});throw console.error(this._name+`.${s} fail:`,t),t}})}},Vc=new class{constructor(){this._name="GetGroupOnlineMemberCount",this._onlineMemberCountMap=new Map}init(e,t){e=(this._core=e).helper;e.registerApi({apiName:"getGroupOnlineMemberCount",context:this,matcher:()=>!t.getInstalledSubPlugins().includes(la)})}getGroupOnlineMemberCount(n){return h(this,void 0,void 0,function*(){let s="getGroupOnlineMemberCount",e=Dc.hasLocalGroup(n);if(console.log(`${this._name}.${s} groupID:${n} hasLocalGroup:`+e),!e)return Lc({memberCount:0});let r=Date.now();if(this._onlineMemberCountMap.has(n)){let e=this._onlineMemberCountMap.get(n),{lastReqTime:t=0,memberCount:s=0}=e||{};if(r-t<=6e4)return Lc({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}})})}(n,this._core),{OnlineMemberNum:t=0}=e||{};return this._onlineMemberCountMap.set(n,{lastReqTime:Date.now(),memberCount:t}),console.log(`${this._name}.${s} ok. groupID:${n} memberCount:`+t),Lc({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}})}},Bc=new class{init(e,t){console.log("GroupAction.init"),Nc.init(e),bc.init(e),wc.init(e,t),kc.init(e,t),Fc.init(e,t),$c.init(e),Pc.init(e),qc.init(e),xc.init(e),Vc.init(e,t)}dismissGroup(e){return wc.dismissGroup(e)}joinGroup(e){return kc.joinGroup(e)}quitGroup(e){return Fc.quitGroup(e)}getGroupOnlineMemberCount(e){return Vc.getGroupOnlineMemberCount(e)}},jc=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 Lc({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(o){return h(this,void 0,void 0,function*(){var{type:e,startTime:t=0,limit:s=20}=o||{},r=this._core["common"];let n;try{n=yield function(n,o){return h(this,void 0,void 0,function*(){var{type:e,startTime:t,limit:s,handleAccount:r}=n;return o.common.buildAndSendPacket({servcmd:"group_open_http_svc.get_pendency",data:{Type:e,StartTime:t,Limit:s,Handle_Account:r}})})}({type:e,startTime:t,limit:s,handleAccount:r.getCurrentUserID()},this._core)}catch(e){if(11e3!==(null==e?void 0:e.errorCode))throw e;n={}}var{NextStartTime:e=0,PendencyList:t=[]}=n||{};return 0===e?t:(s=yield this._getGroupApplicationList(Object.assign(Object.assign({},o),{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:n,From_Account:o,GroupId:i,GroupName:a,PendencyType:l,To_Account:c}=e;return{handled:e,messageKey:t,applicant:o,applicantNick:n,groupID:i,groupName:a,authentication:r,applicationType:l,userID:c,note:s}}},Kc=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)===La?yield function(i,a){return h(this,void 0,void 0,function*(){var{groupID:e,handleAction:t,handleMessage:s,applicant:r,authentication:n,invitee:o}=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:n,Invited_Account:o}})})}(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:n,messageKey:o}=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:n,MsgKey:o}})})}(r,this._core),console.log(this._name+`.${s} ok.`);let e=Dc.getLocalGroup(r.groupID);return Lc({group:e})}catch(e){let t=new this._core.helper.ChatError({functionName:s,code:null==e?void 0:e.errorCode,message:null==e?void 0:e.errorInfo});throw console.error(this._name+`.${s} fail:`,t),t}})}_handleParams(e){var{handleAction:e,handleMessage:t,message:s,application:r}=e;let n,o,i,a,l;if(s){let e=(s||{})["payload"];n=e.operatorID,o=null==(s=e.groupProfile)?void 0:s.groupID,i=e.authentication,a=e.messageKey}else n=(null==r?void 0:r.applicant)||"",o=(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)===La&&(l=r.userID),{handleAction:e,handleMessage:t,applicant:n,invitee:l,groupID:o,authentication:i,messageKey:a}}},Wc=new class{init(e){console.log("GroupApplication.init"),jc.init(e),Kc.init(e)}};let Hc=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}}=ua["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&&Ec(this.memberCustomField,e.memberCustomField),s(this,e,["memberCustomField","marks","onlineStatus","muteTime"],t)}};function Yc(a,l){return h(this,void 0,void 0,function*(){var{groupID:e,userID:t,muteTime:s,role:r,nameCard:n,memberCustomField:o}=a;let i;e={GroupId:e,Member_Account:t,ShutUpTime:s,Role:r,NameCard:n,AppMemberDefinedData:i=o?Mc(o):i};return l.common.buildAndSendPacket({servcmd:"group_open_http_svc.modify_group_member_info",data:e})})}var zc=new class{constructor(){this._name="GetGroupMemberList"}init(e,t){e=(this._core=e).helper;e.registerApi({apiName:"getGroupMemberList",context:this,matcher:()=>!t.getInstalledSubPlugins().includes(la)})}getGroupMemberList(r){return h(this,void 0,void 0,function*(){let o="getGroupMemberList",{groupID:i,offset:a=0,count:e=100,role:t="",filter:s=""}=r;console.log(`${this._name}.${o} groupID:${i} offset:${a} count:${e} role:${t} filter:`+s);var l=Dc.getLocalGroup(i),c=100<e?100:e,u={groupID:i,offset:a,limit:c,memberRoleFilter:Na.includes(t)?[t]:void 0,memberInfoFilter:ba};try{let e=yield function(o,i){return h(this,void 0,void 0,function*(){var{groupID:e,offset:t,limit:s,memberRoleFilter:r,memberInfoFilter:n}=o;return i.common.buildAndSendPacket({servcmd:"group_open_http_svc.get_group_member_info",data:{GroupId:e,Offset:t,Limit:s,MemberRoleFilter:r,MemberInfoFilter:n}})})}(u,this._core),{MemberList:t,MemberNum:s,Next:r}=e||{};console.log(`${this._name}.${o} ok, totalMemberCount:${s} next:`+r);var{utils:{isArray:d,isEmpty:p},common:{isCommunity:g}}=this._core;if(l&&(l.memberCount=s),!d(t)||0===t.length)return Lc({memberList:[],offset:0});let n=a+c;g({groupID:i})&&(n=p(r)?0:r),t.length<c&&(n=0);var _=this._convertMemberInfo(t),_=yield this._patchAvatarAndNick(_),m=this._generateGroupMember(_);return Lc({memberList:m,offset:n})}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}})}_convertMemberInfo(s){var r=[];for(let e=0,t=s.length;e<t;e++){var{AppMemberDefinedData:n,JoinTime:o,Member_Account:i,OnlineStatus:a,Role:l,ShutUpUntil:c}=s[e],n=Cc(n);r.push({userID:i,joinTime:o,onlineStatus:a,role:l,muteUntil:c,memberCustomField:n})}return r}_patchAvatarAndNick(o){return h(this,void 0,void 0,function*(){let e,t=o.map(e=>e.userID),s=yield null==(e=this._core.user.userProfile)?void 0:e.getUserProfile({userIDList:t}),r=(null==s?void 0:s.data)||[],n=new Map(r.map(e=>[e.userID,e]));return o.forEach(e=>{var t,s;n.has(e.userID)&&({nick:t="",avatar:s=""}=n.get(e.userID),e.nick=t,e.avatar=s)}),o})}_generateGroupMember(s){var r=[];for(let e=0,t=s.length;e<t;e++){var n=new Hc(s[e]);r.push(n)}return r}},Jc=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:n,memberCustomFieldFilter:o}=t,e=Dc.getLocalGroup(r),{helper:i,utils:{isArray:a}}=this._core;if(e&&Sc(e.type))throw new i.ChatError({functionName:s,replacement1:s,code:mc});50<n.length&&(console.warn(`${this._name}.${s} userIDList length:${n.length} exceeds limit 50`),n.splice(50));try{let e=yield function(n,o){return h(this,void 0,void 0,function*(){var{groupID:e,userIDList:t,memberInfoFilter:s,memberCustomFieldFilter:r}=n;return o.common.buildAndSendPacket({servcmd:"group_open_http_svc.get_specified_group_member_info",data:{GroupId:e,Member_List_Account:t,MemberInfoFilter:s,AppDefinedDataFilter_GroupMember:r}})})}({groupID:r,userIDList:n,memberCustomFieldFilter:o,memberInfoFilter:[...ba]},this._core),t=(console.log(this._name+`.${s} ok.`),e||{})["MemberList"];var l,c;return a(t)&&0!==t.length?(l=this._convertMemberInfo(t),l=yield this._getMemberAvatarAndNick(l),c=this._generateGroupMember(l),Lc({memberList:c})):Lc({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:n,JoinTime:o,Member_Account:i,OnlineStatus:a,Role:l,ShutUpUntil:c}=s[e],n=Cc(n);r.push({userID:i,joinTime:o,onlineStatus:a,role:l,muteUntil:c,memberCustomField:n})}return r}_getMemberAvatarAndNick(o){return h(this,void 0,void 0,function*(){let e,t=o.map(e=>e.userID),s=yield null==(e=this._core.user.userProfile)?void 0:e.getUserProfile({userIDList:t}),r=(null==s?void 0:s.data)||[],n=new Map(r.map(e=>[e.userID,e]));return o.forEach(e=>{var t,s;n.has(e.userID)&&({nick:t="",avatar:s=""}=n.get(e.userID),e.nick=t,e.avatar=s)}),o})}_generateGroupMember(s){var r=[];for(let e=0,t=s.length;e<t;e++){var n=new Hc(s[e]);r.push(n)}return r}},Qc=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=Dc.getLocalGroup(a),s=this._core["helper"];if(l&&Sc(l.type))throw new s.ChatError({functionName:i,code:dc});var c=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:c},this._core),{MemberList:t=[]}=e||{},{failureUserIDList:s,successUserIDList:r,existedUserIDList:n,overLimitUserIDList:o}=this._handleResult(t);return console.log(`${this._name}.${i} groupID:${a} ok, successUserIDList:${r} failureUserIDList:${s} existedUserIDList:${n} overLimitUserIDList:`+o),Lc({failureUserIDList:s,successUserIDList:r,existedUserIDList:n,overLimitUserIDList:o,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=[],n=[],o=[];return e.forEach(e=>{var{Result:e,Member_Account:t}=e;e===Ga?s.push(t):e===wa?r.push(t):e===Pa?n.push(t):e===Ua&&o.push(t)}),{failureUserIDList:s,successUserIDList:r,existedUserIDList:n,overLimitUserIDList:o}}},Xc=new class{constructor(){this._name="DeleteGroupMember"}init(e,t){e=(this._core=e).helper;e.registerApi({apiName:"deleteGroupMember",context:this,matcher:()=>!t.getInstalledSubPlugins().includes(la)})}deleteGroupMember(i){return h(this,void 0,void 0,function*(){let s="deleteGroupMember",{groupID:e,userIDList:t}=i,r=Dc.getLocalGroup(e),{helper:n,utils:{isUndefined:o}}=this._core;if(o(r))throw new n.ChatError({functionName:s,code:rc});20<t.length&&(console.warn(`${this._name}.${s} userIDList length:${t.length} exceeds limit 20`),t.splice(20));try{return yield function(r,n){return h(this,void 0,void 0,function*(){var{groupID:e,userIDList:t,reason:s}=r;return n.common.buildAndSendPacket({servcmd:"group_open_http_svc.delete_group_member",data:{GroupId:e,MemberToDel_Account:t,Reason:s}})})}({groupID:e,userIDList:t},this._core),console.log(`${this._name}.${s} ok, groupID:${e} userIDList length:`+t.length),Lc({group:r,userIDList:t})}catch(e){let t=new n.ChatError({functionName:s,code:null==e?void 0:e.errorCode,message:null==e?void 0:e.errorInfo});throw console.error(this._name+`.${s} fail:`,t),t}})}},Zc=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 Yc(i,this._core);let{groupID:e,userID:t,muteTime:s}=i;console.log(`${this._name}.${r} ok, groupID:${e} userID:${t} muteTime:`+s);var n=Dc.getLocalGroup(e),o=new Hc({userID:t,muteTime:s});return Lc({group:n,member:o})}catch(e){n=new t.ChatError({functionName:r,code:null==e?void 0:e.errorCode,message:null==e?void 0:e.errorInfo});throw console.error(this._name+`.${r} fail:`,n),n}})}_preCheckSettingMuteParams(e){var e=e["userID"],{store:t,helper:s}=this._core;if(e===t.get("login").userId)throw new s.ChatError({functionName:"setGroupMemberMuteTime",code:_c})}},eu=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 Yc(i,this._core);let{groupID:e,userID:t,role:s}=i;console.log(`${this._name}.${r} ok, groupID:${e} userID:${t} role:`+s);var n=Dc.getLocalGroup(e),o=new Hc({userID:t,role:s});return Lc({group:n,member:o})}catch(e){n=new t.ChatError({functionName:r,code:null==e?void 0:e.errorCode,message:null==e?void 0:e.errorInfo});throw console.error(this._name+`.${r} fail:`,n),n}})}_preCheckSettingRoleParams(e){var{groupID:e,userID:t,role:s}=e,{store:r,helper:n,OuterConstant:o,common:{isCommunity:i}}=this._core,a=Dc.getLocalGroup(e);if((null==(a=null==a?void 0:a.selfInfo)?void 0:a.role)!==o.GRP_MBR_ROLE_OWNER)throw new n.ChatError({functionName:"setGroupMemberRole",code:pc});if(t===r.get("login").userId)throw new n.ChatError({functionName:"setGroupMemberRole",code:gc});a=[...Na];if(i({groupID:e})&&a.push(o.GRP_MBR_ROLE_CUSTOM),!a.includes(s))throw new n.ChatError({functionName:"setGroupMemberRole",code:hc})}},tu=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 n="setGroupMemberNameCard",{helper:s,common:{getCurrentUserID:o}}=this._core;this._preCheckSettingNameCardParams(l);try{let{groupID:e,userID:t=o(),nameCard:s}=l,r={groupID:e,userID:t,nameCard:s};yield Yc(r,this._core),console.log(`${this._name}.${n} ok, groupID:${e} userID:${t} nameCard:`+s);var i=Dc.getLocalGroup(e),a=new Hc({userID:t,nameCard:s});return Lc({group:i,member:a})}catch(e){let t=new s.ChatError({functionName:n,code:null==e?void 0:e.errorCode,message:null==e?void 0:e.errorInfo});throw console.error(this._name+`.${n} fail:`,t),t}})}_preCheckSettingNameCardParams(e){var e=e["groupID"],t=this._core["helper"],e=Dc.getLocalGroup(e);if(Sc(null==e?void 0:e.type))throw new t.ChatError({functionName:"setGroupMemberNameCard",code:mc})}},su=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 n="setGroupMemberCustomField",{helper:s,common:{getCurrentUserID:o}}=this._core;this._preCheckSettingCustomFiledParams(l);try{let{groupID:e,userID:t=o(),memberCustomField:s}=l,r={groupID:e,userID:t,memberCustomField:s};yield Yc(r,this._core),console.log(`${this._name}.${n} ok, groupID:${e} userID:${t} memberCustomField:`+JSON.stringify(s));var i=Dc.getLocalGroup(e),a=new Hc({userID:t,memberCustomField:s});return Lc({group:i,member:a})}catch(e){let t=new s.ChatError({functionName:n,code:null==e?void 0:e.errorCode,message:null==e?void 0:e.errorInfo});throw console.error(this._name+`.${n} fail:`,t),t}})}_preCheckSettingCustomFiledParams(e){var e=e["groupID"],t=this._core["helper"],e=Dc.getLocalGroup(e);if(Sc(null==e?void 0:e.type))throw new t.ChatError({functionName:"setGroupMemberCustomField",code:mc})}},ou=new class{init(e,t){console.log("GroupMember.init"),zc.init(e,t),Jc.init(e),Qc.init(e),Xc.init(e,t),Zc.init(e),eu.init(e),tu.init(e),su.init(e)}getGroupMemberList(e){return zc.getGroupMemberList(e)}deleteGroupMember(e){return Xc.deleteGroupMember(e)}},nu=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{yc(t,pa);var e,s,r,{groupID:n,keyList:o=[]}=l,{avChatRoomKey:i,lastUpdateTime:a}=Uc.getLocalGroupCounters(n);return Date.now()-a>=this._getExpireTime()&&(e=yield function(n){return h(this,void 0,void 0,function*(){var{groupID:e,GroupCounterKeys:t,avChatRoomKey:s}=n,r=ua.core["common"];return r.buildAndSendPacket({servcmd:"group_open_http_svc.get_group_counter",data:{GroupId:e,keyList:t,BytesKey:s}})})}({groupID:n,keyList:o,avChatRoomKey:i}),{GroupCounter:s=[],GroupCounterSeq:r}=e,Uc.updateLocalGroupCounters({groupID:n,counterList:s,groupCounterSeq:r})),{code:0,data:{counters:Uc.getLocalCounters(n,o)}}}catch(e){Ac(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)}},iu=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(ha,e)})}increaseGroupCounter(e){return h(this,void 0,void 0,function*(){return this._handleCounterOperation(ga,e)})}decreaseGroupCounter(e){return h(this,void 0,void 0,function*(){return this._handleCounterOperation(_a,e)})}_handleCounterOperation(a,l){return h(this,void 0,void 0,function*(){var t=a+"GroupCounter";try{yc(t,pa);var{groupID:e,key:s,value:r=0}=l,n=Uc.getLocalGroupCounters(e)["avChatRoomKey"],o=a===ha?this._convertObjectToList(l.counters):[{Key:s,Value:r}],i=yield this._updateGroupCounters({groupID:e,counterList:o,avChatRoomKey:n,mode:a});return Uc.setGroupCounters(e,i),{code:0,data:{counters:i}}}catch(e){Ac(t,e)}})}_updateGroupCounters(o){return h(this,void 0,void 0,function*(){let e=yield function(){var{groupID:e,counterList:t,mode:s,avChatRoomKey:r}=o,n=ua.core["common"];return n.buildAndSendPacket({servcmd:"group_open_http_svc.update_group_counter",data:{GroupId:e,GroupCounter:t,Mode:s,BytesKey:r}})}(),{GroupCounter:t=[]}=e,s={};return t.forEach(e=>{var{Key:e,Value:t=0}=e;s[e]=t}),s})}_convertObjectToList(e){return Object.entries(e).map(([e,t])=>({Key:e,Value:t||0}))}},ru=new class{init(e){this._core=e,nu.init(e),iu.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!==ma&&e!==fa||this._processAndNotifyCounterUpdate(r,t,s),e===va&&Uc.deleteLocalGroupCounters({groupID:r,groupCounterSeq:t,counterList:s})})}_processAndNotifyCounterUpdate(s,e,t){let{OuterEvent:r,notificationCenter:n}=this._core;Uc.updateLocalGroupCounters({groupID:s,groupCounterSeq:e,counterList:t}),t.forEach(({Key:e,Value:t=0})=>{n.emitOuterEvent(r.GROUP_COUNTER_UPDATED,{name:r.GROUP_COUNTER_UPDATED,data:{groupID:s,key:e,value:t}})})}reset(){Uc.reset()}},au=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:n,groupAttributes:o}=e,{serverMainSequence:i,avChatRoomKey:a}=Gc.getGroupAttributesCache(n),l=Gc.convertKeyValueMapToList(o);try{let e=yield function(n,o){return h(this,void 0,void 0,function*(){var{groupID:e,mainSequence:t,groupAttributeList:s,avChatRoomKey:r}=n;return o.common.buildAndSendPacket({servcmd:"group_open_http_svc.set_group_attr",data:{GroupId:e,AttrMainSeq:t,GroupAttr:s,BytesKey:r,AttrControl:["RaceConflict"]}})})}({groupID:n,avChatRoomKey:a,groupAttributeList:l,mainSequence:i},this._core),{AttrMainSeq:t,GroupAttr:s}=e||{};console.log(`${this._name}.${r} ok. groupID:${n} serverMainSequence:`+t);var c=s.map(e=>{var{Key:e,seq:t}=e;return{key:e,value:o[e],sequence:t}});return Gc.saveGroupAttributesCacheValuesCopy(n),Gc.refreshGroupAttributesCache({groupID:n,serverMainSequence:t,groupAttributeList:c,operation:ka}),Gc.emitGroupAttributesUpdated(n),Lc({groupAttributes:o})}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}})}},cu=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:n,groupAttributes:o}=e,{serverMainSequence:i,avChatRoomKey:a,values:l}=Gc.getGroupAttributesCache(n),c=Gc.convertKeyValueMapToList(o).map(e=>{var{key:t,value:s}=e;return{key:t,value:s,seq:(null==(t=l.get(e.key))?void 0:t.sequence)||0}});try{let e=yield function(n,o){return h(this,void 0,void 0,function*(){var{groupID:e,mainSequence:t,groupAttributeList:s,avChatRoomKey:r}=n;return o.common.buildAndSendPacket({servcmd:"group_open_http_svc.modify_group_attr",data:{GroupId:e,AttrMainSeq:t,GroupAttr:s,BytesKey:r,AttrControl:["RaceConflict"]}})})}({groupID:n,avChatRoomKey:a,groupAttributeList:c,mainSequence:i},this._core),{AttrMainSeq:t,GroupAttr:s}=e||{};console.log(`${this._name}.${r} ok. groupID:${n} serverMainSequence:`+t);var u=s.map(e=>{var{Key:e,seq:t}=e;return{key:e,value:o[e],sequence:t}});return Gc.saveGroupAttributesCacheValuesCopy(n),Gc.refreshGroupAttributesCache({groupID:n,serverMainSequence:t,groupAttributeList:u,operation:Fa}),Gc.emitGroupAttributesUpdated(n),Lc({groupAttributes:o})}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}})}},uu=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:n,operation:o,groupAttributeList:i}=(0===t.length?yield this._clearGroupAttributes(e):yield this._deleteGroupAttributes(e,t))||{};return console.log(`${this._name}.${s} ok. groupID:${e} operation: `+o),Gc.saveGroupAttributesCacheValuesCopy(e),Gc.refreshGroupAttributesCache({groupID:e,serverMainSequence:n,groupAttributeList:i,operation:o}),Gc.emitGroupAttributesUpdated(e),Lc({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}=Gc.getGroupAttributesCache(i),r=[],n=[];a.forEach(e=>{var t;s.has(e)&&({sequence:t=0}=s.get(e)||{},n.push({key:e,seq:t}),r.push(e))});var o=((yield function(n,o){return h(this,void 0,void 0,function*(){var{groupID:e,mainSequence:t,groupAttributeList:s,avChatRoomKey:r}=n;return o.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:n,mainSequence:e},this._core))||{})["AttrMainSeq"];return{resultList:r,serverMainSequence:o,groupAttributeList:n,operation:qa}})}_clearGroupAttributes(r){return h(this,void 0,void 0,function*(){var{serverMainSequence:e,avChatRoomKey:t,values:s}=Gc.getGroupAttributesCache(r),s=[...s.keys()],t=((yield function(r,n){return h(this,void 0,void 0,function*(){var{groupID:e,mainSequence:t,avChatRoomKey:s}=r;return n.common.buildAndSendPacket({servcmd:"group_open_http_svc.clear_group_attr",data:{GroupId:e,AttrMainSeq:t,BytesKey:s,AttrControl:["RaceConflict"]}})})}({groupID:r,avChatRoomKey:t,mainSequence:e},this._core))||{})["AttrMainSeq"];return{resultList:s,serverMainSequence:t,operation:$a}})}},lu=new class{constructor(){this._name="GetGroupAttributes"}init(e){e=(this._core=e).helper;e.registerApi({apiName:"getGroupAttributes",context:this})}getGroupAttributes(u){return h(this,void 0,void 0,function*(){let r="getGroupAttributes",n=u["groupID"],{avChatRoomKey:o,lastUpdateTime:e,localMainSequence:t,serverMainSequence:s}=Gc.getGroupAttributesCache(n),{ssoLog:i,helper:{ChatError:a}}=this._core,l=i.createSSOLogData({method:"getGroupAttributes"});if(l.setLogInfo({message:`groupID:${n} localMainSequence:${t} serverMainSequence:${s} keyList:`+u.keyList}),3e4<=Date.now()-e||t<s)try{let e=yield this.getGroupAttributesFromServer({groupID:n,avChatRoomKey:o}),t=Gc.getGroupAttributesCacheValues(u),{serverGroupAttributeList:s=[]}=e||{};return l.setLogInfo({moreMessage:"from server, count:"+s.length}).end(),console.log(this._name+`.${r} from server. groupID:`+n),Lc({groupAttributes:t})}catch(e){let t=new a({functionName:r,code:null==e?void 0:e.errorCode,message:null==e?void 0:e.errorInfo});throw l.setError(t).end(),console.error(this._name+`.${r} fail:`,t),t}var c=Gc.getGroupAttributesCacheValues(u);return l.setLogInfo({moreMessage:"from cache."}).end(),console.log(this._name+`.${r} from cache. groupID:`+n),Lc({groupAttributes:c})})}getGroupAttributesFromServer(n){return h(this,void 0,void 0,function*(){var e=this._core["utils"]["isUndefined"],{groupID:t,avChatRoomKey:s}=n,{AttrMainSeq:e=0,GroupAttrAry:s}=(yield function(r,n){return h(this,void 0,void 0,function*(){var{groupID:e,groupType:t,avChatRoomKey:s}=r;return n.common.buildAndSendPacket({servcmd:"group_open_attr_http_svc.get_group_attr",data:{GroupId:e,GroupType:t,Key:s}})})}({groupID:t,avChatRoomKey:s,groupType:e(s)?Ba:Va},this._core))||{},r=(console.log(this._name+`._getGroupAttributesFromServer ok. groupID:${t} serverMainSequence:`+e),s.map(e=>{var{key:e,value:t,seq:s}=e;return{key:e,value:t,sequence:s}}));return Gc.refreshGroupAttributesCache({groupID:t,serverMainSequence:e,groupAttributeList:r,operation:xa}),{serverGroupAttributeList:s}})}},du=new class{init(e){console.log("GroupAttribute.init"),au.init(e),cu.init(e),uu.init(e),lu.init(e),Gc.init(e)}isGroupAttributesUpdated(e){return Gc.isGroupAttributesUpdated(e)}handleGroupAttributesUpdated(e){let{to:t,elements:{newGroupProfile:s}}=e,r=s["groupAttributeOption"],{serverMainSequence:n,withChangedAttributeInfo:o}=r,i=Gc.getGroupAttributesCache(t)["localMainSequence"],a=n-i;if(console.log(`GroupAttribute.handleGroupAttributesUpdated groupID:${t} withChangedAttributeInfo:${o} diffSequence:`+a),0!=a)if(Gc.saveGroupAttributesCacheValuesCopy(t),1!==o||1!=a){if(Gc.hasGroupAttributesCache(t)){let e=Gc.getGroupAttributesCache(t)["avChatRoomKey"];lu.getGroupAttributesFromServer({groupID:t,avChatRoomKey:e}).then(()=>{Gc.emitGroupAttributesUpdated(t)}).catch(()=>{})}}else Gc.handleGroupAttributesUpdated({groupID:t,groupAttributeOption:r})}reset(){Gc.reset()}};function pu(e,t="tips"){let{ClientSeq:s,From_Account:r,MsgClientTime:n,MsgPriority:o,MsgRandom:i,MsgSeq:a,MsgTimeStamp:l,TinyId:c,ToGroupId:u,GroupInfo:d,MsgBody:h}=e,p=function(){var{GroupCode:e,GroupId:t,GroupName:s,GroupType:r,MsgFrom_AccountExtraInfo:n,From_Account:o,To_Account:i}=d;return{groupCode:e,groupID:t,groupName:s,type:r,messageFromAccountExtraInformation:n,from:o,to:i}}();return{clientSequence:s,from:r,clientTime:n,priority:o,random:i,sequence:a,time:l,tinyID:c,to:u,groupProfile:p,elements:("tips"===t?hu:_u)(h)}}function hu(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=>gu(e));break;case"MsgOperatorMemberExtraInfo":e.operatorInfo=gu(r[s]);break;case"MsgGroupNewInfo":e.newGroupProfile=function(i){let e={};return Object.keys(i).forEach(o=>{switch(o){case"GroupIntroduction":e.introduction=i[o];break;case"GroupName":e.groupName=i[o];break;case"GroupFaceUrl":e.avatar=i[o];break;case"GroupNotification":e.notification=i[o];break;case"ApplyJoinOption":e.joinOption=i[o];break;case"InviteJoinOption":e.inviteOption=i[o];break;case"ShutupAll":e.muteAllMembers=i[o];break;case"Owner_Account":e.ownerID=i[o];break;case"GroupAttrOption":e.groupAttributeOption=function(){var{BytesChangedKeys:e,GroupAttrSeq:t,OpType:s,PushChangedAttrValFlag:r,GroupAttrInfo:n}=i[o];return{changedKeyList:e,groupAttributeList:n.map(e=>{var{Key:e,Val:t,SubKeySeq:s}=e;return{key:e,value:t,sequence:s}}),serverMainSequence:t,operation:s,withChangedAttributeInfo:r}}()}}),e}(r[s]);break;case"MsgMemberInfo":e.msgMemberInfo=r[s].map(e=>{var{ShutupTime:e,User_Account:t}=e;return{muteTime:e,userID:t}});break;case"OnlineMemberInfo":e.onlineMemberInfo=function(){var{ExpireTime:e,OnlineMemberNum:t}=r[s];return{expireTime:e,onlineMemberNum:t}}();break;case"GroupCounterInfo":e.groupCounterInfo=r[s].map(e=>{var{GroupCounterSeq:e,GroupCounter:t,Type:s}=e;return{type:s,groupCounterSeq:e,counterList:t}})}}),e}function gu(e){var{ImageUrl:e,NickName:t,Role:s,UserId:r}=e;return{avatar:e,nick:t,role:s,userID:r}}function _u(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 mu{constructor(e){this.type=ua.core.OuterConstant.MSG_GRP_TIP,this.content={},this._initContent(e)}static parseServerPushElement(e){e=hu(e);return new mu(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];Ya[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 vu=new class{constructor(){this._name="GroupTipsNotification"}init(e){var{common:{workflowManager:t},constants:{WORKFLOW_NAME:s,WORKFLOW_STEP:r}}=this._core=e,{message:{messageFactory:e},OuterConstant:n}=e;null!=e&&e.registerElementClass(n.MSG_GRP_TIP,mu),t.registerWorkflowStep(s.SYNC_SERVER_INFO_AFTER_RE_ONLINE,r.GROUP_TIPS_RECOVER,this._handleGroupTipsRecover,this)}onNewGroupTips(e){let{messageList:t,conversationUpdateFieldList:s}=this._handleGroupTips(e),{notificationCenter:r,OuterEvent:n,appStore:{conversationStore:o}}=this._core;null!=s&&s.forEach(e=>{var{conversationID:e,lastMessage:t,unreadCount:s}=e,{unreadCount:r=0}=o.getConversation(e)||{};o.updateConversation(e,{lastMessage:t,unreadCount:s+r})}),0<t.length&&(r.emitOuterEvent(n.MESSAGE_RECEIVED,{name:n.MESSAGE_RECEIVED,data:t}),this._handleGroupTipMessage(t))}_handleGroupTips(e,s=!0){let{Event:r,GroupTips:n}=e,o=new Map,t=[],i=[];for(let t=0,e=n.length;t<e;t++){let e=pu(n[t],"tips");if(r===Ka){if(du.isGroupAttributesUpdated(e)){du.handleGroupAttributesUpdated(e);continue}if(ru.isGroupCounterUpdated(e)){ru.handleGroupCounterUpdated(e);continue}}var a=e["groupProfile"]["groupID"];if(Dc.hasLocalGroup(a)){a=this._assembleMessage(e);if(r===Ka&&(a._onlineOnlyFlag=!0,i.push(a)),r===ja){if(!this._core.message.messageDataHandler.storeConversationMessage(a)&&s)continue;i.push(a)}this._handleConversationOptions(o,a)}}return t.push(...o.values()),{conversationUpdateFieldList:t,messageList:i}}_assembleMessage(e){var{OuterConstant:t,message:{messageFactory:s}}=this._core,t=(e.flow="in",e.conversationType=t.CONV_GROUP,s.createMessage(e)),s=(this._patchNickAndAvatar(e.elements,t),new mu(Object.assign(Object.assign({},e.elements),{groupProfile:Object.assign({},e.groupProfile)})));return t.setElement(s),t.isSystemMessage=!1,t}_patchNickAndAvatar(e,s){let{utils:{isEmpty:t},OuterConstant:{GROUP_TIPS_OPERATION_TYPE:r}}=this._core,{operationType:n,memberInfoList:o,operatorInfo:i}=e,a={};if(t(o)?t(i)||(a=i):n!==r.JOINED&&n!==r.KICKED&&n!==r.ADMIN_SET&&n!==r.ADMIN_CANCELED||(a=Object.assign({},o[0])),!t(a)){let{nick:e="",avatar:t=""}=a;s.nick=e,s.avatar=t}}_handleConversationOptions(e,t){var{common:{getMessagePreviewText:s},utils:{isObject:r}}=this._core,{conversationID:n,conversationType:o}=t;let i;if(e.has(n))i=e.get(n),"in"!==t.flow||t._isExcludedFromUnreadCount||t._onlineOnlyFlag||i.unreadCount++,i.type=o,i.lastMessage=t._isExcludedFromLastMessage?"":Object.assign({},t);else{let e=0;"in"!==t.flow||t._isExcludedFromUnreadCount||t._onlineOnlyFlag||(e=1),i={conversationID:n,unreadCount:e,type:o,lastMessage:t._isExcludedFromLastMessage?"":Object.assign({},t)}}r(i.lastMessage)&&(i.lastMessage.messageForShow=s(i.lastMessage.type,i.lastMessage.payload)),e.set(n,i)}_handleGroupTipMessage(e){let{GROUP_TIPS_OPERATION_TYPE:s}=this._core["OuterConstant"];e.forEach(e=>{var t=e.payload["operationType"];switch(t){case s.JOINED:this._handleNewMemberJoined(e);break;case s.QUITTED:this._handleMemberQuitted(e);break;case s.KICKED:this._handleMemberKicked(e);break;case s.GROUP_PROFILE_UPDATED:this._handleGroupProfileUpdated(e)}})}_handleNewMemberJoined(e){this._handleGroupMemberCountUpdated(e)}_handleMemberQuitted(e){this._handleGroupMemberCountUpdated(e)}_handleMemberKicked(e){this._handleGroupMemberCountUpdated(e)}_handleGroupProfileUpdated(e){let t,{newGroupProfile:s,groupProfile:r,operatorInfo:n}=e.payload,o=r.groupID,i=Dc.getLocalGroup(o);Object.keys(s).forEach(e=>{switch(e){case"ownerID":this._handleGroupOwnerChanged(o,s);break;case"groupName":i.name=s[e];break;default:i[e]=s[e]}});var e=this._core["utils"]["isUndefined"];e(n)||(null==(t=null==i?void 0:i.selfInfo)?void 0:t.userID)!==n.userID||Object.keys(n).forEach(e=>{"nameCard"===e&&i.updateSelfInfo({nameCard:n[e]}),"role"===e&&this._updateSelfRole(i,n[e])}),Dc.emitGroupListUpdate(),Dc.updateConversationGroupProfile(o)}_handleGroupOwnerChanged(e,t){var{common:s,OuterConstant:r}=this._core,e=Dc.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===Wa?r=s.GRP_MBR_ROLE_OWNER:t===Ha&&(r=s.GRP_MBR_ROLE_ADMIN),e.updateSelfInfo({role:r})}_handleGroupMemberCountUpdated(e){var{memberCount:e,groupProfile:{groupID:t}}=e.payload,s=Dc.getLocalGroup(t),r=this._core["utils"]["isNumber"];s&&r(e)&&s.memberCount!==e&&(s.memberCount=e,Dc.emitGroupListUpdate(),Dc.updateConversationGroupProfile(t))}_handleGroupTipsRecover(e){var t=this._core["utils"]["isArray"],e=((null==e?void 0:e.result)||{})["groupTipList"];t(e)&&e.forEach(e=>{e=this._handleGroupTips({Event:e.Event,GroupTips:[e]},!1).messageList;this._handleGroupTipMessage(e)})}};class fu{constructor(e){this.type=ua.core.OuterConstant.MSG_GRP_SYS_NOTICE,this.content={},this._initContent(e)}static parseServerPushElement(e){e=_u(e);return new fu(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];za[r]&&(this.content.groupProfile[r]=t[r])}}}var Iu=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,fu)}onNewGroupSystemNotification(e){var{GroupTips:e=[],isInstantMessage:t=!0}=e,{conversationUpdateFieldList:e,messageList:s}=(console.log(`${this._name}.onNewGroupSystemNotification count:${e.length} isInstantMessage:`+t),this._handleGroupSystemNotification(e,t)),{notificationCenter:r,OuterEvent:n}=this._core;0<e.length&&this._handleGroupSysTemMessage(t,s),!0===t&&0<s.length&&r.emitOuterEvent(n.MESSAGE_RECEIVED,{name:n.MESSAGE_RECEIVED,data:s})}_handleGroupSystemNotification(t,s){var r=[];let n={};for(let e=0;e<t.length;e++){var o=pu(t[e],"system"),i=o["elements"]["operationType"];i!==tc&&(i=this._assembleMessage(o),this._core.message.messageDataHandler.storeConversationMessage(i))&&(r.push(i),n=this._handleConversationOptions(i,s))}return n.lastMessage=r[r.length-1],{conversationUpdateFieldList:0<r.length?[n]:[],messageList:r}}_assembleMessage(e){var{message:{messageFactory:t},OuterConstant:s,utils:{randomInt:r}}=this._core,s=(e.flow="in",e.conversationType=s.CONV_SYSTEM,e.conversationSubType=e.groupProfile.type,e.conversationID=s.CONV_SYSTEM,t.createMessage(e)),t=new fu(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 Ja:this._handleGroupJoinResult(e);break;case Qa:this._handleMemberKicked(e);break;case Xa:this._handleGroupDismissed(e);break;case Za:this._handleGroupInvitedResult(e);break;case ec:this._handleGroupQuitResult(e);break;case sc:this._handleMessageRemindTypeSynced(e);break;case oc:this._handleAVChatRoomMemberBanned(e)}})}_handleGroupJoinResult(e){var e=e.payload["groupProfile"],{groupID:t,type:s}=e,r=Dc.hasLocalGroup(t);console.log(this._name+`._handleGroupJoinResult groupID:${t} type:${s} hasLocalGroup:`+r),r||Sc(s)||(Dc.updateLocalGroup([Object.assign({},e)]),Dc.emitGroupListUpdate())}_handleMemberKicked(e){var{groupID:e,type:t}=e.payload["groupProfile"];Dc.hasLocalGroup(e)&&this._deleteLocalGroup(e,t),this._updateConversationProfile(e,{unreadCount:0})}_handleGroupDismissed(e){var{groupID:e,type:t}=e.payload["groupProfile"];Dc.hasLocalGroup(e)&&this._deleteLocalGroup(e,t),this._updateConversationProfile(e,{unreadCount:0})}_handleGroupInvitedResult(e){var e=e.payload["groupProfile"],e=e["groupID"],t=Dc.hasLocalGroup(e);console.log(this._name+`._handleGroupInvitedResult groupID:${e} hasLocalGroup:`+t),t||Pc.getGroupProfile({groupID:e}).then(e=>{var e=e["data"]["group"];Dc.updateLocalGroup([Object.assign({},e)]),Dc.emitGroupListUpdate()})}_handleGroupQuitResult(e){var{groupID:e,type:t}=e.payload["groupProfile"],s=Dc.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(Sc(e)){let{appStore:{conversationStore:e},OuterConstant:{CONV_GROUP:t}}=this._core;e.deleteConversation(""+t+s)}Dc.deleteLocalGroup(s),Dc.emitGroupListUpdate()}_updateConversationProfile(e,t){var{appStore:{conversationStore:s},OuterConstant:{CONV_GROUP:r}}=this._core,r=""+r+e;s.getConversation(r)&&s.updateConversation(r,t)}},Su=new class{init(e){this._core=e,console.log("GroupNotificationHandler.init"),vu.init(e),Iu.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){vu.onNewGroupTips(e)}_onNewGroupSystemNotification(e){Iu.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 Eu={required:!0,rules:["string"],allowEmpty:!1},Cu={required:!0,rules:["number"],allowEmpty:!1},Mu={required:!0,rules:["array"],allowEmpty:!1},yu={required:!0,rules:["object"],allowEmpty:!1},Au={createGroup:{name:Eu,type:Eu},dismissGroup:[Object.assign({key:"groupID"},Eu)],joinGroup:{groupID:Eu,applyMessage:{required:!1,rules:["string"],allowEmpty:!0}},quitGroup:[Object.assign({key:"groupID"},Eu)],searchGroupByID:[Object.assign({key:"groupID"},Eu)],getGroupProfile:{groupID:Eu,groupCustomFieldFilter:{required:!1,rules:["array"],allowEmpty:!0}},updateGroupProfile:{groupID:Eu,muteAllMembers:{required:!1,rules:["boolean"],allowEmpty:!1}},changeGroupOwner:{groupID:Eu,newOwnerID:Eu},getGroupOnlineMemberCount:[Object.assign({key:"groupID"},Eu)],handleGroupApplication:{handleAction:Eu},getGroupMemberList:{groupID:Eu},getGroupMemberProfile:{groupID:Eu,userIDList:Mu,memberCustomFieldFilter:{required:!1,rules:["array"],allowEmpty:!0}},addGroupMember:{groupID:Eu,userIDList:Mu},deleteGroupMember:{groupID:Eu,userIDList:Mu},setGroupMemberMuteTime:{groupID:Eu,userID:Eu,muteTime:Object.assign(Object.assign({},Cu),{customValidator:e=>!(e<0)||"muteTime must be a non-negative number."})},setGroupMemberRole:{groupID:Eu,userID:Eu,role:Eu},setGroupMemberNameCard:{groupID:Eu,userID:{required:!1,rules:["string"],allowEmpty:!1},nameCard:Eu},setGroupMemberCustomField:{groupID:Eu,userID:{required:!1,rules:["string"],allowEmpty:!1},memberCustomField:Mu},markGroupMemberList:{groupID:Eu,markType:Object.assign(Object.assign({},Cu),{customValidator:e=>!(e<1e3)||"markType must be greater than or equal to 1000."}),enableMark:{required:!0,rules:["boolean"],allowEmpty:!1},userIDList:Mu},initGroupAttributes:{groupID:Eu,groupAttributes:yu},setGroupAttributes:{groupID:Eu,groupAttributes:yu},deleteGroupAttributes:{groupID:Eu,keyList:Object.assign(Object.assign({},Mu),{allowEmpty:!0})},getGroupAttributes:{groupID:Eu,keyList:Object.assign(Object.assign({},Mu),{allowEmpty:!0})},getGroupCounters:{groupID:Eu,keyList:{required:!1,rules:["array"],allowEmpty:!0}},setGroupCounters:{groupID:Eu,counters:yu},increaseGroupCounter:{groupID:Eu,key:Eu,value:Cu},decreaseGroupCounter:{groupID:Eu,key:Eu,value:Cu}},Tu={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 Ou=new class{constructor(){this._installedSubPlugins=[],this.groupDataHandler=Dc,this.groupAction=Bc,this.groupAttribute=du,this.groupMember=ou,this.name="Group"}install(e,t=[]){this._core=e,ua.init(e),Dc.init(e),Bc.init(e,this),ou.init(e,this),Wc.init(e),ru.init(e),du.init(e),Su.init(e),e.helper.registerValidateConfig({auth:Tu,params:Au}),this._installSubPlugins(t);var{notificationCenter:t,InnerEvent:e}=e;t.subscribeInnerEvent(e.LOGOUT,this._reset,this),t.subscribeInnerEvent(e.DESTROY,this._dispose,this)}getInstalledSubPlugins(){return this._installedSubPlugins}_installSubPlugins(e){var{isArray:t}=this._core["utils"];e&&t(e)&&e.forEach(e=>{var t;this._installedSubPlugins.includes(e.name)||(null!=(t=e.install)&&t.call(e,this._core,this),this._installedSubPlugins.push(e.name))})}_reset(){Dc.reset(),du.reset(),ru.reset()}_dispose(){this._reset();var{notificationCenter:e,InnerEvent:t}=this._core;e.unSubscribeInnerEvent(t.LOGOUT,this._reset,this),e.unSubscribeInnerEvent(t.DESTROY,this._dispose,this)}};let Du=new class{init(e){this.core=e}},Ru="AV_MBR_LIST",Lu="AV_BAN_MBR",Nu={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},bu={GROUP_DISMISSED:5,QUIT_GROUP:8,AVCHATROOM_MEMBER_BANNED:21},Gu=60,wu=2603,Pu=2686,Uu=2688,ku=3122;class Fu{constructor(e){var{core:e,manager:t,groupID:s,getRequestParams:r,onSuccess:n,onFail:o}=e;this._name="Polling",this._core=e,this._manager=t,this._timeoutID=-1,this._isRunning=!1,this._groupID=s,this._getRequestParams=r,this._onSuccess=n,this._onFail=o}start(){this._isRunning=!0,this._request(),console.log(this._name+".start pollingInterval:"+this._manager.getCurrentPollingInterval(this._groupID))}isRunning(){return this._isRunning}_request(){return h(this,void 0,void 0,function*(){try{var e=yield function(n,o){return h(this,void 0,void 0,function*(){var{longPollingKey:e,startSequence:t,startBroadcastSeq:s,simplifiedMessage:r}=n;return o.common.buildAndSendPacket({servcmd:"group_open_long_polling_http_svc.get_msg",data:{Key:e,StartSeq:t,StartBroadcastSeq:s,DownsizeFlag:r,USP:1,HoldTime:90}})})}(this._getRequestParams(this._groupID),this._core),t=(this._onSuccess(this._groupID,e),this._manager.getCurrentPollingInterval(this._groupID));this._runNextPolling(t)}catch(e){this._onFail(this._groupID,e),this._runNextPolling(2e3)}})}_runNextPolling(e){this.isRunning()&&(-1<this._timeoutID&&clearTimeout(this._timeoutID),this._timeoutID=setTimeout(this._request.bind(this),e))}stop(){console.log(this._name+".stop timerID:"+this._timeoutID),-1<this._timeoutID&&(clearTimeout(this._timeoutID),this._timeoutID=-1),this._isRunning=!1}}class $u{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 qu=e=>e===Nu.GROUP_TIPS_HAS_NO_ROAMING||e===Nu.GROUP_TIPS_HAS_ROAMING,xu=e=>e===Nu.GROUP_SYSTEM_MESSAGE;function Vu(g){var e,t,s,r,n,o,i,a=function(){var{E:e,MCT:t,MR:s,MP:r,MTS:n,GId:o,MS:i,CCD:a,F_Account:l,IsSys:c,GInf:u,MsgBody:d}=g,h=p(g,["E","MCT","MR","MP","MTS","GId","MS","CCD","F_Account","IsSys","GInf","MsgBody"]);return Object.assign({Event:e,MsgClientTime:t,MsgRandom:s,MsgPriority:r,MsgTimeStamp:n,ToGroupId:o,MsgSeq:i,CloudCustomData:a,From_Account:l,IsSystemMsg:c,GroupInfo:Bu(u),MsgBody:ju(d)},h)}(),l=a,c=l["Event"];if((qu(c)||xu(c))&&(l.From_Account=l.From_Account||"@TIM#SYSTEM"),c===Nu.BROADCAST_MESSAGE||c===Nu.NORMAL_MESSAGE){var u=l;let e=Du["core"]["OuterConstant"];u.CloudCustomData=u.CloudCustomData||"",u.MsgBody=u.MsgBody.map(t=>{if(t.MsgType===e.MSG_CUSTOM){let{content:e={}}=t;t.content=Object.assign({Data:"",Desc:"",Ext:""},e)}return t})}return qu(c)&&({GroupJoinType:e,MsgOperatorMemberExtraInfo:t={},MsgMemberExtraInfo:s,Operator_Account:r,List_Account:n,OpType:o}=(u=l).MsgBody||{},"number"==typeof e||1!==o&&2!==o||(u.MsgBody.GroupJoinType=2===o?0:1),s||(u.MsgBody.MsgMemberExtraInfo=n.map(e=>({UserId:e}))),1!==o||s||(u.MsgBody.MsgMemberExtraInfo=[{UserId:t.UserId}]),u.MsgBody.MsgOperatorMemberExtraInfo=Object.assign({Operator_Account:r,ImageUrl:"",NickName:""},t)),xu(c)&&({MsgOperatorMemberExtraInfo:e={},Operator_Account:n}=(i=l).MsgBody||{},i.MsgBody.MsgMemberExtraInfo=Object.assign({UserId:n,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 Bu(e){var e=e||{},{GN:t,GT:s,F_Hd:r,F_NN:n,F_Ll:o}=e,e=p(e,["GN","GT","F_Hd","F_NN","F_Ll"]),t=Object.assign({GroupName:t,GroupType:s},e);return r&&(t.From_AccountHeadurl=r),n&&(t.From_AccountNick=n),o&&(t.From_AccountLevel=o),t}function ju(e){let t=e;var s=(t=Array.isArray(e)?t:[e]).map(e=>{var{O_Account:t,Opt:s,L_Account:r,RT:n,UDF:o,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:n,UserDefinedField:o},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 Ku=new class{constructor(){this._name="MessageParser",this._sequenceList=new $u(200),this._messageIDList=new $u(100),this._broadcastMessageIDMap=new Map,this._reportMessageStackedCount=0}init(e,t){this._core=e,this._avChatRoomHandler=t}onMessageReceived(n,e,o=!1){this._sortServerMessageList({groupID:n,serverMessageList:e,isHistoryMessage:o});var i=this._handleMessageList(n,e);if(0!==i.length){if(!o){let{appStore:{conversationStore:e},OuterConstant:{CONV_GROUP:t}}=this._core,s=(e=>{var{common:{getMessagePreviewText:t}}=Du["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+n,{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 n,o,{messageDataHandler:i,messageHelper:a}=this._core["message"],l=this._avChatRoomHandler.isPollingSimplifiedMessage(),c=[],e=r.length;for(let t=0;t<e;t++){let e=r[t];if(l&&(e=Vu(e)),xu(e.Event)&&Object.values(bu).includes(e.MsgBody.ReportType)){this._onGroupDismissed(s);break}null!==this._filterMessageItem(e)&&(this._patchMessageType(e),n=a.parseServerGroupMessage(e),(o=this._createMessage(n)).level=e.GroupInfo.From_AccountLevel,qu(e.Event)&&this._avChatRoomHandler.isGroupAttributesUpdated(n)?this._avChatRoomHandler.handleGroupAttributesUpdated(n):null===this._filterDuplicateMessage(o)||i.isMessageSentByCurrentInstance(o)||(1===n.isModified&&(o.isModified=!0),qu(e.Event)&&this._updateLocalOnlineMemberCountFromTips(e),c.push(o)))}return c}_patchMessageType(e){var t=this._core["OuterConstant"];qu(e.Event)&&(e.MsgBody.MsgType=t.MSG_GRP_TIP),xu(e.Event)&&(e.MsgBody.MsgType=t.MSG_GRP_SYS_NOTICE)}_filterMessageItem(e){var t=e["Event"];return Object.values(Nu).includes(t)?t===Nu.MESSAGE_REVOKED?(this._handleMessageRevoked(e),null):t===Nu.LIVE_CUSTOM_DATA?(this._onLiveCustomData(e),null):t===Nu.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===Nu.GROUP_SYSTEM_MESSAGE&&(r=s.CONV_SYSTEM);s=!!e.isSystemMessage,t=t.createMessage(Object.assign(Object.assign({},e),{conversationType:r,isSystemMessage:s,flow:"in"}));return t.setElement(e.elements),t}_filterDuplicateMessage(e){var t=this._core["common"];if(!t.isUnlimitedAVChatRoom()){if(this._sequenceList.has(e.sequence))return null;this._sequenceList.set(e.sequence)}t=this._messageIDList.has(e.ID);return t?(console.warn(`${this._name}_filterDuplicateMessageItem ID:${e.ID} has:`+t),null):(this._messageIDList.set(e.ID),e)}_handleMessageRevoked(e){let{OuterConstant:n,OuterEvent:{MESSAGE_REVOKED:t}}=this._core,{ToGroupId:o,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:""+n.CONV_GROUP+o,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:n}=e,n=(null==n?void 0:n.MsgContent)||"";this._emitEvent({name:t,data:n}),console.log(this._name+`._onLiveCustomData groupID:${e} sequence:${s} time:${r} data:`+n)}_onGroupDismissed(e){this._avChatRoomHandler.reset(e)}_checkMessageStacked(e){var t=e["length"];if(100<=t&&this._reportMessageStackedCount<5){let e=this._avChatRoomHandler.getJoinedGroups();this._core.ssoLog.createSSOLogData({method:"MessageStacked"}).setLogInfo({message:`count:${t} groupID:`+e.join(",")}).end(),this._reportMessageStackedCount+=1}}_emitEvent(e){this._core.notificationCenter.emitOuterEvent(e.name,e)}onBroadcastMessageReceived(s){var{message:{messageHelper:r},OuterEvent:{MESSAGE_RECEIVED:e}}=this._core,n=this._avChatRoomHandler.isPollingSimplifiedMessage(),o=[],i=s.length;for(let t=0;t<i;t++){let e=s[t];n&&(e=Vu(e));var a=r.parseServerGroupMessage(e);Object.values(Nu).includes(e.Event)?((a=this._createMessage(a)).isBroadcastMessage=!0,this._broadcastMessageIDMap.has(a.ID)||(o.push(a),this._broadcastMessageIDMap.set(a.ID,1))):console.warn(this._name+".onBroadcastMessageReceived unknown event:"+e.Event)}0<o.length&&this._emitEvent({name:e,data:o})}_updateLocalOnlineMemberCountFromTips(t){var s=this._core["utils"]["isEmpty"],{ToGroupId:t,MsgBody:{OnlineMemberInfo:r}}=t;if(!s(r)){var{OnlineMemberNum:r=0,ExpireTime:n=Gu}=r,o=Date.now();let e=this._avChatRoomHandler.getLocalOnlineMemberCount(t);s(e)?e={lastReqTime:0,lastSyncTime:0,latestUpdateTime:o,memberCount:r,expireTime:n}:(e.latestUpdateTime=o,e.memberCount=r),this._avChatRoomHandler.updateLocalOnlineMemberCount(t,e)}}reset(){this._reportMessageStackedCount=0,this._sequenceList.clear(),this._messageIDList.clear(),this._broadcastMessageIDMap.clear()}};let Wu=e=>{var{store:t}=Du["core"];return(t.get("cloudConfig")||{})[e]},Hu=e=>{var{utils:{isUndefined:t}}=Du["core"];return!t(e)},Yu=()=>{var e=Wu("polling_interval");return Hu(e)?parseInt(e,10):300},zu=()=>{var e=Wu("polling_simplified_msg");return Hu(e)?parseInt(e,10):0};var Ju=new class{constructor(){this._name="AVChatRoomHandler",this._joinedGroupMap=new Map,this._pollingRequestInfoMap=new Map,this._pollingInstanceMap=new Map,this._onlineMemberCountMap=new Map,this._pollingIntervalMap=new Map,this._pollingNoMessageCountMap=new Map,this._membersReqInfoMap=new Map,this._startBroadcastSequence=1}init(e,t){this._core=e,this._parentPlugin=t,Ku.init(e,this),console.log("AVChatRoomHandler.init")}onAVChatRoomSystemNotification(e){var t=this._core["OuterConstant"]["GRP_AVCHATROOM"],{GroupTips:s=[]}=e;for(let e=0;e<s.length;e++){var{MsgBody:r,GroupInfo:{GroupId:n,GroupType:o}}=s[e],r=Object.values(bu).includes(r.ReportType);o===t&&r&&this.reset(n)}}getCurrentPollingInterval(e){return this._pollingIntervalMap.get(e)||Yu()}isPollingSimplifiedMessage(){return 0!==zu()}isGroupAttributesUpdated(e){return!!this._parentPlugin.groupAttribute.isGroupAttributesUpdated(e)&&(this._parentPlugin.groupAttribute.handleGroupAttributesUpdated(e),!0)}updateLocalOnlineMemberCount(e,t){this._onlineMemberCountMap.set(e,t)}getLocalOnlineMemberCount(e){return this._onlineMemberCountMap.get(e)||{}}hasPollingInstance(e){return this._pollingInstanceMap.has(e)}getJoinedLiveList(){let{GRP_LIVE:t}=this._core["OuterConstant"],e=[];return e=0<this._joinedGroupMap.size?[...this._joinedGroupMap.values()].filter(e=>e.type===t):e}handleJoinGroupResult(l){return h(this,void 0,void 0,function*(){var{utils:{isUndefined:e},OuterConstant:{CONV_GROUP:t},apiMap:{getConversationProfile:s},OuterConstant:r}=this._core,{longPollingKey:n,group:o,historyMessageList:i=[]}=l,a=o["groupID"];return yield this._preCheck(o),this._joinedGroupMap.set(a,o),this._parentPlugin.groupDataHandler.updateLocalGroup([o]),this._parentPlugin.groupDataHandler.emitGroupListUpdate(),s(""+t+a),0<i.length&&Ku.onMessageReceived(a,i,!0),e(n)?{status:r.JOIN_STATUS_SUCCESS,group:o}:this.startMessageLongPolling(l)})}_preCheck(n){return h(this,void 0,void 0,function*(){var{common:t,OuterConstant:e,helper:s,apiMap:{quitGroup:r}}=this._core;if(t.isUnlimitedAVChatRoom()){if(this._pollingInstanceMap.size>(t=Wu("polling_count_limit"),Hu(t)&&0<t?parseInt(t,10):20))throw new s.ChatError({code:Uu,message:"the count of longPolling exceeds the max limit"})}else if(0!==this._joinedAVChatRoomCount()&&n.type!==e.GRP_LIVE){var[t,s]=this._joinedGroupMap.entries().next().value;if(s.selfInfo.role===e.GRP_MBR_ROLE_OWNER)this._parentPlugin.groupDataHandler.deleteLocalGroup(t);else try{yield r(t)}catch(e){console.log(this._name+`._preCheck quitGroup failed, groupID:${t} info:`,e)}this.reset(t)}})}startMessageLongPolling(e){var t=this._core["OuterConstant"],{longPollingKey:e,startSequence:s=1,group:r}=e,n=r["groupID"];return this._pollingRequestInfoMap.set(n,{longPollingKey:e,startSequence:s}),this._pollingIntervalMap.set(n,Yu()),this._startPolling(n),this._reportLongPollingCount(),{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 Fu({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:zu()}:{longPollingKey:t,startSequence:s,simplifiedMessage:zu()}}_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(t,e){var{Key:e,NextSeq:s,NextBroadcastSeq:r,RspMsgList:n=[],RspBroadcastMsgList:o=[]}=e;if(e&&s&&this._pollingRequestInfoMap.set(t,{longPollingKey:e,startSequence:s}),r&&r>this._startBroadcastSequence&&(this._startBroadcastSequence=r),0<n.length)0!==this._getPollingNoMessageCount(t)&&(this._updatePollingNoMessageCount(t,0),this._pollingIntervalMap.set(t,Yu())),Ku.onMessageReceived(t,n);else{e=this._getPollingNoMessageCount(t);if(this._updatePollingNoMessageCount(t,e+=1),e===(s=Wu("polling_no_msg_count"),Hu(s)?parseInt(s,10):20)){let e=Yu()+(r=Wu("polling_interval_plus"),Hu(r)?parseInt(r,10):2e3);this._pollingIntervalMap.set(t,e)}}0<o.length&&Ku.onBroadcastMessageReceived(o)}_handleFailure(e,t){console.warn(this._name+`._handleFailure groupID:${e} error:`,t)}_joinedAVChatRoomCount(){let t=this._core["OuterConstant"],e=[];return(e=0<this._joinedGroupMap.size?this.getJoinedGroups().filter(e=>e.type===t.GRP_AVCHATROOM):e).length}_hasJoinedAVChatRoom(e){return this._joinedGroupMap.has(e)}getJoinedGroups(){return[...this._joinedGroupMap.values()]}updateLocalLiveGroup(e,t){this._joinedGroupMap.set(e,t),this._parentPlugin.groupDataHandler.updateLocalGroup([t])}handleLiveHistoryMessages(e,t){Ku.onMessageReceived(e,t,!0)}isOverFrequencyLimit(e){var t,s,r,n;return!this._membersReqInfoMap.has(e)||({startTime:t,requestCount:s}=this._membersReqInfoMap.get(e),{interval:r,count:n}=(()=>{var e=Wu("av_members_freq_limit");if(Hu(e)){var{interval:e,count:t}=JSON.parse(e);if(0<t&&0<e)return{interval:e,count:t}}return{interval:30,count:4}})(),Date.now()-t>1e3*r)?(this._membersReqInfoMap.set(e,{startTime:Date.now(),requestCount:1}),!1):(this._membersReqInfoMap.set(e,{startTime:t,requestCount:s+=1}),n<s)}_stopPolling(e){var t,s;if(e)console.log(this._name+"._stopPolling groupID:"+e),{appStore:{conversationStore:s},OuterConstant:{CONV_GROUP:t}}=this._core,s.deleteConversation(""+t+e),null!=(s=this._pollingInstanceMap.get(e))&&s.stop(),this._parentPlugin.groupDataHandler.deleteLocalGroup(e),this._pollingInstanceMap.delete(e),this._pollingRequestInfoMap.delete(e),this._joinedGroupMap.delete(e),this._onlineMemberCountMap.delete(e),this._pollingIntervalMap.delete(e),this._pollingNoMessageCountMap.delete(e),this._membersReqInfoMap.delete(e);else{console.log(this._name+"._stopPolling all.");for(let e of this._pollingInstanceMap.values())null!=e&&e.stop();this._pollingInstanceMap.clear(),this._pollingRequestInfoMap.clear(),this._joinedGroupMap.clear(),this._onlineMemberCountMap.clear(),this._pollingIntervalMap.clear(),this._pollingNoMessageCountMap.clear(),this._membersReqInfoMap.clear()}}_updatePollingNoMessageCount(e,t){this._pollingNoMessageCountMap.set(e,t)}_getPollingNoMessageCount(e){return this._pollingNoMessageCountMap.get(e)||0}_reportLongPollingCount(){var i=this._joinedGroupMap.size;if(1<i){let{common:e,OuterConstant:s,ssoLog:t}=this._core,r=e.isUnlimitedAVChatRoom()?1:0,n=[],o=[];this._joinedGroupMap.values().forEach(({groupID:e,type:t})=>{(t===s.GRP_LIVE?o:n).push(e)}),t.createSSOLogData({method:"longPollingCount"}).setLogInfo({message:i,moreMessage:`av:${n.join(",")} live:`+o.join(","),eventType:29,code:r}).end()}}reset(e){this._stopPolling(e),this._startBroadcastSequence=1,Ku.reset()}},Qu=new class{init(e,t){this._core=e,this._parentPlugin=t;e=e.helper;e.registerApi({apiName:"joinGroup",context:this,matcher:()=>0<t.getInstalledSubPlugins().length})}joinGroup(n){return h(this,void 0,void 0,function*(){var e=this._core["OuterConstant"],t=yield this._parentPlugin.groupAction.joinGroup(n),{status:s,group:{type:r}}=t["data"];return r!==e.GRP_AVCHATROOM||s===e.JOIN_STATUS_ALREADY_IN_GROUP?t:Ju.handleJoinGroupResult(t.data)})}},Xu=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&&Ju.reset(r),t})}},Zu=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&&Ju.reset(r),t})}},el=new class{constructor(){this._name="GetAVChatRoomMemberList"}init(e,t){this._core=e,this._parentPlugin=t;e=e.helper;e.registerApi({apiName:"getGroupMemberList",context:this,matcher:()=>0<t.getInstalledSubPlugins().length})}getGroupMemberList(n){return h(this,void 0,void 0,function*(){var{appStore:{groupStore:e},helper:t,OuterConstant:s}=this._core,r=n["groupID"],e=e.getGroup(r);if((null==e?void 0:e.type)===s.GRP_AVCHATROOM&&t.checkBusinessCapabilityBits(Ru)){if(Ju.isOverFrequencyLimit(r))throw{code:2996,message:"Over frequency limit: get_members-"+r};return this._getGroupMemberList(n)}return this._parentPlugin.groupMember.getGroupMemberList(n)})}_getGroupMemberList(o){return h(this,void 0,void 0,function*(){let n="_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}})})}(o,this._core),{MemberList:t=[],NextTimestamp:s=0}=e||{},r=this._handleMemberList(t);return console.log(`${this._name}.${n} ok, groupID:${o.groupID} count:${r.length} nextOffset:`+s),{code:0,data:{memberList:r,offset:s}}}catch(e){var s=new t.ChatError({functionName:n,code:null==e?void 0:e.errorCode,message:null==e?void 0:e.errorInfo});throw console.error(this._name+`.${n} fail:`,s),s}})}_handleMemberList(e){return e.map(e=>{var{Member_Account:e,NickName:t="",Avatar:s="",Remark:r="",JoinTime:n=0,Marks:o=[]}=e;return{userID:e,nick:t,avatar:s,remark:r,joinTime:n,marks:o,isOnline:!0}})}},tl=new class{constructor(){this._name="GetAVChatRoomOnlineMemberCount"}init(e,t){this._core=e,this._parentPlugin=t;e=e.helper;e.registerApi({apiName:"getGroupOnlineMemberCount",context:this,matcher:()=>0<t.getInstalledSubPlugins().length})}getGroupOnlineMemberCount(s){return 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=Ju.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=Ju.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(o){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}})})}(o,this._core),{OnlineMemberNum:t=0,ExpireTime:s=Gu}=e||{},r=Date.now(),n={lastSyncTime:r,latestUpdateTime:r,lastReqTime:r,memberCount:t,expireTime:s};return Ju.updateLocalOnlineMemberCount(o,n),{memberCount:t}}catch(e){var s=new this._core.helper.ChatError({functionName:t,code:null==e?void 0:e.errorCode,message:null==e?void 0:e.errorInfo});throw console.error(`${this._name}.${t} fail:`,s),s}})}},sl=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:n}=this._core,o=i["groupID"],t=t.getGroup(o);if(s(t))throw new r.ChatError({functionName:e,code:wu});if(t.type!==n.GRP_AVCHATROOM)return this._parentPlugin.groupMember.deleteGroupMember(i);if(r.checkBusinessCapabilityBits(Lu))return this._deleteGroupMember(i);throw new r.ChatError({functionName:e,code:ku})})}_deleteGroupMember(i){return h(this,void 0,void 0,function*(){let s="_deleteGroupMember",{appStore:{groupStore:e},helper:r}=this._core,{groupID:t,duration:n=0,userIDList:o}=i;if(0===n)throw new r.ChatError({functionName:s,code:Pu});try{return yield function(n,o){return h(this,void 0,void 0,function*(){var{groupID:e,userIDList:t,duration:s,reason:r}=n;return o.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:o}}}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}})}},ol=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 n="markGroupMemberList",{groupID:o,markType:i,enableMark:a,userIDList:l=[]}=e,c=this._generateRequestData(e);try{let e=yield function(r,n){return h(this,void 0,void 0,function*(){var{groupID:e,operationType:t,memberList:s}=r;return n.common.buildAndSendPacket({servcmd:"group_open_avchatroom_http_svc.modify_user_info",data:{GroupId:e,CommandType:t,MemberList:s}})})}(c,this._core),{MemberList:t=[]}=e||{},{successUserIDList:s,failureUserIDList:r}=this._handleResult(t,l);return console.log(`${this._name}.${n} ok, groupID:${o} 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:n,code:null==e?void 0:e.errorCode,message:null==e?void 0:e.errorInfo});throw console.error(this._name+`.${n} fail:`,t),t}})}_generateRequestData(e){let{groupID:t,markType:s,enableMark:r,userIDList:n=[]}=e,o=!0===r?1:2,i=[...n];return 500<i.length&&console.warn(this._name+"._generateRequestData, the length of userIDList cannot exceed 500"),{groupID:t,operationType:o,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}}},nl=new class{init(e,t){console.log("AVChatRoomAction.init"),Qu.init(e,t),Xu.init(e,t),Zu.init(e,t),el.init(e,t),tl.init(e,t),sl.init(e,t),ol.init(e)}},il=new class{constructor(){this._name="LiveHandler"}init(e){e=(this._core=e).helper;e.registerExperimentalAPI("startMessageLongPolling",this),e.registerExperimentalAPI("stopMessageLongPolling",this),console.log("LiveHandler.init")}startMessageLongPolling(e){var{common:t,utils:{isEmpty:s},OuterConstant:r}=this._core,{groupID:e,longPollingKey:n,longPollingSequence:o=1}=e;if(s(n))return console.warn(this._name+".startMessageLongPolling longPollingKey is empty."),Promise.resolve({});Ju.hasPollingInstance(e)&&this.stopMessageLongPolling({groupID:e});s=Ju.getJoinedLiveList(),t=t.isUnlimitedAVChatRoom(),!t&&0<s.length&&this.stopMessageLongPolling({groupID:s[0].groupID}),console.log(this._name+`.startMessageLongPolling isUnlimited:${t} groupID:${e} longPollingKey:${n} longPollingSequence:`+o),s={groupID:e,type:r.GRP_LIVE};return Ju.updateLocalLiveGroup(e,s),this._getLiveHistoryMessages({groupID:e,longPollingKey:n,startSequence:o}),Ju.startMessageLongPolling({group:s,longPollingKey:n,startSequence:o})}stopMessageLongPolling(e){e=e.groupID;return Ju.reset(e),console.log(this._name+".stopMessageLongPolling ok, groupID:"+e),Promise.resolve({groupID:e})}_getLiveHistoryMessages(r){return h(this,void 0,void 0,function*(){var t=r["groupID"];try{var e=yield function(r,n){return h(this,void 0,void 0,function*(){var{groupID:e,longPollingKey:t,startSequence:s}=r;return n.common.buildAndSendPacket({servcmd:"group_open_http_svc.get_huge_group_msg",data:{GroupId:e,LongPollingKey:t,PullPreSeq:s}})})}(r,this._core),{RspMsgList:s=[]}=e||{};console.log(this._name+`._getLiveHistoryMessages ok, groupID:${t} count:`+s.length),0<s.length&&Ju.handleLiveHistoryMessages(t,s)}catch(e){console.log(this._name+`._getLiveHistoryMessages failed, groupID:${t} info:`,e)}})}},rl=new class{constructor(){this.name="AVChatRoom"}install(e,t){this._core=e,Du.init(e),Ju.init(e,t),nl.init(e,t),il.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){Ju.onAVChatRoomSystemNotification(e)}_reset(){Ju.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 al="friend",cl=100,ul=2700,ll=2710,dl=2711,pl=2716,hl=2742,gl=30539,_l="Tag_SNS_IM_",ml={GROUP:_l+"Group",REMARK:_l+"Remark",ADDSOURCE:_l+"AddSource",ADDWORDING:_l+"Wording",ADDTIME:_l+"AddTime"},vl="Update_Type_Add",fl="Update_Type_Delete",Il="add",Sl="remove",El="rename",Cl=e=>void 0===e;function Ml(e,t){return h(this,void 0,void 0,function*(){return Al(yield t.common.buildAndSendPacket({servcmd:"sns.friend_update",data:e}),"ResultItem",e=>({to:e.To_Account,resultCode:e.ResultCode,resultInfo:e.ResultInfo}))})}function yl(e,t){return h(this,void 0,void 0,function*(){return Al(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 Al(e,t="ResultItem",s=e=>({userID:e.To_Account,resultCode:e.ResultCode,resultInfo:e.ResultInfo})){var{[t]:e=[],ActionStatus:t,ErrorCode:r,ErrorInfo:n,ErrorDisplay:o}=e;return{resultList:e.map(s),actionStatus:t,errorCode:r,errorInfo:n,errorDisplay:o}}let Tl={[ml.REMARK]:(e,t)=>{e.remark=t},[ml.GROUP]:(e,t)=>{e.groupList=t?JSON.parse(JSON.stringify(t)):[]},[ml.ADDSOURCE]:(e,t)=>{e.source=t},[ml.ADDWORDING]:(e,t)=>{e.wording=t},[ml.ADDTIME]:(e,t)=>{e.addTime=t}},Ol=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}),Tl[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=Tl[t];null!=e&&e(this,s)})}};var Dl=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(al+" getFriendListFromCache, data ",e),{code:0,data:e}})}syncFriendListFromServer(){return h(this,void 0,void 0,function*(){var e;try{console.log(al+" syncFriendListFromServer");var{friendList:t,nextStartIndex:s,standardSequence:r,customSequence:n,completeFlag:o}=yield function(u,d){return h(this,void 0,void 0,function*(){var{UserDataItem:e=[],StandardSequence:t,CustomSequence:s,FriendNum:r,CompleteFlag:n,NextStartIndex:o,ActionStatus:i,ErrorCode:a,ErrorInfo:l,ErrorDisplay:c}=e=yield d.common.buildAndSendPacket({servcmd:"sns.friend_get",data:u});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:n,nextStartIndex:o,actionStatus:i,errorCode:a,errorInfo:l,errorDisplay:c}})}({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=n,this._processFriendList(t),0===o?yield this.syncFriendListFromServer():(this._emitFriendListUpdated(),this._fetchFriendProfile()),console.log(al+" syncFriendListFromServer ok")}catch(e){throw console.error(al+" syncFriendListFromServer error:",e),e}})}getFriendProfile(l){return h(this,void 0,void 0,function*(){var t;try{console.log(al+" getFriendProfile params:",l);let e=l["userIDList"];e.length>cl&&(e=e.slice(0,cl));var s,r,n,{friendUserIdList:o,unFriendUserIdList:i}=this.partitionByIsFriend(e),a=this._createNonFriendErrorList(i);return 0===o.length?{code:0,data:{friendList:[],failureUserIDList:a}}:(s=(yield function(o,i){return h(this,void 0,void 0,function*(){var{InfoItem:e=[],ActionStatus:t,ErrorCode:s,ErrorInfo:r,ErrorDisplay:n}=e=yield i.common.buildAndSendPacket({servcmd:"sns.friend_get_specified",data:o});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:n}})}({From_Account:null==(t=this._core.store.get("login"))?void 0:t.userId,To_Account:o},this._core))||{},{successProfiles:r,failedProfiles:n}=this._processFriendProfileResponse(s),{code:0,data:{friendList:r,failureUserIDList:[...n,...a]}})}catch(e){throw console.error(al+" getFriendProfile error:",e),e}})}addFriend(g){return h(this,void 0,void 0,function*(){var e;try{console.log(al+" addFriend options:",g);var{helper:t,store:s}=this._core,{to:r,source:n,type:o,wording:i,remark:a,groupName:l}=g,c=yield function(e,t){return h(this,void 0,void 0,function*(){return Al(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:n,AddWording:i,GroupName:l,Remark:a}],AddType:o},this._core),{resultList:u=[]}=c,{userID:d,resultCode:p}=u[0];if(0===p)return console.log(al+" addFriend ok"),{code:0,data:{userID:d}};if(p===gl)return console.log(al+" 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(al+" addFriend error:",e),e}})}deleteFriend(u){return h(this,void 0,void 0,function*(){var s;try{console.log(al+" deleteFriend options:",u);var r=this._core["store"];let{userIDList:e,type:t}=u;var n,o,i,a=null==(s=r.get("login"))?void 0:s.userId,{friendUserIdList:l,unFriendUserIdList:c}=(1e3<e.length&&(console.warn(al+" deleteFriend the length of userIDList cannot exceed:",1e3),e=e.slice(0,cl)),this.partitionByIsFriend(e));return 0===l.length?{code:0,data:{friendList:[],failureUserIDList:this._createNonFriendErrorList(c)}}:(n=yield function(e,t){return h(this,void 0,void 0,function*(){return Al(yield t.common.buildAndSendPacket({servcmd:"sns.friend_delete",data:e}))})}({From_Account:a,To_Account:l,DeleteType:t},this._core),{successUserIDList:o,failureUserIDList:i}=this._processOperationResult({resultList:n.resultList,includeRelation:!1}),console.log(al+" deleteFriend ok"),{code:0,data:{successUserIDList:o,failureUserIDList:i}})}catch(e){throw console.error(al+" deleteFriend error:",e),e}})}updateFriend(p){return h(this,void 0,void 0,function*(){var e;try{console.log(al+" updateFriend options:",p);var{userID:t,remark:s,friendCustomField:r}=p,{helper:n,store:o,appStore:{userStore:i}}=this._core,a=null==(e=o.get("login"))?void 0:e.userId;if(!i.getFriendMap().has(t))throw new n.ChatError({functionName:"updateFriend",code:ul});var l=(yield Ml({From_Account:a,UpdateItem:[{To_Account:t,SnsItem:this._buildSnsItemList(s,r)}]},this._core))["resultList"],{to:c,resultCode:u,resultInfo:d}=l[0];if(Cl(u)||0===u)return{code:0,data:this._updateLocalFriend({userID:c,remark:s,friendCustomField:r})};throw new n.ChatError({functionName:"updateFriend",code:u,message:d})}catch(e){throw console.error(al+" updateFriend error:",e),e}})}checkFriend(l){return h(this,void 0,void 0,function*(){var e;try{console.log(al+" checkFriend options:",l);var{userIDList:t,type:s}=l,{OuterConstant:r,store:n}=this._core,o=yield yl({From_Account:null==(e=n.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:o.resultList,includeRelation:!0});return{code:0,data:{successUserIDList:i,failureUserIDList:a}}}catch(e){throw console.error(al+" 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(al+" updateFriendList data:",r);let s=this._core.appStore["userStore"],{addedFriendList:e=[],removedFriendList:t=[]}=r;0<e.length&&(e.forEach(e=>{var t=new Ol({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(al+" updateFriendInfo data: ",e);let{appStore:{userStore:t,conversationStore:n},utils:{isEmpty:s}}=this._core,{userID:o,tagValueList:i}=e[0]||{},a=t.getFriend(o);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=n.getConversation("C2C"+o))?void 0:s.remark;e===ml.REMARK&&t!==s&&n.updateConversation("C2C"+o,{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 Ol({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(al+" _fetchFriendProfile");let{appStore:{userStore:s},user:{userProfile:t}}=this._core,r=[...s.getFriendMap().keys()],n=Math.ceil(r.length/100);for(let e=0;e<n;e++){var o=100*e,i=Math.min(100+o,r.length),a=r.slice(o,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(al+" _fetchFriendProfile error:",e),e}})}_emitFriendListUpdated(){var{notificationCenter:e,OuterEvent:t,appStore:{userStore:s}}=this._core,s=Array.from(s.getFriendMap().values());console.log(al+" _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 n=!1;return e.forEach(({key:t,value:e})=>{var s=r.find(e=>e.key===t);s?s.value!==e&&(s.value=e,n=!0):(r.push({key:t,value:e}),n=!0)}),n}_updateLocalFriend(e){var t=this._core.appStore["userStore"],{userID:e,remark:s,friendCustomField:r}=e,t=t.getFriend(e);if(t)return Cl(s)||(t.remark=s),Array.isArray(r)&&0<r.length&&this._updateCustomField(t.friendCustomField,r),this._emitFriendListUpdated(),t}_processOperationResult(e){let{resultList:t,includeRelation:n=!1}=e,s=this._core.utils["isEmpty"],o=[],i=[];return Array.isArray(t)&&!s(t)&&t.forEach(e=>{var{userID:t,relation:s,resultCode:e,resultInfo:r}=e;if(Cl(e)||0===e){let e={userID:t};n&&(e.code=0,e.relation=s),o.push(e)}else i.push({userID:t,code:e,message:r})}),{successUserIDList:o,failureUserIDList:i}}_createNonFriendErrorList(e){return e.map(e=>({userID:e,code:ul,message:"The specified userID is not my friend"}))}_buildSnsItemList(e,t){let s=[];return Cl(e)||s.push({Tag:ml.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,n=this._core.appStore["userStore"],o=[],i=[];return t.forEach(e=>{var{userID:t,resultCode:e,resultInfo:s,profileItem:r}=e;if(0===e){let e=new Ol({userID:t,tagValueList:r,core:this._core});o.push(e),n.getFriendMap().set(t,e)}else i.push({userID:t,code:e,message:s})}),console.log(al+" _processFriendProfileResponse successProfiles:",o),{successProfiles:o,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(`${al} partitionByIsFriend, friendUserIdList: ${s}, unFriendUserIdList: `+r),{friendUserIdList:s,unFriendUserIdList:r}}isMyFriend(e){var t=this._core.appStore["userStore"];return t.getFriendMap().has(e)}},Rl=new class{init(e){this.core=e}};function Ll(s){return h(this,void 0,void 0,function*(){var{store:e,common:t}=Rl.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 Gl(yield t.buildAndSendPacket({servcmd:"sns.friend_response",data:e}))})}function Nl(s){return h(this,void 0,void 0,function*(){var{store:e,common:t}=Rl.core,e={From_Account:null==(e=e.get("login"))?void 0:e.userId,ResponseFriendItem:[{To_Account:s.userID,ResponseAction:"Response_Action_Reject"}]};return Gl(yield t.buildAndSendPacket({servcmd:"sns.friend_response",data:e}))})}function bl(s){return h(this,void 0,void 0,function*(){var{store:e,common:t}=Rl.core,e={From_Account:null==(e=e.get("login"))?void 0:e.userId,To_Account:[s.userID],PendencyType:s.type};return Gl(yield t.buildAndSendPacket({servcmd:"sns.pendency_delete",data:e}))})}function Gl(e){var{ResultItem:e=[],ActionStatus:t,ErrorCode:s,ErrorInfo:r,ErrorDisplay:n}=e;return{resultList:e.map(e=>({userID:e.To_Account,resultCode:e.ResultCode,resultInfo:e.ResultInfo})),actionStatus:t,errorCode:s,errorInfo:r,errorDisplay:n}}var wl=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(al+" 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(al+" "+t);try{let e=yield function(l){return h(this,void 0,void 0,function*(){var{store:e,OuterConstant:t,common:s}=Rl.core,e={From_Account:null==(e=e.get("login"))?void 0:e.userId,PendencyType:t.SNS_APPLICATION_TYPE_BOTH,MaxLimited:cl,StartTime:l.startTime,LastSequence:l.currentSequence},{PendencyItem:t=[],StartTime:s,UnreadPendencyCount:e,CurrentSequence:r,ActionStatus:n,ErrorCode:o,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:n,errorCode:o,errorInfo:i,errorDisplay:a}})}({startTime:this._startTime,currentSequence:this._currentSequence}),{resultList:t,unreadCount:s,startTime:r,currentSequence:n}=e;this._startTime=r,this._currentSequence=n,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(`${al} ${t} error:`,s),s}})}acceptFriendApplication(e){return h(this,void 0,void 0,function*(){return this._operationApplication({functionName:"acceptFriendApplication",options:e,protocolFunction:Ll})})}refuseFriendApplication(e){return h(this,void 0,void 0,function*(){return this._operationApplication({functionName:"refuseFriendApplication",options:e,protocolFunction:Nl})})}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:bl})})}_checkApplicationExists(e,t,s){if(!this._friendApplicationMap.has(e+"_"+t))throw new this._core.helper.ChatError({functionName:s,code:pl})}_operationApplication(e){return h(this,void 0,void 0,function*(){let{functionName:n,options:o,protocolFunction:i}=e;console.log(al+` ${n} options:`,o);try{let e=yield i(o),{resultList:t=[]}=e,{resultCode:s,resultInfo:r}=t[0];if(0===s)return console.log(al+` ${n} ok`),{code:0,data:{}};throw{errorCode:s,errorInfo:r}}catch(e){let t=new this._core.helper.ChatError({functionName:n,code:null==e?void 0:e.errorCode,message:null==e?void 0:e.errorInfo});throw console.error(al+` ${n} error:`,t),t}})}setFriendApplicationRead(){return h(this,void 0,void 0,function*(){var t="setFriendApplicationRead";console.log(al+" "+t);try{return yield function(){return h(this,void 0,void 0,function*(){var{store:e,common:t}=Rl.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(al+` ${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(al+` ${t} error:`,s),s}})}updateFriendApplicationList(e){var{from:t,addedApplicationList:s=[],removedApplicationList:r=[]}=e,e=(console.log(al+" 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:n}=this._core,o=t===(null==(s=r.get("login"))?void 0:s.userId)?n.SNS_APPLICATION_SENT_BY_ME:n.SNS_APPLICATION_SENT_TO_ME;e.forEach(e=>{var t=e.userID+"_"+o;o!==n.SNS_APPLICATION_SENT_TO_ME||this._friendApplicationMap.has(t)||(this._unreadCount+=1),this._friendApplicationMap.set(t,this._createFriendApplication(Object.assign(Object.assign({},e),{type:o})))}),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(al+" _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 Pl(){return h(this,void 0,void 0,function*(){var e=Rl.core["common"],t={From_Account:e.getCurrentUserID(),LastSequence:0,NeedFriend:"Need_Friend_Type_Yes"};return Vl(yield e.buildAndSendPacket({servcmd:"sns.group_get",data:t}),e=>({name:e.GroupName,userIDList:e.To_Account||[],count:e.FriendNumber}))})}function Ul(r){return h(this,void 0,void 0,function*(){var{name:e,userIDList:t}=r,s=Rl.core["common"],e={From_Account:s.getCurrentUserID(),GroupName:[e],To_Account:t};return Vl(yield s.buildAndSendPacket({servcmd:"sns.group_add",data:e}),e=>({userID:e.To_Account,resultCode:e.ResultCode,resultInfo:e.ResultInfo}))})}function kl(s){return h(this,void 0,void 0,function*(){var e=Rl.core["common"],t={From_Account:e.getCurrentUserID(),GroupName:[s.name]};return Vl(yield e.buildAndSendPacket({servcmd:"sns.group_delete",data:t}))})}function Fl(r){return h(this,void 0,void 0,function*(){var e=Rl.core["common"],{name:t,userIDList:s}=r,s=xl(s,vl),t={From_Account:e.getCurrentUserID(),GroupOldName:t,UpdateGroupItem:s};return Vl(yield e.buildAndSendPacket({servcmd:"sns.group_update",data:t}),e=>({userID:e.To_Account,updateType:e.UpdateType,resultCode:e.ResultCode,resultInfo:e.ResultInfo}))})}function $l(r){return h(this,void 0,void 0,function*(){var e=Rl.core["common"],{name:t,userIDList:s}=r,s=xl(s,fl),t={From_Account:e.getCurrentUserID(),GroupOldName:t,UpdateGroupItem:s};return Vl(yield e.buildAndSendPacket({servcmd:"sns.group_update",data:t}),e=>({userID:e.To_Account,updateType:e.UpdateType,resultCode:e.ResultCode,resultInfo:e.ResultInfo}))})}function ql(r){return h(this,void 0,void 0,function*(){var e=Rl.core["common"],{oldName:t,newName:s}=r,t={From_Account:e.getCurrentUserID(),GroupOldName:t,GroupNewName:s};return Vl(yield e.buildAndSendPacket({servcmd:"sns.group_update",data:t}))})}function xl(e,t){return e.filter(e=>Dl.isMyFriend(e)).map(e=>({To_Account:e,UpdateType:t}))}function Vl(e,t){var{CurrentSequence:e,ActionStatus:s,ErrorCode:r,ErrorInfo:n,ErrorDisplay:o,ResultItem:i=[]}=e,e={currentSequence:e,actionStatus:s,errorCode:r,errorInfo:n,errorDisplay:o};return t&&0<i.length?Object.assign(Object.assign({},e),{resultList:i.map(t)}):e}class Bl{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 jl=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(al+" getFriendGroupListFromCache, data: ",e),{code:0,data:e}})}syncFriendGroupListFromServer(){return h(this,void 0,void 0,function*(){var t="syncFriendGroupListFromServer";console.log(al+" "+t);try{var e=yield Pl(),{resultList:s=[]}=e;this._core.helper.isEmpty(s)&&console.log(al+` ${t} ok. count: 0`),s.forEach(e=>{var t=new Bl(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(al+` ${t} params:`,i);try{var e=i["name"],s=(this._checkGroupExist(t,e),yield Ul(i)),{successUserIDList:r,failureUserIDList:n}=this._parseCreateGroupResponse(s),o=new Bl({name:e,userIDList:r});return this._friendGroupMap.set(e,o),this._emitGroupListUpdated(),{code:0,data:{friendGroup:o,failureUserIDList:n}}}catch(e){this._handleError(t,e)}})}deleteFriendGroup(r){return h(this,void 0,void 0,function*(){var t="deleteFriendGroup";console.log(al+` ${t} params:`,r);try{var e=r["name"],s=(this._checkGroupNotExist(t,e),yield kl(r),this._friendGroupMap.get(e));return s&&(this._updateFriendGroup({name:e,userIDList:s.userIDList,action:Sl}),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:Fl})})}removeFromFriendGroup(e){return h(this,void 0,void 0,function*(){return this._updateFriendGroupMember({functionName:"removeFromFriendGroup",params:e,protocolFunction:$l})})}renameFriendGroup(n){return h(this,void 0,void 0,function*(){var t="renameFriendGroup";console.log(al+` ${t} params:`,n);try{var{oldName:e,newName:s}=n,r=(this._checkGroupNotExist(t,e),this._checkGroupExist(t,s),yield ql(n),this._updateGroupNameInCache(e,s));return r&&this._updateFriendGroup({name:e,userIDList:r.userIDList,action:El,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(al+` ${t} params:`,s);try{let e=s["name"];this._checkGroupNotExist(t,e);var n=yield r(s),{friendGroup:o,failureUserIDList:i}=this._parseUpdateFriendGroupResponse(e,n);return this._emitGroupListUpdated(),{code:0,data:{friendGroup:o,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=[],n=[];return t.forEach(({userID:e,resultCode:t,resultInfo:s})=>{Cl(t)||0===t?r.push(e):n.push({userID:e,code:t,message:s})}),{successUserIDList:r,failureUserIDList:n}}_parseUpdateFriendGroupResponse(t,e){let{resultList:s=[]}=e,r=this._friendGroupMap.get(t),n=[],o=[],i=[];return s.forEach(e=>{0===e.resultCode?r&&(e.updateType===vl?this._addFriendToGroup(t,e.userID,r,o):e.updateType===fl&&this._removeFriendFromGroup(t,e.userID,r,i)):n.push({userID:e.userID,code:e.resultCode,message:e.resultInfo})}),{friendGroup:r,failureUserIDList:n}}_addFriendToGroup(e,t,s,r){s.addToUserIDList(t),r.push(t),this._updateFriendGroup({name:e,userIDList:r,action:Il})}_removeFriendFromGroup(e,t,s,r){s.removeFromUserIDList(t),r.push(t),this._updateFriendGroup({name:e,userIDList:r,action:Sl})}_emitGroupListUpdated(){var{notificationCenter:e,OuterEvent:t}=this._core,s=[...this._friendGroupMap.values()];console.log(al+" _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:dl})}_checkGroupExist(e,t){if(this._friendGroupMap.has(t))throw new this._core.helper.ChatError({functionName:e,code:ll})}_updateFriendGroup(e){let{name:r,userIDList:t,action:n,newName:o}=e,i=this._core.appStore["userStore"];console.log(al+" updateFriendGroup",{name:r,userIDList:t,action:n,newName:o}),r&&!this._core.utils.isEmpty(t)&&t.forEach(e=>{var t=i.getFriend(e);if(t){var s=t["groupList"];switch(n){case Il:-1===s.indexOf(r)&&(s.push(r),t.count=s.length);break;case Sl:{let e=s.indexOf(r);-1<e&&(s.splice(e,1),t.count=s.length);break}case El:if(o){let e=s.indexOf(r);-1!==e&&(s[e]=o)}}}})}_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(al+` ${e} error:`,t),t}reset(){this._friendGroupMap.clear()}dispose(){this.reset()}};function Kl(e){return e&&0!==e.length?e.map(e=>({userID:e.To_Account,addBlackTimeStamp:e.AddBlackTimeStamp})):[]}var Wl=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(al+" getBlacklistFromCache"),{code:0,data:Array.from(this._blacklistMap.keys())}})}syncBlacklistFromServer(){return h(this,void 0,void 0,function*(){try{console.log(al+" syncBlacklistFromServer");var e=yield function(r,n){return h(this,void 0,void 0,function*(){var{helper:e,channel:t}=n,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:Kl(t),startIndex:e}})}({From_Account:this._core.common.getCurrentUserID(),MaxLimited:cl,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(al+" syncBlacklistFromServer error:",e),e}})}addToBlacklist(r){return h(this,void 0,void 0,function*(){try{console.log(al+" addToBlacklist options:",r);var e=this._preprocessBlacklist(r),t=yield function(r,n){return h(this,void 0,void 0,function*(){var{helper:e,channel:t}=n,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:Kl(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(al+" addToBlacklist error:",e),e}})}removeFromBlacklist(s){return h(this,void 0,void 0,function*(){try{console.log(al+" removeFromBlacklist options:",s);var e=yield function(r,n){return h(this,void 0,void 0,function*(){var{helper:e,channel:t}=n,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:Kl(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(al+" removeFromBlacklist error:",e),e}})}dispose(){this.reset()}reset(){this._retryCount=0,this._startIndex=0,this._blacklistMap.clear()}updateBlacklist(e){console.log(al+" 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(al+" _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(al+" _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:hl});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(al+" _emitBlackListUpdated blackList:",s),e.emitOuterEvent(t.BLACKLIST_UPDATED,{name:t.BLACKLIST_UPDATED,data:s})}};let Hl={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=Rl.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=Rl.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=Rl.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=Rl.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}}},Yl={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 zl=new class{constructor(){this.name="Friend"}install(e){console.log(al+" install");var{helper:t,notificationCenter:s,InnerEvent:r,constants:{WORKFLOW_NAME:n,WORKFLOW_STEP:o}}=this._core=e;Rl.init(e),Dl.init(e),wl.init(e),jl.init(e),Wl.init(e),t.registerValidateConfig({auth:Yl,params:Hl}),t.registerWorkflowStep(n.SYNC_SERVER_INFO_AFTER_LOGIN,o.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(al+" handleLoginSuccess"),Wl.syncBlacklistFromServer(),Dl.syncFriendListFromServer(),wl.syncFriendApplicationListFromServer(),jl.syncFriendGroupListFromServer()}onFriendModified(e){var{from:e,addedBlacklist:t,removedBlacklist:s,addedFriendList:r,removedFriendList:n,addedApplicationList:o,removedApplicationList:i,friendUpdateInfo:a,reportTime:l}=this._parseFriendListModification(null==e?void 0:e.FriendListMod[0]),c=this._core.utils["isEmpty"];c(t)&&c(s)||Wl.updateBlacklist({addedBlacklist:t,removedBlacklist:s}),c(r)&&c(n)||(Dl.updateFriendList({addedFriendList:r,removedFriendList:n}),wl.updateFriendApplicationList({from:e,removedApplicationList:r})),c(a)||Dl.updateFriendInfo(a),c(o)&&c(i)||wl.updateFriendApplicationList({from:e,addedApplicationList:o,removedApplicationList:i}),l&&wl.onApplicationRead()}_parseFriendListModification(e){var{PushType:e,From_Account:t,To_Account:s,ReportTime:r,BlackListAdd_Account:n=[],BlackListDel_Account:o=[],FriendAdd_Account:i=[],FriendDel_Account:a=[],PendencyAdd:l=[],FrienPencydDel_Account:c=[],FriendUpInfo:u=[]}=e,u=u.map(e=>({userID:e.Friend_Account,tagValueList:[...e.SNS]}));return{pushType:e,from:t,to:s,reportTime:r,addedBlacklist:n,removedBlacklist:o,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:u,removedApplicationList:c}}reset(){console.log(al+" reset"),Wl.reset(),Dl.reset(),wl.reset(),jl.reset()}dispose(){console.log(al+" 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),Wl.dispose(),Dl.dispose(),wl.dispose(),jl.dispose()}};let Jl=new class{init(e){this.core=e}},Ql="Follow",Xl="FOLLOW",Zl=3122,ed={NONE:0,FOLLOWERS:1,FOLLOWING:2,MUTUAL:3};function td(i,a){return h(this,void 0,void 0,function*(){var{common:e,store:t}=Jl.core,t={FollowType:i,From_Account:null==(t=t.get("login"))?void 0:t.userId,StartCursor:a,WantNum:ad()},{FollowItem:e=[],NextCursor:t,ActionStatus:s,ErrorCode:r,ErrorInfo:n,ErrorDisplay:o}=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:n,errorDisplay:o}})}function sd(e){return h(this,void 0,void 0,function*(){return td(ed.FOLLOWERS,e)})}function od(e){return h(this,void 0,void 0,function*(){return td(ed.MUTUAL,e)})}function nd(e){return h(this,void 0,void 0,function*(){return td(ed.FOLLOWING,e)})}function id(o){return h(this,void 0,void 0,function*(){var{common:e,store:t}=Jl.core,t={From_Account:null==(t=t.get("login"))?void 0:t.userId,FollowItem:o.map(e=>({To_Account:e}))},{ResultItem:e=[],ActionStatus:t,ErrorCode:s,ErrorInfo:r,ErrorDisplay:n}=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:n}})}function rd(o){return h(this,void 0,void 0,function*(){var{common:e,store:t}=Jl.core,t={From_Account:null==(t=t.get("login"))?void 0:t.userId,To_Account:o},{ResultItem:e=[],ActionStatus:t,ErrorCode:s,ErrorInfo:r,ErrorDisplay:n}=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:n}})}function ad(){let e=Jl.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 cd={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}]},ud={getMyFollowersList:!0,getMyFollowingsList:!0,getMutualFollowersList:!0,followUser:!0,unfollowUser:!0,checkFollow:!0,getUserFollowInfo:!0};var ld=new class{constructor(){this.name="Follow"}install(e){var{helper:t,notificationCenter:s,InnerEvent:r}=this._core=e;Jl.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:ud,params:cd}),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:nd,nextCursor:e})})}getMyFollowersList(){return h(this,arguments,void 0,function*(e=""){return this._getFollowList({functionName:"getMyFollowersList",protocolFunction:sd,nextCursor:e})})}getMutualFollowersList(){return h(this,arguments,void 0,function*(e=""){return this._getFollowList({functionName:"getMutualFollowersList",protocolFunction:od,nextCursor:e})})}_getFollowList(e){return h(this,void 0,void 0,function*(){var{functionName:n,protocolFunction:o,nextCursor:i=""}=e;console.log(Ql+` ${n} nextCursor:`,i);try{this._checkBusinessCapabilityBits(n);let e=yield o(i),{resultList:t=[],nextPageToken:s=""}=e,r=this._parseFollowItems(t);return console.log(Ql+`.${n} nextCursor: ${i} from remote.`),{code:0,data:{resultList:r,nextCursor:s}}}catch(e){console.error(Ql+`.${n} fail:`,e),this._handleError(n,e)}})}followUser(e){return h(this,void 0,void 0,function*(){return this._handleUserFollowRelation({functionName:"followUser",userIDList:e,protocolFunction:id})})}unfollowUser(e){return h(this,void 0,void 0,function*(){return this._handleUserFollowRelation({functionName:"unfollowUser",userIDList:e,protocolFunction:rd})})}_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:n=[]}=yield r(e);return{code:0,data:n}}catch(e){this._handleError(t,e)}})}getUserFollowInfo(o){return h(this,void 0,void 0,function*(){var s="getUserFollowInfo";console.log(Ql+` ${s} userIDList:`,o);try{this._checkBusinessCapabilityBits(s);var n=o||[this._core.common.getCurrentUserID()];console.log(Ql+` ${s} userIDList: `+n);let e=yield function(o){return h(this,void 0,void 0,function*(){var{common:e,store:t}=Jl.core,t={From_Account:null==(t=t.get("login"))?void 0:t.userId,To_Account:o},{FollowInfo:e=[],ActionStatus:t,ErrorCode:s,ErrorInfo:r,ErrorDisplay:n}=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:n}})}(o),{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(Ql+` ${t} userIDList:`,r);try{this._checkBusinessCapabilityBits(t),100<r.length&&(r=r.slice(0,100),console.warn(Ql+` ${t} the length of userIDList cannot exceed 100`));var e=yield function(o){return h(this,void 0,void 0,function*(){var{common:e,store:t}=Jl.core,t={From_Account:null==(t=t.get("login"))?void 0:t.userId,To_Account:o},{ResultItem:e=[],ActionStatus:t,ErrorCode:s,ErrorInfo:r,ErrorDisplay:n}=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:n}})}(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(Ql+" 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"]),n={userID:t,avatar:r.FaceUrl,nick:r.NickName};s.forEach(e=>{e=this._updateFollowRelation(e,n);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={[ed.FOLLOWERS]:t.MY_FOLLOWERS_LIST_UPDATED,[ed.FOLLOWING]:t.MY_FOLLOWING_LIST_UPDATED,[ed.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(ed).forEach(e=>{e!==ed.NONE&&(t[e]={userInfoList:[],isAdd:!1})}),t}_emitFollowUpdated(e,t){console.log(Ql+" _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(Xl))throw new t.ChatError({functionName:e,code:Zl,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(Ql+` ${e} fail:`,t),t}_parseFollowItems(e){return e.map(e=>{let t,{userID:s,followTime:r,profileItem:n=[]}=e,o=[];n.forEach(e=>{o.push({tag:e.Tag,value:e.Value})});e=null==(t=this._core.user.userProfile)?void 0:t.createProfile(s,o);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 dd=new class{init(e){this.core=e}},pd="message",hd="user",gd={OR:"or",AND:"and"},_d=20,md=20,vd=20,fd={required:!1,rules:["array"],allowEmpty:!0,customValidator:e=>!e||!!(Array.isArray(e)&&e.length<=5)||"keywordList should be an array and length <= 5"},Id={required:!1,rules:["string"],allowEmpty:!0,customValidator:e=>!e||!![gd.OR,gd.AND].includes(e)||"keywordListMatchType should be OR or AND"},Sd={required:!1,rules:["number"],allowEmpty:!0,customValidator:e=>"number"==typeof e&&1<=e&&e<=100||"count must be a number between 1 and 100"},Ed={required:!1,rules:["string"],allowEmpty:!0},Cd={required:!1,rules:["array"],allowEmpty:!0,customValidator:t=>{var e=dd.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=dd.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"}},yd={required:!1,rules:["string"],allowEmpty:!0,customValidator:e=>{var t=dd.core["OuterConstant"];return!!(null!=e&&e.startsWith(t.CONV_C2C)||null!=e&&e.startsWith(t.CONV_GROUP)||e===t.CONV_SYSTEM)||"conversationID is invalid"}},Ad=t=>({required:!1,rules:["number"],allowEmpty:!0,customValidator:e=>"number"==typeof e&&0<=e||t+" should be a number >= 0';"}),Td={required:!1,rules:["string"],allowEmpty:!0,customValidator:e=>{var t=dd.core["OuterConstant"];return!![t.GENDER_FEMALE,t.GENDER_MALE].includes(e)||"gender is invalid"}},Od={searchCloudMessages:{keywordList:fd,keywordListMatchType:Id,cursor:Ed,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:yd,timePosition:Ad("timePosition"),timePeriod:Ad("timePeriod")},searchCloudUsers:{keywordList:fd,keywordListMatchType:Id,cursor:Ed,count:Sd,miniBirthday:Ad("miniBirthday"),maxBirthday:Ad("maxBirthday"),gender:Td},searchCloudGroupMembers:{keywordList:fd,keywordListMatchType:Id,cursor:Ed,count:Sd,groupTypeList:Cd,groupIDList:{required:!1,rules:["array"],allowEmpty:!0}},searchCloudGroups:{keywordList:fd,keywordListMatchType:Id,cursor:Ed,count:Sd,groupTypeList:Cd}},Dd={searchCloudMessages:!0,searchCloudUsers:!0,searchCloudGroupMembers:!0,searchCloudGroups:!0};var Rd=new class{constructor(){this.name="CloudSearch"}install(e){this._core=e,dd.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:Dd,params:Od})}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:n}=I,o=p(I,["conversationID","timePeriod","timePosition"]),l=Object.assign({count:100},o);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:n});var c=yield function(u){return h(this,void 0,void 0,function*(){var{count:e,keywordList:t,keywordListMatchType:s,senderUserIDList:r,messageTypeList:n,endTime:o,startTime:i,cursor:a,account:l,groupID:c}=u,e={Count:e,KeywordList:t,MatchType:s,SendUserIDList:r,MsgTypeList:n,EndTime:o,StartTime:i,Cursor:a,PeerAccount:l,GroupID:c};return dd.core.common.buildAndSendPacket({servcmd:"message_search.query",data:e})})}(l);if(!c)return{code:0,data:{}};var{ErrorCode:u,ErrorInfo:d,TotalCount:g,Cursor:_="",ConversationMsgs:m=[]}=c;if(0!==u)throw{errorCode:u,errorInfo:d};var v=`keywordList:${I.keywordList} keywordListMatchType:${I.keywordListMatchType} cursor:${I.cursor} res: totalCount:`+g,f=(t.setLogInfo({message:v}).end(),m.map(e=>{let{MsgList:t,Count:s,GroupID:n,UserID:r}=e,o=n?""+i.CONV_GROUP+n:""+i.CONV_C2C+r;return this._isSearchingAllConversations(I)&&1<s?{conversationID:o,messageCount:s,messageList:[]}:{conversationID:o,messageCount:s,messageList:t.map(e=>{return a.isEmpty(n)?(t=this._core,s=t.OuterConstant.CONV_C2C,r=t.message.messageHelper.parseServerPushMessage(e),(t=t.message.messageFactory.createMessage(Object.assign(Object.assign({},r),{conversationType:s,flow:"in"}))).setElement(r.elements),t):(s=this._core,r=s.OuterConstant.CONV_GROUP,t=s.message.messageHelper.parseServerGroupMessage(e),(s=s.message.messageFactory.createMessage(Object.assign(Object.assign({},t),{conversationType:r,flow:"in"}))).setElement(t.elements),s);var t,s,r})}}));return{code:0,data:{searchResultList:f,cursor:_,totalCount:g}}}catch(e){var{errorCode:c,errorInfo:u}=e||{};this._handleError({errorCode:c,errorInfo:u,searchType:pd,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=md}=S,n=p(S,["keywordListMatchType","count"]),o=Object.assign({count:r,keywordListMatchType:t===gd.AND?1:0},n),i=(this._setBirthdayRangeParams(o,S),yield function(a){return h(this,void 0,void 0,function*(){var{count:e,keywordList:t,keywordListMatchType:s,miniBirthday:r,maxBirthday:n,cursor:o,gender:i}=a,e={Count:e,Keywords:t,KeywordMatchType:s,Cursor:o,UserBirthStart:r,UserBirthEnd:n,Gender:i};return dd.core.common.buildAndSendPacket({servcmd:"user_search.query",data:e})})}(o));if(!i)return{error:0,data:{}};var{ErrorCode:a,ErrorInfo:l,TotalCount:c,Cursor:u="",Users:d=[]}=i;if(0!==a)throw{errorCode:a,errorInfo:l};var g=`keywordList:${S.keywordList} keywordListMatchType:${S.keywordListMatchType} cursor:${S.cursor} count:${S.count} res: totalCount:`+c,_=(e.setLogInfo({message:g}).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),_.push(v))}return{code:0,data:{searchResultList:_,cursor:u,totalCount:c}}}catch(e){let{errorCode:t,errorInfo:s}=e||{};this._handleError({errorCode:t,errorInfo:s,searchType:hd,functionName:"searchCloudUsers"})}})}searchCloudGroupMembers(g){return h(this,void 0,void 0,function*(){try{var e=this._core.ssoLog.createSSOLogData({method:"searchCloudGroupMembers"}),{count:t=vd,keywordListMatchType:s}=g,r=p(g,["count","keywordListMatchType"]),n=yield function(i){return h(this,void 0,void 0,function*(){var{count:e,keywordList:t,keywordListMatchType:s,groupTypeList:r,cursor:n,groupIDList:o}=i,e={Count:e,Keywords:t,KeywordMatchType:s,Cursor:n,GroupType:r,GroupIdList:o};return dd.core.common.buildAndSendPacket({servcmd:"group_member_search.query",data:e})})}(Object.assign({count:t,keywordListMatchType:s===gd.AND?1:0},r));if(!n)return{code:0,data:{}};var{ErrorCode:o,ErrorInfo:i,GroupMembers:a=[],Cursor:c,TotalCount:u}=n;if(0!==o)throw{errorCode:o,errorInfo:i};var d=`keywordList:${g.keywordList} keywordListMatchType:${g.keywordListMatchType} cursor:${g.cursor} count:${g.count} res: totalCount:`+u;e.setLogInfo({message:d}).end();let l=new Map;return a.forEach(e=>{var{GroupID:t,GroupName:e,GroupType:s,GroupFaceUrl:r,GroupMemberUserName:n,GroupMemberUserID:o,GroupMemberNameCard:i,GroupMemberAvatar:a=""}=e,e={groupID:t,name:e,type:s,avatar:r},s={userID:o,nick:n,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:c,totalCount:u}}}catch(e){var{errorCode:t,errorInfo:s}=e||{};this._handleError({errorCode:t,errorInfo:s,searchType:hd,functionName:"searchCloudGroupMembers"})}})}searchCloudGroups(d){return h(this,void 0,void 0,function*(){try{var e=this._core.ssoLog.createSSOLogData({method:"searchCloudGroups"}),{count:t=_d,keywordListMatchType:s}=d,r=p(d,["count","keywordListMatchType"]),n=yield function(o){return h(this,void 0,void 0,function*(){var{count:e,keywordList:t,keywordListMatchType:s,groupTypeList:r,cursor:n}=o,e={Count:e,Keywords:t,KeywordMatchType:s,Cursor:n,GroupType:r};return dd.core.common.buildAndSendPacket({servcmd:"group_search.query",data:e})})}(Object.assign({count:t,keywordListMatchType:s===gd.AND?1:0},r));if(!n)return{code:0,data:{}};var{ErrorCode:o,ErrorInfo:i,Groups:a,Cursor:l,TotalCount:c}=n;if(0!==o)throw{errorCode:o,errorInfo:i};var u=`keywordList:${d.keywordList} keywordListMatchType:${d.keywordListMatchType} cursor:${d.cursor} count:${d.count} res: totalCount:`+c;return e.setLogInfo({message:u}).end(),{code:0,data:{searchResultList:(null==a?void 0:a.map(e=>{var{GroupFaceUrl:e,GroupID:t,GroupIntroduction:s,GroupMemberNum:r,GroupName:n,GroupOwnerTinyID:o,GroupOwnerUserID:i,GroupOwnerUserName:a,GroupType:l,GroupAddOption:c,GroupInviteOption:u}=e;return{avatar:e,groupID:t,introduction:s,memberCount:r,name:n,ownerTinyID:o,ownerID:i,ownerNick:a,type:l,joinOption:c,inviteOption:u}}))||[],cursor:l,totalCount:c}}}catch(e){var{errorCode:t,errorInfo:s}=e||{};this._handleError({errorCode:t,errorInfo:s,searchType:hd,functionName:"searchCloudGroups"})}})}_setTimeRangeParams(e,{timePeriod:t,timePosition:s}){t&&0<t&&(e.startTime=s&&0<s?s-t:this._core.helper.timeManager.getServerTimeSeconds()-t),e.startTime&&e.startTime<0&&(e.startTime=void 0),s&&0<s&&(e.endTime=s)}_handleError({errorCode:e,errorMessage:t,searchType:s,functionName:r}){var{ssoLog:n,helper:o}=this._core;let i=e;60020===e?i="SearchUnable":s!==pd&&27003===e?i="SearchParamsError":s!==pd&&60018===e&&(i="SearchOverLimit");s=new o.ChatError({code:i,message:t});throw n.getSSOLogData(r).setError(s).end(),s}_isSearchingAllConversations(e){return this._core.helper.isEmpty(e.conversationID)}_setBirthdayRangeParams(e,t){var{miniBirthday:t,maxBirthday:s}=t;void 0!==t&&(e.miniBirthday=t,void 0===s)&&(e.maxBirthday=4294967295),void 0!==s&&(e.maxBirthday=s)}},Ld=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 Nd=new class{init(e){this.core=e}},bd="CONV_GROUP",Gd=2500,wd=2503,Pd=1,Ud=2,kd="NOT_STARTED",Fd="FETCHING",$d="FINISHED",qd="FAILED",xd=0,Vd=1,Bd=1,Kd=2,Wd=3,Hd=1,Yd=2;function zd(e){var{helper:t,constants:s}=Nd.core;if(!t.checkBusinessCapabilityBits(bd))throw new t.ChatError({functionName:e,code:s.ERROR_CODE.NO_USE,replacement1:e})}function Jd(){var{notificationCenter:e,OuterEvent:t}=Nd.core;e.emitOuterEvent(t.CONVERSATION_GROUP_LIST_UPDATED,{name:t.CONVERSATION_GROUP_LIST_UPDATED,data:[...Ld.getConversationGroupMap().values()]})}function Qd(e){var{utils:{isUndefined:t},constants:{OuterConstant:s}}=Nd.core,{Type:e,To_Account:r,GroupId:n,ToGroupId:n=n,Peer_Account:o}=e;let i="";return e===Pd?t(o)?t(r)||(i=""+s.CONV_C2C+r):i=""+s.CONV_C2C+o:e===Ud&&(i=""+s.CONV_GROUP+n),i}function Xd(e){let t=[],{OuterConstant:s,common:{isC2CConv:r,isGroupConv:n}}=Nd.core,{conversationIDList:o,failureConversationIDList:i,additionalData:a={}}=e;return o.forEach(e=>{Zd(e,i),r(e)?t.push(Object.assign({ContactItem:{Type:Pd,To_Account:e.replace(s.CONV_C2C,"")}},a)):n(e)&&t.push(Object.assign({ContactItem:{Type:Ud,ToGroupId:e.replace(s.CONV_GROUP,"")}},a))}),t}function Zd(e,t){var{appStore:{conversationStore:s},common:{isC2CConv:r,isGroupConv:n}}=Nd.core;s.getConversation(e)?r(e)||n(e)||t.push({conversationID:e,code:wd}):t.push({conversationID:e,code:Gd})}function ep(t){var{isString:e}=Nd.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 tp(n){null!=n&&n.forEach((e,t)=>{var s=Nd.core["appStore"],{conversationID:e,data:r}=e,t=t===n.length-1;s.conversationStore.updateConversation(e,r,{emit:t})})}function sp(e){var{conversationInfoList:e,fromAccount:t}=e,t={From_Account:t,MarkItem:e};return Nd.core.common.buildAndSendPacket({servcmd:"recentcontact.mark_contact",data:t})}function op(e){var{fromAccount:e,groupName:t,conversationInfoList:s}=e,e={From_Account:e,UpdateType:1,UpdateGroup:{UpdateGroupType:Yd,OldGroupName:t,ContactUpdateItem:s}};return Nd.core.common.buildAndSendPacket({servcmd:"recentcontact.update_contact_group",data:e})}var np=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:o,isArray:i},appStore:a,ssoLog:e}=this._core;zd("createConversationGroup");var l=e.createSSOLogData({method:"createConversationGroup"});l.setLogInfo({message:JSON.stringify(r)});let{groupName:c,conversationIDList:t}=r,u=[],s=this._generateConversationInfo(t,u);if(u.length===t.length)return{code:0,data:{successConversationIDList:[],failureConversationIDList:u}};try{let n=yield function(e){var{buildAndSendPacket:t,getCurrentUserID:s}=Nd.core["common"],{item:e,groupName:r}=e;return t({servcmd:"recentcontact.create_contact_group",data:{From_Account:s(),GroupContactItem:[{GroupName:r,ContactItem:e}]}})}({groupName:c,item:s});if(n){l.end();let{GroupResultItem:e=[]}=n,{GroupItem:s,ResultItem:t}=(null==e?void 0:e[0])||{},r=[];if(o(s)){let{GroupName:e,GroupId:t}=s;Ld.setConversationGroup(t,e),Jd()}if(i(t)){let o=[];t.forEach(e=>{let{ContactItem:t,ResultCode:s,ResultInfo:r}=e,n=Qd(t);if(0===s){let t=a.conversationStore.getConversation(n);if(t&&!t.conversationGroupList.includes(c)){let e=t.conversationGroupList.slice();e.push(c),o.push({conversationID:n,data:{conversationGroupList:e}})}}else u.push({conversationID:n,code:s,message:r})}),0<o.length&&(tp(o),Jd())}return{code:0,data:{successConversationIDList:r,failureConversationIDList:u}}}}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:n,common:{isC2CConv:o,isGroupConv:i}}=this._core;return e.forEach(e=>{Zd(e,t),o(e)?r.push(Object.assign({Type:Pd,To_Account:e.replace(n.CONV_C2C,"")},s)):i(e)&&r.push(Object.assign({Type:Ud,ToGroupId:e.replace(n.CONV_GROUP,"")},s))}),r}},ip=new class{constructor(){this._fetchConversationGroupStatus=kd}init(e){var{helper:{registerApi:t,registerWorkflowStep:s},constants:{WORKFLOW_NAME:r,WORKFLOW_STEP:n}}=e;this._core=e,t({apiName:"getConversationGroupList",context:this}),s(r.SYNC_SERVER_INFO_AFTER_LOGIN,n.CONVERSATION_GROUP_LIST_SYNC,this._syncConversationGroupList,this),s(r.SYNC_SERVER_INFO_AFTER_LOGIN,n.CONVERSATION_GROUP_UPDATE,this._updateConversation,this)}getConversationGroupList(){return h(this,void 0,void 0,function*(){return zd("getConversationGroupList"),this._fetchConversationGroupStatus===qd&&(yield this._fetchConversationGroupList(0)),{code:0,data:[...Ld.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,o=[]){let{common:{getCurrentUserID:e},utils:{isArray:i}}=this._core;this._fetchConversationGroupStatus=Fd;try{let s=e(),n=yield function(){var{fromAccount:e,startIndex:t}={fromAccount:s,startIndex:r},e={From_Account:e,StartIndex:t};return Nd.core.common.buildAndSendPacket({servcmd:"recentcontact.get_contact_group",data:e})}();if(n){let{CompleteFlag:e,ContactItem:t=[],NextStartIndex:s=0,GroupItem:r=[]}=n;return(i(r)&&r.forEach(e=>{var{GroupName:e,GroupId:t}=e;Ld.setConversationGroup(t,e)}),o.push(...t),e===xd)?this._fetchConversationGroupList(s):e===Vd?(this._fetchConversationGroupStatus=$d,o):void 0}}catch(r){this._fetchConversationGroupStatus=qd,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])||[];tp(this._generateConversationUpdateFields(e)),Jd()}_generateConversationUpdateFields(e){let{utils:{isArray:i},appStore:a}=this._core,l=[];if(i(e)){let o;e.forEach(e=>{let t=[],{StandardMark:s,CustomMark:r="",ContactGroupId:n}=e;i(n)&&n.forEach(e=>{Ld.getConversationGroupMap().has(e)&&t.push(Ld.getConversationGroup(e))});e=Qd(e);(o=a.conversationStore.getConversation(e))&&l.push({conversationID:e,data:{markList:ep(s),customData:r,conversationGroupList:[...t]}})})}return l}reset(){this._fetchConversationGroupStatus=kd}dispose(){this.reset()}},rp=new class{init(e){var{notificationCenter:t,helper:{registerApi:s},InnerEvent:{MESSAGE_PUSH:r},InnerEventSubType:{CONVERSATION_MARK_UPDATED:n,CONVERSATION_GROUP_ADD:o,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,o,this._handleConversationGroupAdd,this),t.subscribeInnerEvent(r,i,this._handleConversationGroupDeleted,this),t.subscribeInnerEvent(r,a,this._handleConversationGroupUpdated,this),t.subscribeInnerEvent(r,n,this._handleConversationMarkUpdated,this)}renameConversationGroup(t){return h(this,void 0,void 0,function*(){zd("renameConversationGroup");let{common:{getCurrentUserID:r},ssoLog:e}=this._core,{oldName:n,newName:o}=t,i=e.createSSOLogData({method:"renameConversationGroup"});i.setLogInfo({message:`oldName:${n} newName:`+o});try{let s=yield function(){var{fromAccount:e,oldName:t,newName:s}={fromAccount:r(),oldName:n,newName:o},e={From_Account:e,UpdateType:1,UpdateGroup:{UpdateGroupType:Hd,OldGroupName:t,NewGroupName:s}};return Nd.core.common.buildAndSendPacket({servcmd:"recentcontact.update_contact_group",data:e})}();if(s){i.end();let e=s["UpdateGroupResult"],t=e["GroupId"];Ld.setConversationGroup(t,o),Jd(),this._updateLocalConversationGroupName({oldName:n,newName:o})}}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*(){zd("deleteConversationGroup");let{common:{getCurrentUserID:s},ssoLog:e}=this._core,n=e.createSSOLogData({method:"deleteConversationGroup"});n.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 Nd.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=Ld.getConversationGroupMap();t.has(e)&&(t.delete(e),s=!0)}),s&&Jd(),this._deleteLocalConversationGroupName([r])}}catch(e){let{errorCode:t,errorInfo:s}=e,r=new this._core.helper.ChatError({functionName:"deleteConversationGroup",code:t,message:s});throw n.setError(r).end(),r}})}markConversation(g){return h(this,void 0,void 0,function*(){zd("markConversation");let{utils:{isNumber:e},common:{getCurrentUserID:s},ssoLog:t,appStore:i}=this._core,{conversationIDList:r,markType:a,enableMark:l}=g,n=this._getFlagBit(a),c=[],u=[],o,d;var h=t.createSSOLogData({method:"markConversation"}),p=(h.setLogInfo({message:JSON.stringify(g)}),!0===l&&e(n)?o=[n]:d=[n],Xd({conversationIDList:r,failureConversationIDList:c,additionalData:{SetMark:o,ClearMark:d,OptType:Bd}}));if(c.length===r.length)return{code:0,data:{successConversationIDList:[],failureConversationIDList:c}};try{let t=yield sp({conversationInfoList:p,fromAccount:s()});if(t){h.end();let e=t["ResultItem"],o=[];e.forEach(e=>{let{ContactItem:t,ResultCode:s,ResultInfo:r}=e,n=Qd(t);if(0===s){u.push(n);let s=i.conversationStore.getConversation(n);if(s){let t=s.markList.indexOf(a),e=!1===l&&-1!==t;if(!0===l&&-1===t)o.push({conversationID:n,data:{markList:[...s.markList,a]}});else if(e){let e=s.markList.slice();e.splice(t,1),o.push({conversationID:n,data:{markList:e}})}}}else c.push({conversationID:n,code:s,message:r})}),tp(o)}return{code:0,data:{successConversationIDList:u,failureConversationIDList:c}}}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(n){return h(this,void 0,void 0,function*(){zd("setConversationCustomData");let{common:{getCurrentUserID:e},ssoLog:t,appStore:o}=this._core,{conversationIDList:s,customData:i}=n,a=[],l=[],c=t.createSSOLogData({method:"setConversationCustomData"});c.setLogInfo({message:JSON.stringify(n)});var r=Xd({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 sp({fromAccount:e(),conversationInfoList:r});if(t){c.end();let e=t["ResultItem"],n=[];null!=e&&e.forEach(e=>{let{ContactItem:s,ResultCode:t,ResultInfo:r}=e;if(0===t){let e=Qd(s),t=(l.push(e),o.conversationStore.getConversation(e));t&&t.customData!==i&&n.push({conversationID:e,data:{customData:i}})}else a.push({conversationID:conversationID,code:t,message:r})}),tp(n)}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 c.setError(r).end(),r}})}deleteConversationsFromGroup(n){return h(this,void 0,void 0,function*(){zd("deleteConversationsFromGroup");let{common:{getCurrentUserID:e},ssoLog:t,appStore:o}=this._core,i=t.createSSOLogData({method:"deleteConversationsFromGroup"}),{conversationIDList:s,groupName:a}=(i.setLogInfo({message:JSON.stringify(n)}),n),l=[],c=[],r=Xd({conversationIDList:s,failureConversationIDList:l,additionalData:{ContactOptType:2}});if(l.length===s.length)return{code:0,data:{successConversationIDList:[],failureConversationIDList:l}};try{let t=yield op({fromAccount:e(),groupName:a,conversationInfoList:r});if(t){i.end();let n=[],{ContactResultItem:e}=t["UpdateGroupResult"];null!=e&&e.forEach(e=>{var s,r=Qd(e.ContactItem);if(0===e.ResultCode){let t=o.conversationStore.getConversation(r);if(t){let e=t.conversationGroupList.indexOf(a);-1!==e&&((s=t.conversationGroupList.slice()).splice(e,1),c.push(r),n.push({conversationID:r,data:{conversationGroupList:s}}))}}else l.push({conversationID:r,code:e.ResultCode,message:e.ResultInfo})}),0<n.length&&(Jd(),tp(n))}return{code:0,data:{successConversationIDList:c,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(c){return h(this,void 0,void 0,function*(){zd("deleteConversationsFromGroup");let{common:{getCurrentUserID:e},ssoLog:t,appStore:n}=this._core,o=t.createSSOLogData({method:"addConversationsToGroup"}),{conversationIDList:s,groupName:i}=(o.setLogInfo({message:JSON.stringify(c)}),c),a=[],l=[],r=Xd({conversationIDList:s,failureConversationIDList:a,additionalData:{ContactOptType:1}});if(a.length===s.length)return{code:0,data:{successConversationIDList:[],failureConversationIDList:a}};try{let t=yield op({fromAccount:e(),groupName:i,conversationInfoList:r});if(t){o.end();let r=[],{ContactResultItem:e}=t["UpdateGroupResult"];null!=e&&e.forEach(e=>{var s=Qd(e.ContactItem);if(0===e.ResultCode){let t=n.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&&(Jd(),tp(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 o.setError(r).end(),r}})}_updateLocalConversationGroupName(e){let t=this._core["appStore"],{oldName:s,newName:r}=e,n=[],o=[],i;Array.from(t.conversationStore.getConversationMap().values()).forEach(e=>{var t;n=e.conversationGroupList,-1!==(i=n.indexOf(s))&&((t=n.slice()).splice(i,1,r),o.push({conversationID:e.conversationID,data:{conversationGroupList:t}}))}),tp(o)}_deleteLocalConversationGroupName(n){var{utils:{isEmpty:e},appStore:t}=this._core;if(!e(n)){let r=[];Array.from(t.conversationStore.getConversationMap().values()).forEach(e=>{var{conversationID:e,conversationGroupList:t}=e,s=t.filter(e=>!n.includes(e));s.length<t.length&&r.push({conversationID:e,data:{conversationGroupList:s}})}),tp(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:n}=t,o=[];Ld.getConversationGroup(r)!==n&&(Ld.setConversationGroup(r,n),i=!0),a(s)&&s.forEach(e=>{var t=Qd(e),s=l.conversationStore.getConversation(t);if(s&&(null==(e=s.conversationGroupList)||!e.includes(n))){let e=s.conversationGroupList.slice();e.push(n),o.push({conversationID:t,data:{conversationGroupList:e}})}}),i&&Jd(),tp(o)})})}_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,n=[];e.forEach(e=>{var{GroupId:e,GroupName:t}=e,s=Ld.getConversationGroupMap();s.has(e)&&(s.delete(e),r=!0,n.push(t))}),r&&Jd(),0<n.length&&this._deleteLocalConversationGroupName(n)}})}_handleConversationGroupUpdated(e){null!=(e=e.RecentContactMod)&&e.forEach(e=>{var{GroupId:e,GroupName:t,OldGroupName:s,RecentContactUpdateGroupItem:r,UpdateGroupType:n}=e["RecentContactUpdateContactGroup"]["MsgUpdateGroup"];1===n?this._handleGroupNameUpdated({groupID:e,newName:t,oldName:s}):2===n&&this._handleGroupAddOrDeleteFromConversation({groupInfoList:r,groupName:s})})}_handleConversationMarkUpdated(e){let t,o=this._core.appStore;null!=(t=null==e?void 0:e.RecentContactMod)&&t.forEach(e=>{let{RecentContactMarkContactItem:t}=e["RecentContactMarkContact"],n=[];null!=t&&t.forEach(e=>{var{RecentContactItem:e,CustomMark:t,StandardMark:s,OptType:r}=e,e=Qd(e),e=o.conversationStore.getConversation(e);e&&(r===Bd?this._updateStandMark({conversation:e,standardMark:s,updateConversationList:n}):r===Kd?this._updateCustomMark({conversation:e,customMark:t,updateConversationList:n}):r===Wd&&(this._updateStandMark({conversation:e,standardMark:s,updateConversationList:n}),this._updateCustomMark({conversation:e,customMark:t,updateConversationList:n})))}),tp(n)})}_updateStandMark(e){var{conversation:e,standardMark:t,updateConversationList:s}=e,t=ep(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;Ld.getConversationGroup(e)!==s&&(Ld.setConversationGroup(e,s),Jd(),this._updateLocalConversationGroupName({oldName:t,newName:s}))}_handleGroupAddOrDeleteFromConversation({groupInfoList:e,groupName:o}){let i=this._core["appStore"],a=[];e.forEach(e=>{var{RecentContactItem:e,ContactOptType:t}=e,s=Qd(e),r=i.conversationStore.getConversation(s),n=r.conversationGroupList.indexOf(o);if(r){let e=r.conversationGroupList.slice();1===t&&-1===n?(e.push(o),a.push({conversationID:s,data:{conversationGroupList:e}})):2===t&&-1!==n&&(e.splice(n,1),a.push({conversationID:s,data:{conversationGroupList:e}}))}}),tp(a)}dispose(){var{notificationCenter:e,InnerEvent:{MESSAGE_PUSH:t},InnerEventSubType:{CONVERSATION_MARK_UPDATED:s,CONVERSATION_GROUP_ADD:r,CONVERSATION_GROUP_DELETED:n,CONVERSATION_GROUP_UPDATED:o}}=this._core;e.unSubscribeInnerEvent(t,r,this._handleConversationGroupAdd,this),e.unSubscribeInnerEvent(t,n,this._handleConversationGroupDeleted,this),e.unSubscribeInnerEvent(t,o,this._handleConversationGroupUpdated,this),e.unSubscribeInnerEvent(t,s,this._handleConversationMarkUpdated,this)}};let ap={required:!0,rules:["string"],allowEmpty:!1},cp={required:!0,rules:["array"],allowEmpty:!1},up={createConversationGroup:{groupName:ap,conversationIDList:{required:!0,rules:["array"],allowEmpty:!1}},renameConversationGroup:{oldName:ap,newName:Object.assign(Object.assign({},ap),{customValidator:e=>!(32<e.length)||"newName length cannot longer than 32"})},deleteConversationGroup:[{required:!0,rules:["string"],allowEmpty:!1}],addConversationsToGroup:{conversationIDList:cp,groupName:ap},deleteConversationsFromGroup:{conversationIDList:cp,groupName:ap},markConversation:{conversationIDList:cp,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:cp,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"}}},lp={createConversationGroup:!0,deleteConversationGroup:!0,renameConversationGroup:!0,getConversationGroupList:!0,addConversationsToGroup:!0,deleteConversationsFromGroup:!0,markConversation:!0,setConversationCustomData:!0};var dp=new class{constructor(){this.name="ConversationGroup"}install(e){this._core=e,Nd.init(e),Ld.init(e),np.init(e),ip.init(e),rp.init(e),e.helper.registerValidateConfig({auth:lp,params:up}),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),rp.dispose(),ip.dispose()}reset(){ip.reset()}};let pp=new class{init(e){this.core=e}},hp="@TOPIC#_",gp=7,_p=8,mp=17,vp=18,fp=20,Ip=300,Sp=0,Ep=3600,Cp=3021,Mp=["topicID","topicName","avatar","introduction","notification","unreadCount","muteAllMembers","customData","nextMessageSeq","selfInfo","lastMessage"],yp=e=>{var{common:{getMessagePreviewText:t}}=pp["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 Ap{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=yp(),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]=yp(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=yp(e)}updateGroupAtInfoList(e){var{common:{updateGroupAtInfo:t}}=pp["core"];t(e,this.groupAtInfoList)}updateTopic(e){var{utils:{isUndefined:t},common:{deepMerge:s}}=pp["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}}=pp["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 Tp=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:n}}=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(n,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 Ap(e),this._setTopic(t,s,r));e=this.computeUnreadCount(r);null!=r&&r.updateUnreadCount(e)})}_getLastMessage(s){var{isEmpty:r,isUndefined:n,isArray:o}=this._core["utils"];if(!n(s.lastMsg)){let e=null,t="";t=(o(s.lastMsg.elements)?(e=s.lastMsg.elements[0].content,s.lastMsg.elements[0]):(e=s.lastMsg.elements.content,s.lastMsg.elements)).type;n={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=n}}computeUnreadCount(s){let{excludedUnreadSequenceList:e=[],readedSequence:r}=s.selfInfo,n=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&&(n-=t)}return 0<n?n: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:n,isEmpty:t}}=this._core,o=e(),i=null;s.forEach(e=>{var{groupID:t,topicID:s,from:r}=e;r!==o&&((i=this.getTopic(t,s))&&i.updateGroupAtInfoList(e),n(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,n=(null==t?void 0:t.getLocalMessageList(""+r+e))||[];if(0!==n.length){e=n["length"];for(let t=e-1;0<=t;t--){let e=n[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 n=!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),n=!0),n)&&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 Op=(e="")=>{var{OuterConstant:t}=pp["core"];return e.replace(t.CONV_GROUP,"")},Dp=(e="")=>e.split(hp)[0];var Rp=new class{constructor(){this._name="TopicMessageHandler"}init(e){var{helper:e,notificationCenter:t,constants:{WORKFLOW_NAME:s,WORKFLOW_STEP:r},InnerEvent:{MESSAGE_PUSH:n,TOPIC_NEW_MESSAGE:o,TOPIC_MESSAGE_DELETED:i,TOPIC_MESSAGE_REVOKED:a,TOPIC_MESSAGE_MODIFIED:l,DESTROY:c}}=this._core=e,{TOPIC_AT_TIPS:u,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(o,this._handleNewMessage,this),t.subscribeInnerEvent(i,this._handleMessageDeleted,this),t.subscribeInnerEvent(a,this._handleMessageRevoked,this),t.subscribeInnerEvent(l,this._handleMessageModified,this),t.subscribeInnerEvent(n,u,this._handleTopicAtTips,this),t.subscribeInnerEvent(n,d,this._handleLatestMessage,this),t.subscribeInnerEvent(c,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:n}=e,s=Op(t),r=Dp(s),o=Tp.getTopic(r,s);if(o){let{from:e,sequence:t}=n,s=t+1,r=e===i();if(s>o.nextMessageSeq){o.updateNextMessageSeq(s),o.updateLastMessage(n),o.updateReadSequence(t,r);let e=r?0:Tp.computeUnreadCount(o);o.updateUnreadCount(e),this._emitTopicUpdate(o)}}})}}}_handleMessageDeleted(s){var r=Op(s),n=Dp(r),n=Tp.getTopic(n,r);if(console.log(this._name+`._handleMessageDeleted, topicID:${r} hasTopic:`+!!n),n){var{message:{messageDataHandler:o},utils:{isEmpty:i}}=this._core,a=(null==o?void 0:o.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;n.lastMessage.lastSequence!==t.sequence&&(i(t)&&(t={}),n.updateLastMessage(t),e=!0),e&&(this._emitTopicUpdate(n),console.log(this._name+`._handleMessageDeleted, topicID:${r} with lastMessage:`+n.lastMessage))}}_handleMessageRevoked(e){var{messageList:e=[]}=e;if(console.log(this._name+"._handleMessageRevoked messageList:"+e.length),0!==e.length){let n=null,o=!1;e.forEach(e=>{var{to:e,sequence:t,revoker:s}=e,r=Dp(e);if(n=Tp.getTopic(r,e)){n.reduceUnreadCount()&&(o=!0),n.isLastMessageRevoked(t)&&(n.setLastMessageRevoked(!0),n.setLastMessageRevoker(s),o=!0);let{excludedUnreadSequenceList:e=[]}=n.selfInfo;e.push(t),n.updateSelfInfo({excludedUnreadSequenceList:e})}}),o&&this._emitTopicUpdate(n)}}_handleMessageModified(e){let{conversationID:t,messageList:s}=e,r=Op(t),n=Dp(r),a=Tp.getTopic(n,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:n,messageVersion:o}=i;l.type=r[0].type,l.payload=r[0].content,l.messageForShow=e(l.type,l.payload),l.cloudCustomData=n,l.version=o,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,o=[],i=!1;t.forEach(e=>{var{GroupAtTips:e,MsgBody:t,MsgRandom:s,ClientSeq:r}=e;let n={};e?n=this._convertAtInfo(e):t&&(n=this._convertAtInfo(t),i=!0),n.__random=s,n.__sequence=r,o.push(n)}),Tp.updateGroupAtInfoList(o,i)}_convertAtInfo(e){var{From_Account:e,GroupId:t,TopicId:s,MsgSeq:r,GroupAtType:n}=e;return{groupID:t,topicID:s,from:e,sequence:r,groupAtType:n}}_handleLatestMessage(e){let{utils:{isEmpty:t},message:{messageHelper:r,messageFactory:n}}=this._core,{NewMsg:o,NoUnreadSeqList:i}=e||{};if(!t(o)){let{TopicId:e}=o["GroupInfo"],t=r.parseServerGroupMessage(o),s=n.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:n}=e,o=Dp(s),i=Tp.getTopic(o,s);if(i){let e=i.selfInfo.excludedUnreadSequenceList||[];if(t(n)||(e=n),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),Tp.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:n,TOPIC_MESSAGE_MODIFIED:o,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(n,this._handleMessageRevoked,this),e.unSubscribeInnerEvent(o,this._handleMessageModified,this),e.unSubscribeInnerEvent(t,a,this._handleTopicAtTips,this),e.unSubscribeInnerEvent(t,l,this._handleLatestMessage,this),e.unSubscribeInnerEvent(i,this._dispose,this)}},Lp=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:n,TOPIC_MESSAGE_READ_SYNC:o}=e["InnerEventSubType"];e.subscribeInnerEvent(t,r,this._handleTopicTips,this),e.subscribeInnerEvent(t,n,this._handleTopicNotices,this),e.subscribeInnerEvent(t,o,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!==gp?s.MsgBody.OpType!==_p?this._emitTopicTips(s):this._handleTopicProfileUpdated(s):this._handleMuteTimeUpdated(s)}}_handleMuteTimeUpdated(e){var{getCurrentUserID:t}=this._core["common"],{GroupInfo:{GroupId:s,TopicId:r},MsgBody:{MsgMemberInfo:n=[]}}=e;for(let e=0;e<n.length;e++){var{User_Account:o,ShutupTime:i}=n[e];if(o===t()&&0<=i){Tp.updateSelfInfo({groupID:s,topicID:r,selfInfo:{muteTime:i}});break}}}_handleTopicProfileUpdated(e){var{GroupInfo:{GroupId:e,TopicId:t},MsgBody:{MsgTopicNewInfo:{CustomString:s,ShutupAll:r,TopicFaceUrl:n,TopicIntroduction:o,TopicName:i,TopicNotification:a}}}=e,l=Tp.getTopic(e,t);l&&(l.updateTopic({groupID:e,topicID:t,customData:s,muteAllMembers:r,avatar:n,introduction:o,topicName:i,notification:a}),Tp.emitTopicUpdate(l))}_handleTopicNotices(e){var{GroupTips:t=[]}=e;for(let e=0;e<t.length;e++){var s=t[e],{MsgBody:{ReportType:r,TopicIdArray:n,MsgFlag:o},GroupInfo:{GroupId:i,TopicId:a}}=s;r===mp?this._handleTopicCreated({groupID:i,topicID:a}):r===vp?this._handleTopicDeleted({groupID:i,topicIDList:n}):r===fp?this._handleMessageRemindTypeUpdated({groupID:i,topicID:a,messageRemindType:o}):this._emitTopicNotices(s)}}_handleTopicCreated(e){var{OuterEvent:t,notificationCenter:s}=this._core;Tp.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:n=[]}=e;Tp.deleteTopicList(r,n),s.emitOuterEvent(t.TOPIC_DELETED,{name:t.TOPIC_DELETED,data:e})}_handleMessageRemindTypeUpdated(e){var{groupID:e,topicID:t,messageRemindType:s}=e;Tp.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),Tp.updateSelfInfo({groupID:e,topicID:t,selfInfo:{readedSequence:s}}),Tp.clearGroupAtInfoList(e,t),Tp.markMessageAsRead(t,s),Tp.updateUnreadCount(e,t)})})}_emitTopicTips(e){var{message:{messageHelper:t,messageFactory:s},OuterConstant:r,OuterEvent:n,notificationCenter:o}=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,o.emitOuterEvent(n.MESSAGE_RECEIVED,{name:n.MESSAGE_RECEIVED,data:[e]})}_emitTopicNotices(e){var{message:{messageHelper:t,messageFactory:s},OuterConstant:r,OuterEvent:n,notificationCenter:o}=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,o.emitOuterEvent(n.MESSAGE_RECEIVED,{name:n.MESSAGE_RECEIVED,data:[e]})}_dispose(){var{notificationCenter:e,InnerEvent:{MESSAGE_PUSH:t,DESTROY:s}}=this._core,{TOPIC_TIPS_NOTIFICATION:r,TOPIC_SYSTEM_NOTIFICATION:n,TOPIC_MESSAGE_READ_SYNC:o}=e["InnerEventSubType"];e.unSubscribeInnerEvent(t,r,this._handleTopicTips,this),e.unSubscribeInnerEvent(t,n,this._handleTopicNotices,this),e.unSubscribeInnerEvent(t,o,this._handleTopicMessageReadSynced,this),e.unSubscribeInnerEvent(s,this._dispose,this)}},Np=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}}})}},bp=new class{constructor(){this._name="CreateTopicHandler"}init(e){e=(this._core=e).helper;e.registerApi({apiName:"createTopicInCommunity",context:this})}createTopicInCommunity(o){return h(this,void 0,void 0,function*(){let s="createTopicInCommunity",{utils:{isUndefined:e},common:{isTopic:t},helper:{ChatError:r}}=this._core,n=o["topicID"];if(!e(n)&&!t(n)){let e=new r({functionName:s,code:Cp});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:n,introduction:o,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:n,Introduction:o,CustomString:i}})})}(o,this._core),{TopicId:t=""}=e||{};return console.log(this._name+`.${s} ok, topicID:`+t),Tp.updateTopic([Object.assign(Object.assign({},o),{topicID:t})]),{code:0,data:{topicID:t}}}catch(e){throw console.error(this._name+`.${s} failed, error:`,e),e}})}},Gp=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=[],n=[],o=[];return t.forEach(e=>{var{TopicId:e,ErrorCode:t,ErrorInfo:s}=e;0===t?(r.push({topicID:e}),o.push(e)):n.push({topicID:e,code:t,message:s})}),0<o.length&&Tp.deleteTopicList(l.groupID,o),console.log(`${this._name}.${s} ok, groupID:${i} success:${r.length} fail:`+n.length),{code:0,data:{successTopicList:r,failureTopicList:n}}}catch(e){throw console.error(this._name+`.${s} failed, error:`,e),e}})}},wp=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=Tp.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}=Tp.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))>=Sp&&t<=Ep?1e3*t:1e3*Ip}_getTopicListFromServer(c,u){return h(this,void 0,void 0,function*(){var r="_getTopicListFromServer",{isEmpty:n}=this._core["utils"],l=c["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"]}})})}(c,this._core),{TopicAndSelfInfo:t=[]}=e||{},o=[],i=[],a=[],s=(this._convertTopicInfoList(t).forEach(e=>{var{topic:e,selfInfo:t,code:s,message:r}=e,n=e["topicID"];0===s?(o.push(Object.assign(Object.assign({},e),{selfInfo:t})),i.push(n)):a.push({topicID:n,code:s,message:r})}),Tp.updateTopic(o),Tp.updateTopicAtInfo(o),console.log(`${this._name}.${r} groupID:${l} from remote, success count:${i.length}, fail count:`+a.length),[]);return n(i)||(Tp.setTopicRequestInfo(l,{hasFetchedAllTopics:u,time:Date.now()}),s=Tp.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 n=[];return e.forEach(e=>{var{TopicInfo:e={},SelfInfo:t={},ErrorCode:s,ErrorInfo:r}=e;n.push({code:s,message:r,topic:this._convertTopicInfo(e),selfInfo:this._convertSelfInfo(t)})}),n}_convertTopicInfo(e){var t,s,r,n,o,i,a,l,c,u,d,h=this._core["utils"]["isEmpty"];return h(e)?{}:({CreateTime:h,CustomString:e,FaceUrl:t,GroupId:s,LastMsgTime:r,NextMsgSeq:n,Introduction:o,Notification:i,ShutUpAllFlag:a,TopicId:l,TopicName:c,LastMsg:u,AtInfoList:d}=e,{createTime:h,customData:e,avatar:t,groupID:s,lastMessageTime:r,nextMessageSeq:n,introduction:o,notification:i,muteAllMembers:a,topicID:l,topicName:c,lastMsg:this._convertLastMsg(u),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:n,atInfoList:t=[]}=e;if(0===t.length)return[];let o=[];return t.forEach(e=>{var{AtFlagList:e,AtMsgSeq:t,From_Account:s}=e;o.push({groupID:r,topicID:n,groupAtType:e,sequence:t,from:s})}),o}_convertSelfInfo(e){var t,s,r,n=this._core["utils"]["isEmpty"];return n(e)?{}:({InheritGroupReceiveOption:n,MsgFlag:e,MsgSeq:t,NoUnreadSeqList:s,ShutUpTime:r}=e,{inheritGroupReceiveOption:n,messageRemindType:e,readedSequence:t,excludedUnreadSequenceList:s,muteTime:r})}},Pp=new class{constructor(){this._name="UpdateTopicHandler"}init(e){e=(this._core=e).helper;e.registerApi({apiName:"updateTopicProfile",context:this})}updateTopicProfile(o){return h(this,void 0,void 0,function*(){var t="updateTopicProfile",{isUndefined:e}=this._core["utils"],{groupID:s,topicID:r,muteAllMembers:n}=o;e(o.muteAllMembers)||(o.muteAllMembers=!0===n?"On":"Off");try{return yield function(l,c){return h(this,void 0,void 0,function*(){var{groupID:e,topicID:t,topicName:s,avatar:r,notification:n,introduction:o,customData:i,muteAllMembers:a}=l;return c.common.buildAndSendPacket({servcmd:"million_group_open_http_svc.modify_topic",data:{GroupId:e,TopicId:t,TopicName:s,FaceUrl:r,Notification:n,Introduction:o,CustomString:i,ShutUpAllMember:a}})})}(o,this._core),console.log(this._name+`.${t} ok, topicID:`+r),Tp.updateTopic([o]),{code:0,data:{topic:Tp.getTopic(s,r)}}}catch(e){throw console.error(this._name+`.${t} failed, topicID:${r} error:`,e),e}})}},Up=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(u){return h(this,void 0,void 0,function*(){let{utils:{isEmpty:e},ssoLog:t,helper:{ChatError:n}}=this._core,s=u["conversationID"],r={code:0,data:{}},o=Op(s),i=Dp(o),a=Tp.getTopic(i,o);if(console.log(this._name+`.setMessageRead topicID:${o} unreadCount:`+((null==a?void 0:a.unreadCount)||0)),a&&(e(a.groupAtInfoList)||this._deleteTopicAtTips(i,o),0!==a.unreadCount)){var l=this._getLocalMessageMaxSequence(a),c=t.createSSOLogData({method:"setMessageRead"});c.setLogInfo({message:"conversationID:"+s,moreMessage:"lastMessageSequence:"+l});try{yield this._setTopicMessageRead(i,o,l),c.end()}catch(e){let{errorCode:t,errorInfo:s}=e,r=new n({functionName:"setMessageRead",code:t,message:s});throw c.setError(r).end(),r}}return r})}_deleteTopicAtTips(o,i){return h(this,void 0,void 0,function*(){console.log(this._name+`._deleteTopicAtTips groupID:${o} topicID:`+i);let e=Tp.getTopic(o,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 n=[...r];0===(n=r.filter(e=>!e.atTypeArray.includes(s))).length?Tp.clearGroupAtInfoList(o,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:n.map(e=>({From_Account:e.from,To_Account:t(),MsgSeq:e.__sequence,MsgRandom:e.__random,GroupId:e.groupID}))},this._core),console.log(this._name+"._deleteTopicAtTips ok. count:"+r.length),Tp.clearGroupAtInfoList(o,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 n=(null==(r=null==e?void 0:e.lastMessage)?void 0:r.lastSequence)||0;return s>n&&(console.log(`${this._name}._getLocalMessageMaxSequence update lastMessageSequence from ${n} to `+s),n=s),n}_setTopicMessageRead(e,t,s){return h(this,void 0,void 0,function*(){try{yield function(r,n){return h(this,void 0,void 0,function*(){var{groupID:e,topicID:t,lastMessageSequence:s}=r;return n.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),Tp.updateSelfInfo({groupID:e,topicID:t,selfInfo:{readedSequence:s}}),Tp.markMessageAsRead(t,s),Tp.updateUnreadCount(e,t)}catch(e){throw console.error(this._name+"._setTopicMessageRead fail:",e),e}})}},kp=new class{init(e){console.log("TopicAction.init"),Np.init(e),bp.init(e),Gp.init(e),wp.init(e),Pp.init(e),Up.init(e)}};let Fp={required:!0,rules:["string"],allowEmpty:!1},$p={createTopicInCommunity:{groupID:Fp,topicName:Fp},deleteTopicFromCommunity:{groupID:Fp,topicIDList:{required:!1,rules:["array"],allowEmpty:!0}},getTopicList:{groupID:Fp,topicIDList:{required:!1,rules:["array"],allowEmpty:!0}},updateTopicProfile:{groupID:Fp,topicID:Fp}},qp={getJoinedCommunityList:!0,createTopicInCommunity:!0,deleteTopicFromCommunity:!0,getTopicList:!0,updateTopicProfile:!0};var Kp,xp=new class{constructor(){this.name="Topic"}install(e){pp.init(e),Tp.init(e),Rp.init(e),Lp.init(e),kp.init(e),e.helper.registerValidateConfig({auth:qp,params:$p})}};function Vp(e,t){return Math.round(Number(e)*Math.pow(10,t))/Math.pow(10,t)}let Bp="qualityStat",jp="im-ssolog-quality-stat",Wp=(!function(e){e[e.ONLINE=8]="ONLINE"}(Kp=Kp||{}),"networkRTT"),Hp="messageE2EDelay",Yp="sendMessageC2C",zp="sendMessageGroup",Jp="sendMessageGroupAV",Qp="sendMessageRichMedia",Xp="cosUpload",Zp="messageReceivedGroup",eh="messageReceivedGroupAVPush",th="messageReceivedGroupAVPull",sh={[Wp]:2,[Hp]:3,[Yp]:4,[zp]:5,[Jp]:6,[Qp]:7,[Zp]:8,[eh]:9,[th]:10,[Xp]:11},oh=[Yp,zp,Jp,Qp,Xp],nh=[Zp,eh,th],ih=[Wp,Hp,Yp,zp,Jp,Qp,Xp,Zp,eh,th],rh={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},ah="quality_stat";var ch=new class{constructor(){this._messageStatsMap=new Map,this._userSideErrorCodes=new Set(Object.values(rh))}init(e){this._core=e,Object.values(oh).forEach(e=>{this._messageStatsMap.set(e,{totalCount:0,successCount:0,failedCountOfUserSide:0,costSum:0,costCount:0,fileSizeSum:0})})}dispatchSendStats(e){var{name:e,message:t,error:s,startTs:r}=e,n=this._core.constants["SEND_MESSAGE_STAT"];switch(e){case n.TOTAL_COUNT:this._handleTotalCount(t);break;case n.SUCCESS_COUNT:this._handleSuccessCount(t);break;case n.FAILED_COUNT:this._handleFailedCount(t,s);break;case n.SEND_COST:this._handleSendCost(t,r)}}getStatResult(e){var t,s,r,n,o,i=this._messageStatsMap.get(e);return i&&0!==i.totalCount?({totalCount:t,successCount:s,failedCountOfUserSide:n}=i,r=Vp(s/t*100,2),o=Vp((n=s+n)/t*100,2),i=this._calcAverageValue(i,e),this._resetStat(e),{total_count:t,success_count_business:s,percent_business:r,success_count_platform:n,percent_platform:o,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:n,CONV_C2C:o,CONV_GROUP:i,GRP_AVCHATROOM:a}=this._core.OuterConstant;if([e,t,r,n].includes(s.type))return Qp;if(s.conversationType===o)return Yp;if(s.conversationType===i){let e=this._core.appStore["groupStore"],t=e.getGroup(s.to);if(t){let e=t["type"];return e===a?Jp:zp}}}_calcAverageValue(e,t){return 0===e.costCount?0:t===Xp?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)}},uh=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(Bp+".addMessageSequence invalid key:",t):({conversationID:s,sequence:e}=e,s=s.replace(r,""),0!==(r=this._lastCycleStats.get(t)).size&&r.has(s)&&e>(r=r.get(s)).minSeq&&e<r.maxSeq?this._insertToLastCycle(e,r):this._addToCurrentCycle(t,s,e))}getStatResult(e){var t=this._lastCycleStats.get(e);if(!t||0===t.size)return this._transferCycleDataOptimized(e),null;let r=0,n=0;return t.forEach(e=>{var{sortedSequences:e,minSeq:t,maxSeq:s}=e;0<e.length&&(n+=e.length,r+=s-t+1)}),0===r?null:(this._transferCycleDataOptimized(e),{total_count:r,success_count_business:n,percent_business:Vp(n/r*100,2)})}reset(){this._lastCycleStats.clear(),this._currentCycleStats.clear()}dispose(){var{notificationCenter:e,OuterEvent:{MESSAGE_RECEIVED:t}}=this._core;e.unSubscribeOuterEvent(t,this._onMessageReceived,this),this.reset()}_initStatsMap(){Object.values(nh).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?th:Zp):null}}_insertToLastCycle(e,t){t.dirty&&(t.sortedSequences.sort((e,t)=>e-t),t.dirty=!1);var s=this._findInsertPos(t.sortedSequences,e);t.sortedSequences.splice(s,0,e),t.minSeq=Math.min(t.minSeq,e),t.maxSeq=Math.max(t.maxSeq,e)}_findInsertPos(e,t){let s=0,r=e.length-1;for(;s<=r;){var n=Math.floor((s+r)/2);if(e[n]===t)return n;e[n]<t?s=n+1:r=n-1}return s}_addToCurrentCycle(e,t,s){let r=this._currentCycleStats.get(e).get(t);r?(r.sortedSequences.push(s),r.minSeq=Math.min(r.minSeq,s),r.maxSeq=Math.max(r.maxSeq,s),r.dirty=!0):(r={sortedSequences:[s],minSeq:s,maxSeq:s,dirty:!1},this._currentCycleStats.get(e).set(t,r))}},lh=new class{constructor(){this._totalDelay=0,this._totalCount=0,this._countLessThan1s=0,this._countLessThan3s=0}init(e){var{OuterEvent:{MESSAGE_RECEIVED:e},notificationCenter:t}=this._core=e;t.subscribeOuterEvent(e,this._onMessageReceived,this)}addMessageDelay(e){var t=this._core.common["timeManager"],t=t.getServerTimeSeconds()-e;0<t&&(this._totalDelay+=t,this._totalCount++,t<=1?this._countLessThan1s++:t<=3&&this._countLessThan3s++)}getStatResult(){var e;return 0===this._totalCount?null:(e={total_count:this._totalCount,success_count_business:this._countLessThan1s,success_count_platform:this._countLessThan3s,percent_business:this._calculatePercentage(this._countLessThan1s,this._totalCount),percent_platform:this._calculatePercentage(this._countLessThan3s,this._totalCount),average_value:this._calculateAverageDelay(this._totalCount)},this.reset(),e)}reset(){this._totalDelay=0,this._totalCount=0,this._countLessThan1s=0,this._countLessThan3s=0}dispose(){var{notificationCenter:e,OuterEvent:{MESSAGE_RECEIVED:t}}=this._core;e.unSubscribeOuterEvent(t,this._onMessageReceived,this),this.reset()}_onMessageReceived(e){let{data:t=[]}=e,{MSG_GRP_TIP:s,MSG_GRP_SYS_NOTICE:r}=this._core["OuterConstant"],n=[s,r];t.forEach(e=>{!n.includes(e.type)&&0<e.clientTime&&this.addMessageDelay(e.clientTime)})}_calculateAverageDelay(e){return 0===e?0:Vp(this._totalDelay/e,1)}_calculatePercentage(e,t){return Vp(e/t*100,2)}},dh=new class{init(e){this.core=e}},ph=new class{constructor(){this.name="MessageQualityStat",this._reportIndex=0,this._wholePeriod=!1,this._pendingReports=[],this._failedLogsCache=new Map}install(e){var{helper:t,notificationCenter:s,InnerEvent:{QUALITY_STAT:r,LOGOUT:n,DESTROY:o},constants:{WORKFLOW_NAME:i,WORKFLOW_STEP:a}}=this._core=e;dh.init(e),ch.init(e),uh.init(e),lh.init(e),t.registerWorkflowStep(i.SYNC_SERVER_INFO_AFTER_LOGIN,a.QUALITY_REPORT,this.handleLoginSuccess,this),s.subscribeInnerEvent(r,this._handleQualityStat,this),s.subscribeInnerEvent(n,this._reset,this),s.subscribeInnerEvent(o,this._dispose,this)}handleLoginSuccess(){console.log(Bp+".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:ah,intervalMs:s,callback:this.report,context:this})}report(){this._wholePeriod=!0;var e=[...ih.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&&ch.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:sh[e],timestamp:Date.now(),network_type:Kp.ONLINE,extension:""},Object.assign(Object.assign({},e),t))}_getStatResultByKey(e){switch(e){case Hp:return lh.getStatResult();case Yp:case zp:case Jp:case Qp:case Xp:return ch.getStatResult(e);case Zp:case eh:case th:return uh.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}=dh.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=Bp+"._cacheFailedLogs";let s=[...this._failedLogsCache.get(jp)||[],...e];10<s.length&&(s=s.slice(s.length-10),console.log(t+" logs overflow, keeping last 10 items")),this._failedLogsCache.set(jp,s),console.log(t+" count: "+s.length),this._pendingReports=[]}_reset(){var e=this._core["helper"];e.taskScheduler.removeTask(ah)}_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(),lh.dispose(),uh.dispose()}};let hh=1,gh=300;var _h=new class{constructor(){this.name="OfflineMessageSynchronizer",this._lastMessageSequenceMapOnDisconnect=new Map}install(e){var{common:{workflowManager:t},constants:{WORKFLOW_NAME:s,WORKFLOW_STEP:r,InnerEvent:n}}=this._core=e;t.registerWorkflowStep(s.SYNC_SERVER_INFO_AFTER_RE_ONLINE,r.HISTORY_MESSAGE_RECOVER,this._syncOfflineMessage,this),e.notificationCenter.subscribeInnerEvent(n.SOCKET_DISCONNECTED,this._updateLastMessageSequenceMapOnDisconnect,this)}_syncOfflineMessage(e){let t=((null==e?void 0:e.result)||{})["conversationList"],{OuterConstant:s,utils:{isArray:r}}=this._core;if(r(t)){let e=t.filter(e=>e.type===s.CONV_GROUP&&e.groupProfile.type!==s.GRP_AVCHATROOM);return this._recoverGroupHistoryMessage(e)}}_recoverGroupHistoryMessage(e){return h(this,void 0,void 0,function*(){let n=this._core["OuterConstant"],o=[],i=[];return yield Promise.all(null==e?void 0:e.map(r=>h(this,void 0,void 0,function*(){var{groupProfile:{groupID:e}={},lastMessage:{lastSequence:t}={}}=r,e=""+n.CONV_GROUP+e,s=this._getLocalLastMessageSequence(e);this._shouldRecoverHistory({localLastMessageSequence:s,serverLastMessageSequence:t})&&(yield this._recoverHistoryForConversation({conversationID:e,localLastMessageSequence:s,serverLastMessageSequence:t,groupTipList:i})),o.push(e.replace(n.CONV_GROUP,""))}))),{recoverRevokeNoticeGroupIDList:o,groupTipList:i}})}_recoverHistoryForConversation(e){return h(this,arguments,void 0,function*({conversationID:I,localLastMessageSequence:S,serverLastMessageSequence:E,groupTipList:C}){try{let{utils:{isArray:e,isObject:t,isEmpty:s},OuterEvent:r,OuterConstant:n,notificationCenter:o,message:i,appStore:a,common:{getMessagePreviewText:l}}=this._core,c=E-S,u=Math.min(20,c),d={},h=yield i.messageHistory.getGroupRoamingMessagesByAnchor({conversationID:I,sequence:S+u,direction:n.Direction.FORWARD,count:u}),{nextReqMessageIDFromServer:p,hasNoMoreHistoryMessage:g,messageList:_,serverGroupTipList:m}=h,v=(e(m)&&C.push(...m),g&&p<0),f=[];if(e(_)&&(_.forEach(e=>{i.messageReceiver.groupMessageReceiver.updateMessageProfile(e),e.from===n.CONV_SYSTEM&&(e.isSystemMessage=!1),i.messageDataHandler.storeConversationMessage(e)&&!s(e.payload)&&(f.push(e),e._isExcludedFromLastMessage||(d.lastMessage=Object.assign({},e)))}),0<f.length)&&o.emitOuterEvent(r.MESSAGE_RECEIVED,{name:r.MESSAGE_RECEIVED,data:f}),!v&&0<_.length){let e=_[_.length-1].sequence;yield this._recoverHistoryForConversation({conversationID:I,localLastMessageSequence:e,serverLastMessageSequence:E,groupTipList:C})}t(d.lastMessage)&&(d.lastMessage.messageForShow=l(d.lastMessage.type,d.lastMessage.payload),a.conversationStore.updateConversation(I,d))}catch(S){console.debug("Recovery failed for conversation:",I,S)}})}_updateLastMessageSequenceMapOnDisconnect(){let e=this._core["message"],r=e.messageDataHandler.getContinuousMessagesByConversation();for(let[t,s]of r)if(!t.startsWith("C2C")){let e=Array.from(s.values());var n;0<(null==e?void 0:e.length)&&(n=e[e.length-1].sequence,this._lastMessageSequenceMapOnDisconnect.set(t,n))}}_getLocalLastMessageSequence(e){var t=this._core["message"];return this._lastMessageSequenceMapOnDisconnect.has(e)?this._lastMessageSequenceMapOnDisconnect.get(e):null==(e=(t=t.messageDataHandler.getLocalMessageList(e))[t.length-1])?void 0:e.sequence}_shouldRecoverHistory(e){var t,{localLastMessageSequence:e,serverLastMessageSequence:s}=e;return"number"==typeof e&&"number"==typeof s&&(t=s-e,0!==s)&&0<e&&t>=hh&&t<gh}};let mh=ms.STANDARD,vh=[];mh=ms.PROFESSIONAL,vh=[yo,Mo,Do,ko,qo,ph,_h,Ci,Or,ca,Ou,rl,Rd,_n,zl,ld,dp,xp];var fh=Object.freeze({__proto__:null,ChatError:$s,WorkflowManager:Js,buildAndSendPacket:so,get builtInPlugins(){return vh},checkBusinessCapabilityBits:zs,deepMerge:co,getCurrentUserID:ro,getErrorMessage:Fs,getMessagePreviewText:uo,isC2CConv:e=>_(e)&&e.slice(0,3)===as.CONV_C2C,isCommunity:Xs,isGroupConv:e=>_(e)&&e.slice(0,5)===as.CONV_GROUP,isTopic:Zs,isUnlimitedAVChatRoom:function(){var e;return!(null==(e=Bt.store.get("instance"))||!e.unlimitedAVChatRoom)},liteChatInstanceMap:Qs,registerInterceptor:Hs,registerValidateConfig:Ys,requireAuth:qs,get sdkEdition(){return mh},updateGroupAtInfo:(t,s)=>{var{CONV_AT_ME:r,CONV_AT_ALL:n,CONV_AT_ALL_AT_ME:o}=gs;if(!function(t,e){let{CONV_AT_ME:s,CONV_AT_ALL:r,CONV_AT_ALL_AT_ME:n}=gs,{groupID:o,sequence:i}=t,a=!1;return Xs({groupID:o})&&e.forEach(e=>{e.messageSequence===i&&(e.atTypeArray.includes(s)&&t.groupAtType.includes(r)&&(e.atTypeArray=[n]),e.atTypeArray.includes(r)&&t.groupAtType.includes(s)&&(e.atTypeArray=[n],e.__random=t.__random,e.__sequence=t.__sequence),a=!0)}),a}(t,s)){let e=[...t.groupAtType];e.includes(r)&&e.includes(n)&&(e=[o]);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:Ws,validateParameters:xs});class Ih{constructor(){this._builtInPlugins=new Set,this._externalPlugins=new Set}static getInstance(){return Ih._instance||(Ih._instance=new Ih),Ih._instance}static setInstance(e){Ih._instance=e}installBuiltInPlugin(e){e&&this._installPlugin(e,this._builtInPlugins)}installExternalPlugin(e){e&&this._installPlugin(e,this._externalPlugins)}clear(){this._builtInPlugins=new Set,this._externalPlugins=new Set}_installPlugin(e,t){var s=[];let r=(s=v(e)?e:[e]).findIndex(e=>"AVChatRoom"===(null==e?void 0:e.name)),n=-1<r?s.splice(r,1):[];s.forEach(e=>{this._isPluginInstalled(e.name)||(e&&jt(e.install)?(t.add(e.name),jt(e.getInstalledSubPlugins)?e.install(Ah.getInstance().exposeApiForPlugin(),n):e.install(Ah.getInstance().exposeApiForPlugin()),jt(e.handleLoginSuccess)&&this._isLoggedIn()&&e.handleLoginSuccess()):jt(e)?(t.add(e.name),e(Ah.getInstance().exposeApiForPlugin()),jt(e.handleLoginSuccess)&&this._isLoggedIn()&&e.handleLoginSuccess()):console.warn('A plugin must either be a function or an object with an "install" function.'))})}_isPluginInstalled(e){return this._builtInPlugins.has(e)||this._externalPlugins.has(e)}_isLoggedIn(){var e;return!0===(null==(e=Bt.store.get("login"))?void 0:e.isLoggedIn)}}var Lh,Nh,bh,Uh,Sh=new class{constructor(){this._conversationMap=new Map}getConversationMap(){return this._conversationMap}getConversation(e){return this._conversationMap.get(e)}updateConversation(e,t,s={emit:!0,needSort:!1}){let{emit:r,needSort:n}=s,o=this._conversationMap.get(e);o&&!me(t)&&(Object.keys(t).forEach(e=>{o[e]=t[e]}),r)&&Bt.notificationCenter.emitInnerEvent(Jt.CONVERSATION_UPDATED,{needSort:n})}deleteConversation(e){this._conversationMap.has(e)&&(this._conversationMap.delete(e),Bt.notificationCenter.emitInnerEvent(Jt.CONVERSATION_UPDATED))}},Eh=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]})}},Ch=new class{constructor(){this._messagesByConversation=new Map}updateMessage(s,t,e){let r,{operation:n,updateUnreadCount:o=!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(n,{conversationID:s,messageList:a,updateUnreadCount:o}),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"];Zs(s)?Bt.notificationCenter.emitInnerEvent(ns[e],t):Bt.notificationCenter.emitInnerEvent(e,t)}},Mh=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)}},yh=Object.freeze({__proto__:null,conversationStore:Sh,groupStore:Eh,messageStore:Ch,userStore:Mh});class Ah{static getInstance(){return Ah._instance||(Ah._instance=new Ah),Ah._instance}static setInstance(e){Ah._instance=e}constructor(){this._experimentalApiMap={statTUIKeyFeatures:this.statKeyFeatureUsage.bind(this)},this._apiHandlersMap={},this._apiMap={on:Bt.notificationCenter.subscribeOuterEvent.bind(Bt.notificationCenter),off:Bt.notificationCenter.unSubscribeOuterEvent.bind(Bt.notificationCenter),destroy:this.destroy.bind(this),callExperimentalAPI:this.callExperimentalAPI.bind(this),use:Ih.getInstance().installExternalPlugin.bind(Ih.getInstance()),registerPlugin:this.registerPlugin.bind(this),setLogLevel:this.setLogLevel.bind(this)}}registerPlugin(e){console.log("registerPlugin",e)}statKeyFeatureUsage(e){console.log("statTUIKeyFeatures",e)}setLogLevel(e){console.log("setLogLevel",e),!Bt||"function"!=typeof Bt.setLogLevel||null!=Bt&&Bt.setLogLevel(e)}getApiMap(){return this._apiMap}setApiMap(e){this._apiMap=e}registerApi(e){let{apiName:r,context:t,methodName:n=r,matcher:s}=e;this._apiHandlersMap[r]||(this._apiHandlersMap[r]=[]),this._apiHandlersMap[r].push({context:t,methodName:n,matcher:s}),this._apiMap[r]&&1!==this._apiHandlersMap[r].length||(this._apiMap[r]=(...t)=>{Ws(n,t);var s=this._apiHandlersMap[r];for(let e of s)if(!e.matcher||e.matcher(t))return e.context[e.methodName].bind(e.context)(...t)})}registerExperimentalAPI(e,t,s){this._experimentalApiMap[e]=t[s||e].bind(t)}destroy(){return h(this,void 0,void 0,function*(){var e,t;try{null!=(e=Bt.store.get("login"))&&e.isLogin&&(yield this._apiMap.logout()),Bt.notificationCenter.emitInnerEvent(Jt.DESTROY)}catch(e){console.debug("destroy error: ",e)}finally{Bt.notificationCenter.emitOuterEvent(Yt.SDK_DESTROY,{SDKAppID:null==(t=Bt.store.get("instance"))?void 0:t.sdkAppId}),Qs.clear(),Ih.getInstance().clear(),Js.getInstance().destroy(),Bt.destroy()}})}exposeApiForClient(){return this._apiMap}exposeApiForPlugin(){return Object.assign(Object.assign({InnerEvent:Jt,InnerEventSubType:Bt.notificationCenter.InnerEventSubType,OuterEvent:Yt,OuterConstant:gs,SignalingEvent:Qt,helper:Object.assign(Object.assign(Object.assign({},Bt.utils),Bt.common),{registerApi:this.registerApi.bind(this),registerExperimentalAPI:this.registerExperimentalAPI.bind(this),registerInterceptor:Hs,registerValidateConfig:Ys,checkBusinessCapabilityBits:zs,registerWorkflowStep:Js.getInstance().registerWorkflowStep.bind(Js.getInstance()),ChatError:$s}),apiMap:this._apiMap},Bt),{constants:Object.assign(Object.assign({},Cs),Bt.constants),common:Object.assign(Object.assign(Object.assign({},fh),Bt.common),{workflowManager:Js.getInstance()}),utils:Bt.utils,appStore:yh})}callExperimentalAPI(e,t){return this._experimentalApiMap[e]?this._experimentalApiMap[e](t):Promise.reject(new $s({code:_s.INVALID_OPERATION}))}}class Th{constructor(){this._latestLoginAt=0,this._latestSendOnlinePresenceRequestTime=0,this._helloInterval=120}init(){var{notificationCenter:e,store:t}=Bt;t.set("login",{isReady:!1}),Ah.getInstance().registerApi({apiName:"login",context:this}),Ah.getInstance().registerApi({apiName:"logout",context:this}),Ah.getInstance().registerApi({apiName:"getLoginUser",context:this}),Ah.getInstance().registerApi({apiName:"isReady",context:this}),e.subscribeInnerEvent(Jt.RECONNECTED,this._reLogin,this),Bt.notificationCenter.subscribeInnerEvent(Jt.DESTROY,this._dispose,this)}login(s){return h(this,void 0,void 0,function*(){let e=this._getUiPlatform(),t=(Bt.store.get("instance")||{})["sdkEdition"],r=Bt.ssoLog.createSSOLogData({method:"login",eventType:4,uiPlatform:e,message:t});try{if(this._isLoginIn())return this._createRepeatLoginResponse();if(this._isLoginFrequencyExceeded())throw new $s({functionName:"login",code:_s.REPEAT_LOGIN});let e=yield this._performLogin(s);return this._validateAfterLogin(e),this._handleLoginSuccess(e),yield this._ensureAsyncComplete(),this._updateAndEmitSDKReady(),{code:this._latestLoginAt=0,data:e}}catch(e){let t=e["errorCode"],s=(t!==_s.REPEAT_LOGIN&&(this._latestLoginAt=0),new $s({functionName:"login",code:t}));throw r.setError(s).end(!0),s}})}_getUiPlatform(){var e,t=Bt["store"],t=null==(e=t.get("instance"))?void 0:e.scene;if("string"==typeof t){let e=Number(t);return isNaN(e)?void 0:e}}_reLogin(){return h(this,void 0,void 0,function*(){var e,t,s,r,n,o;try{this._isLoginIn()&&(t=Bt.ssoLog.createSSOLogData({method:"reLogin"}),s=yield ks())&&({instanceID:r,customStatus:n}=s,Bt.store.set("login",{statusInstanceId:r}),Js.getInstance().executeWorkflow(vs.SYNC_SERVER_INFO_AFTER_RE_ONLINE,{customStatus:n,statusType:is.USER_STATUS_ONLINE}),o=`socketId:${null==(e=Bt.channel.getSocketAdapter())?void 0:e.getId()} instanceId:`+r,t.setLogInfo({message:o}).end(!0))}catch(e){console.warn(e)}})}logout(){return h(this,arguments,void 0,function*(s=Ms.USER_INITIATED){let e=Bt.ssoLog.createSSOLogData({method:"logout"});e.setLogInfo({moreMessage:"identifier:"+ro()});try{yield this._performLogout(s),e.end(!0),Bt.ssoLog.uploadSSOLogData()}catch(s){let e=s["errorCode"],t=new $s({functionName:"logout",code:e});this._handleLogoutError(t)}finally{this._handleLogoutCompleted()}return{code:0,data:{}}})}getLoginUser(){return this._isLoginIn()?ro():""}isReady(){var e;return null==(e=Bt.store.get("login"))?void 0:e.isReady}_updateAndEmitSDKReady(){Bt.store.set("login",{isReady:!0}),setTimeout(()=>{Bt.notificationCenter.emitOuterEvent(Yt.SDK_READY,{name:Yt.SDK_READY})},1)}_updateAndEmitSDKNotReady(){Bt.store.set("login",{isReady:!1}),Bt.notificationCenter.emitOuterEvent(Yt.SDK_NOT_READY,{name:Yt.SDK_NOT_READY})}_validateAfterLogin(e){var t,s="login";if(!e)throw new $s({functionName:s,message:"login response is empty"});var{tinyID:e,a2Key:r}=e||{},n=Bt.ssoLog.getSSOLogData(s);if(!e){let e=new $s({functionName:s,code:_s.NO_TINYID});throw null!=(t=null==n?void 0:n.setError)&&t.call(n,e).end(),e}if(!r){let e=new $s({functionName:s,code:_s.NO_A2KEY});throw null!=(t=null==n?void 0:n.setError)&&t.call(n,e).end(),e}}_createRepeatLoginResponse(){var e;return{code:0,data:{actionStatus:"OK",errorCode:0,errorInfo:Fs({code:"RepeatLogin",replacement1:null==(e=Bt.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 Bt.store.set("login",{userId:e,userSig:t}),this._latestLoginAt=Date.now(),ks()})}_ensureAsyncComplete(){return h(this,void 0,void 0,function*(){yield new Promise(e=>{setTimeout(()=>e(null),1)})})}_handleLoginSuccess(e){var t=Bt.common["timeManager"],{helloInterval:s,timeStamp:r,customStatus:n,purchaseBits:o}=e;t.calculateTimeOffsetWithServer(this._latestLoginAt,1e3*r),this._helloInterval=s||120,this._updateLoginStore(e),Bt.user.userStatus.setCustomStatus(n),Js.getInstance().executeWorkflow(vs.SYNC_SERVER_INFO_AFTER_LOGIN,{purchaseBits:o}),Bt.common.taskScheduler.addTask({id:Os,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=Bt.common.generateProtocolData({servcmd:t,data:{wslogout_type:e,isWebUniapp:0}}),t=e.head.seq+t;return yield Bt.channel.sendPacket(e,{requestId:t})})}({logoutReason:e})}_handleLogoutError(e){Bt.ssoLog.getSSOLogData("logout").setError(e).end(),console.error("logout "+e)}_handleLogoutCompleted(){this._updateAndEmitSDKNotReady(),this._reset(),Js.getInstance().reset(),Bt.notificationCenter.emitInnerEvent("logout")}_updateLoginStore(e){var{a2Key:e,tinyID:t,instanceID:s,authKey:r}=e;Bt.store.set("login",{a2Key:e,tinyID:t,statusInstanceId:s,authKey:r,isLoggedIn:!0})}_logLoginSuccess(e){var t=Bt.ssoLog.getSSOLogData("login"),{helloInterval:e,instanceID:s,timeStamp:r,customStatus:n}=e,o=null==(o=Bt.channel.getSocketAdapter())?void 0:o.getId(),i=Bt.common.timeManager.getTimeOffsetWithServer(),{appId:a,href:l}=Bt.store.get("instance")||{},o=`login._logLoginSuccess socketID:${o} scene: helloInterval:${e} instanceID:${s}
|
|
4
|
+
timeStamp:${r} offset:${i} customStatus:${n} href: ${l} appId: `+a;console.log("login ok. "+o),t.updateLogCreatedAtByTimeOffset(),t.setLogInfo({moreMessage:o}).end()}_sendOnlinePresenceRequest(){return h(this,void 0,void 0,function*(){this._latestSendOnlinePresenceRequestTime=Date.now();try{e="im_open_status.wshello",t=Bt.common.generateProtocolData({servcmd:e,data:{isWebUniapp:0}}),e=t.head.seq+e,yield Bt.channel.sendPacket(t,{requestId:e})}catch(e){console.warn("Login._sendOnlinePresenceRequest error:",e)}var e,t})}_isLoginIn(){var e;return!0===(null==(e=Bt.store.get("login"))?void 0:e.isLoggedIn)}_isLoginFrequencyExceeded(){return Date.now()-this._latestLoginAt<=15e3}_reset(){console.log("Login reset"),Bt.common.taskScheduler.removeTask(Os),this._helloInterval=120,this._latestSendOnlinePresenceRequestTime=0,this._latestLoginAt=0,Bt.store.clear("login"),Bt.store.set("login",{isReady:!1})}_dispose(){console.log("Login dispose"),this._reset();var e=Bt["notificationCenter"];e.unSubscribeInnerEvent(Jt.RECONNECTED,this._reLogin,this),e.unSubscribeInnerEvent(Jt.DESTROY,this._dispose,this)}}let Oh={login:{userID:{required:!0,rules:["string"],allowEmpty:!1},userSig:{required:!0,rules:["string"],allowEmpty:!1}}},Dh={logout:!0};class Rh{constructor(){this.loginAction=new Th,this.kickedOutHandler=new Us,this.loginAction.init(),this.kickedOutHandler.init(),Ys({auth:Dh,params:Oh})}}!function(e){e.CONV_C2C="C2C",e.CONV_GROUP="GROUP",e.CONV_TOPIC="TOPIC",e.CONV_SYSTEM="@TIM#SYSTEM"}(Lh=Lh||{}),function(e){e.MSG_PRIORITY_HIGH="High",e.MSG_PRIORITY_NORMAL="Normal",e.MSG_PRIORITY_LOW="Low",e.MSG_PRIORITY_LOWEST="Lowest"}(Nh=Nh||{}),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"}(bh=bh||{});let Gh={1:Nh.MSG_PRIORITY_HIGH,2:Nh.MSG_PRIORITY_NORMAL,3:Nh.MSG_PRIORITY_LOW,4:Nh.MSG_PRIORITY_LOWEST},wh=0,Ph=1,kh=(!function(e){e.IN="in",e.OUT="out"}(Uh=Uh||{}),2),Fh={};function $h(e){var t,s,r;return e?(void 0===Fh[e]?(t=("3"+(r=new Date).getHours()).slice(-2),s=("0"+r.getMinutes()).slice(-2),r=("0"+r.getSeconds()).slice(-2),Fh[e]=parseInt([t,s,r,"0001"].join(""),10),console.log("autoIncrementIndex start index:"+Fh[e])):Fh[e]+=1,Fh[e]):0}class qh{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=Nh.MSG_PRIORITY_NORMAL,this._relayFlag=!1;var t,{clientTime:s=Bt.common.timeManager.getServerTimeSeconds()||0,senderTinyID:r,currentUser:n,needReadReceipt:o,isSupportExtension:i,customModerationConfigurationId:a,to:l,from:c,nick:u="",avatar:d="",time:h,messageControlInfo:p,tinyID:g,cloudCustomData:_="",messageLifeTime:m,messageVersion:v=0,conversationType:f,sequence:I,checkResult:S=0,isPlaceMessage:E=0,messageFlagBits:C,receiverList:M,isSystemMessage:y=!1,status:A=es.SUCCESS,revokeReason:T="",conversationSubType:O,clientSequence:D,protocol:L="JSON",revokerInfo:R={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||g,this.needReadReceipt=!0===o||1===o,this.isSupportExtension=!0===i||1===i,this._cmConfigID=a,this.to=l,this.nick=u,this.avatar=d,this.protocol=L,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=_,this.messageLifeTime=m,this.from=c||null,this.sequence=I||0,this.conversationType=f||Lh.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=R,this._receiverList=M,this.conversationSubType=O,this.revoker=(null==R?void 0:R.revoker)||"",this.clientSequence=D||I||0,this.status=A,this.atUserList=w||[],this.flow=P,this.isRead=U,this.reInitialize(n),this._initC2CReadReceiptInfo(e),this._extractGroupInfo(G)}getElements(){return this._elements}isOnlineMessage(){return 0===this.messageLifeTime}setElement(e){Array.isArray(e)?this._elements=e:this._elements=[e],this._updatePayloadAndType()}transformElementsToServerFormat(){return this._elements?Array.isArray(this._elements)?this._elements.map(e=>e.transformToServerFormat()):this._elements.transformToServerFormat():null}setRelayFlag(e){this._relayFlag=e}validateBeforeSend(){var e,t;return this._relayFlag?{isValid:!0}:0<(null==(e=this._elements)?void 0:e.length)?null==(t=null==(e=this._elements[0])?void 0:e.validateBeforeSend)?void 0:t.call(e):{isValid:!1}}_updatePayloadAndType(){this._elements[0]&&(this.payload=this._elements[0].content,this.type=this._elements[0].type)}_initC2CReadReceiptInfo(e){var{readReceiptSentByPeer:e,timestamp:t=0}=e;this.conversationType===Lh.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!==Lh.CONV_SYSTEM?(e=t!==Lh.CONV_C2C||e===this.from?this.to:this.from,this.conversationID=e?""+t+e:null):this.conversationID=Lh.CONV_SYSTEM}_initSequence(e){0===this.clientSequence&&e&&(this.clientSequence=$h(e)),0===this.sequence&&this.conversationType===Lh.CONV_C2C&&(this.sequence=this.clientSequence)}generateMessageID(){this.from===Lh.CONV_SYSTEM&&(this.senderTinyID="144115198244471703"),this.ID=`${this.senderTinyID}-${this.clientTime}-`+this.random}setIsRead(e){this.isRead=e}}class xh{static parseServerPushElement(e){var{MsgContent:e={}}=e,{Data:e,Ext:t,Desc:s}=e;return new xh({data:e,description:s,extension:t})}constructor(e){this.type=bh.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=Bt.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 Vh{static parseServerPushElement(e){var{MsgContent:e={Text:""}}=e,e=e["Text"];return new Vh({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}}}}var Bh=new class{constructor(){this._elementClassMap={[bh.MSG_CUSTOM]:xh,[bh.MSG_TEXT]:Vh}}init(){Ah.getInstance().registerApi({apiName:"createCustomMessage",context:this}),Ah.getInstance().registerApi({apiName:"createTextMessage",context:this})}registerElementClass(e,t){void 0!==t.prototype&&"constructor"in t.prototype&&(this._elementClassMap[e]=t)}getElementClass(e){return this._elementClassMap[e]}createMessage(e){var{from:t,flow:s=Uh.OUT}=e,r=(Bt.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=Uh.OUT),Object.assign(Object.assign({},e),{currentUser:r}));return new qh(t)}createCustomMessage(t){let e=ro(),s=this.createMessage(Object.assign(Object.assign({},t),{from:e})),r=this._elementClassMap[bh.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 Vh({text:t}),s=ro(),(e=Bt.message.messageFactory.createMessage(Object.assign(Object.assign({},e),{from:s}))).setElement(t),e):null}_updateWithSenderInfo(e){var{nick:t,avatar:s}=e,{userId:r,tinyID:n}=Bt.store.get("login")||{},o=Mh.getUserProfile(r);return e.nick=t||(null==o?void 0:o.nick)||"",e.avatar=s||(null==o?void 0:o.avatar)||"",e.tinyID=e.tinyID||n||"",e.from=r,e.status=es.UNSENT,e.flow=Uh.OUT,e}_isMultiEndpointSyncMessage(e){var{from:e,flow:t,currentUser:s}=e;return e===s&&t===Uh.IN}_isSendByCurrentInstance(e){var{from:e,flow:t,currentUser:s}=e;return e===s&&t===Uh.OUT}};let jh={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}},Kh={HonorImportance:{range:["LOW","NORMAL"],defaultValue:void 0},MeizuNotifyType:{range:[0,1],defaultValue:void 0}},Wh={enableIOSBackgroundNotification:{range:[!0,!1],defaultValue:!1},interruptionLevel:{range:["passive","active","time-sensitive","critical"],defaultValue:"active"}};function Hh(r,n){return Object.keys(n).forEach(e=>{var{range:t,defaultValue:s}=n[e];r[e]=t.includes(r[e])?r[e]:s}),r}function Yh(e){var t=e.lastIndexOf(".");return-1===t?e:e.slice(0,t)}function zh(e){var{androidInfo:e={},androidOPPOChannelID:t=""}=e,t=e.OPPOChannelID||t,e=Hh(e,Kh),{sound:s="",FCMChannelID:r=""}=e,e=p(e,["sound","FCMChannelID"]);return Object.assign(Object.assign({},e),{Sound:Yh(s),OPPOChannelID:t,GoogleChannelID:r})}function Jh(e){var{apnsInfo:e={},ignoreIOSBadge:t=!1,disableVoipPush:s}=e,e=Hh(e,Wh),{ignoreIOSBadge:r,disableVoipPush:n,enableIOSBackgroundNotification:o}=e,e=p(e,["ignoreIOSBadge","disableVoipPush","enableIOSBackgroundNotification"]),r=!0===r||!0===t?1:0;let i;return g(s)||(i=!1===s?1:0),g(n)||(i=!1===n?1:0),Object.assign(Object.assign({},e),{BadgeMode:r,IsVoipPush:i,ContentAvailable:o?1:0})}function Qh(e){return Bt.utils.isPlainObject(e)?{PushFlag:!0===e.disablePush?1:0,Title:e.title||"",Desc:e.description||"",Ext:e.extension||"",ApnsInfo:Jh(e),AndroidInfo:zh(e)}:jh}function Xh(e){let{From_AccountHeadurl:t,From_AccountNick:s,IsNeedReadReceipt:r,IsPeerRead:n,IsSyncMsg:o,MsgBody:i,MsgClientTime:a,MsgLifeTime:l,MsgRandom:c,MsgSeq:u,MsgTimeStamp:d,SendMsgControl:h,SupportMessageExtension:p,TinyId:g,MsgCheckResult:_,CloudCustomData:m,MsgVersion:v,MsgFlagBits:f,RevokerInfo:I}=e,S,{From_Account:E,To_Account:C}=e;if(1===o){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:o,clientTime:a,messageLifeTime:l,random:c,sequence:u,time:d,messageControlInfo:{excludedFromLastMessage:1===(null==h?void 0:h.NoLastMsg),excludedFromUnreadCount:1===(null==h?void 0:h.NoUnread)},isSupportExtension:p,to:C,tinyID:g,checkResult:_,cloudCustomData:m,revokerInfo:S,messageVersion:v,messageFlagBits:f,readReceiptSentByPeer:n,elements:sg(i)}}function Zh(e){var{From_Account:e,MsgBody:t,MsgClientTime:s,MsgRandom:r,MsgSeq:n,MsgTimeStamp:o,To_Account:i,MsgVersion:a,CloudCustomData:l}=e;return{from:e,clientTime:s,random:r,sequence:n,time:o,to:i,elements:sg(t),messageVersion:a,cloudCustomData:l}}function eg(e){let{ClientSeq:t,From_Account:s,GroupInfo:r,MsgBody:n,MsgClientTime:o,MsgRandom:i,MsgSeq:a,MsgTimeStamp:l,SendMsgControl:c,SupportMessageExtension:u,TinyId:d,CloudCustomData:h,MsgVersion:p,MsgCheckResult:g,NeedReadReceipt:_,IsPlaceMsg:m,RevokerInfo:v,GroupAtInfo:f}=e,I,S=Nh.MSG_PRIORITY_NORMAL;if(Object.keys(Gh).includes(String(e.MsgPriority))&&(S=Gh[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===wh?t.push(e.GroupAt_Account):e.GroupAtAllFlag===Ph&&t.push(gs.MSG_AT_ALL)}),t}(f);return{clientSequence:t,from:s,groupProfile:r,clientTime:o,priority:S,random:i,sequence:a,time:l,messageControlInfo:{excludedFromLastMessage:1===(null==c?void 0:c.NoLastMsg),excludedFromUnreadCount:1===(null==c?void 0:c.NoUnread)},isSupportExtension:u,tinyID:d,cloudCustomData:h,messageVersion:p,messageCheckResult:g,needReadReceipt:_,isPlaceMessage:m,revokerInfo:I,atUserList:E,elements:sg(n),to:tg(e)}}function tg(e){var{utils:{isEmpty:t},constants:{IS_TOPIC_MESSAGE:s}}=Bt,{ToGroupId:e,GroupInfo:{MillionGroupFlag:r=0,TopicId:n}={}}=e;return r!==s||t(n)?e:n}function sg(e){var t;return e?Array.isArray(e)?e.map(e=>{var t=Bt.message.messageFactory.getElementClass(e.MsgType);return null==t?void 0:t.parseServerPushElement(e)}):null==(t=Bt.message.messageFactory.getElementClass(e.MsgType))?void 0:t.parseServerPushElement(e):null}function og(e){var{From_Account:e,MsgBody:t,MsgClientTime:s,MsgRandom:r,MsgSeq:n,MsgTimeStamp:o,GroupId:i,TopicId:a,MsgVersion:l,CloudCustomData:c}=e;return{from:e,clientTime:s,random:r,sequence:n,time:o,groupID:i,topicID:a,elements:sg(t),messageVersion:l,cloudCustomData:c}}function ng({conversationUpdateFields:e,message:t}){var{conversationID:s,conversationType:r,conversationSubType:n,flow:o,_isExcludedFromUnreadCount:i,_isExcludedFromLastMessage:a}=t,a=a?"":t,t=!i&&o===Uh.IN;e.has(s)?(e.get(s).lastMessage=a,t&&e.get(s).unreadCount++):e.set(s,{conversationID:s,type:r,subType:n,unreadCount:t?1:0,lastMessage:a})}function ig(e){return e.filter(e=>{var t=!me(null==e?void 0:e.getElements()),s=1===(null==e?void 0:e.isPlaceMessage);return t||Bt.ssoLog.createSSOLogData({method:"emptyMessageBody"}).setLogInfo({message:`from:${e.from} to:${e.to} sequence:`+e.sequence}).end(),t&&!s})}function rg(e){var t=Bt.message["messageDataHandler"];return!t.isInMessageList(e)&&!t.isMessageSentByCurrentInstance(e)}var ag=Object.freeze({__proto__:null,autoIncrementIndex:$h,filterValidMessages:ig,parseServerGroupMessage:eg,parseServerPushC2CModifyMessage:Zh,parseServerPushGroupModifyMessage:og,parseServerPushMessage:Xh,parseServerPushMessageElement:sg,shouldStoreMessage:rg,updateConversationFields:ng});let cg=Bt.utils["isPlainObject"];function ug(e,t={}){let{onlineUserOnly:s,messageControlInfo:r}=t,n=t["offlinePushInfo"],o=(e.conversationType===Lh.CONV_C2C&&!0===s&&(n?n.disablePush=!0:n={disablePush:!0}),"");"string"==typeof e.cloudCustomData&&0<e.cloudCustomData.length&&(o=e.cloudCustomData);var i=[];if(r&&cg(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:o,messageControlInfo:i,offlinePushInfo:n}}function lg(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 dg(t,s){return h(this,void 0,void 0,function*(){var e=yield so((t.conversationType===Lh.CONV_GROUP?function(e,t){var s,{onlineUserOnly:r,cloudCustomData:n,messageControlInfo:o,offlinePushInfo:i}=ug(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=Bt.store.get("login"))?void 0:s.userId,GroupId:e.to,MsgBody:a,CloudCustomData:n,Random:e.random,MsgPriority:e.priority,ClientSeq:e.clientSequence,GroupAtInfo:e._groupAtInfoList,OnlineOnlyFlag:r?1:0,MsgClientTime:e.clientTime,OfflinePushInfo:Qh(i),SendMsgControl:r?void 0:o,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:lg(t)}}}:function(e,t){var s,{onlineUserOnly:r,cloudCustomData:n,messageControlInfo:o,offlinePushInfo:i}=ug(e,t),r=!0===r?0:void 0,a=JSON.parse(JSON.stringify(e.transformElementsToServerFormat()));return{servcmd:"openim.sendmsg",data:{From_Account:null==(s=Bt.store.get("login"))?void 0:s.userId,To_Account:e.to,MsgBody:a,CloudCustomData:n,MsgSeq:e.sequence,MsgRandom:e.random,MsgLifeTime:r,From_AccountNick:e.nick,From_AccountHeadurl:e.avatar,SendMsgControl:0!==r?o: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:Qh(i),forbidCallbackControl:lg(t)}}})(t,s));return e?{time:e.MsgTime,messageDropReason:e.MsgDropReason,sequence:e.MsgSeq}:null})}let pg=Bt.utils["isPlainObject"],{MSG_AUDIO:hg,MSG_FILE:gg,MSG_IMAGE:_g,MSG_VIDEO:mg,MSG_MERGER:vg}=gs;class fg{init(){Ah.getInstance().registerApi({apiName:"sendMessage",context:this,matcher:e=>![hg,gg,_g,mg,vg].includes(e[0].type)})}sendMessage(u,t){return h(this,void 0,void 0,function*(){let r=Bt.ssoLog.createSSOLogData({method:"sendMessage"}),{TOTAL_COUNT:e,SEND_COST:i,SUCCESS_COUNT:a,FAILED_COUNT:o}=Es;if(!(u instanceof qh)){let e=new $s({code:_s.MSG_INSTANCE_REQUIRED});throw r.setError(e).end(),e}let n=u.validateBeforeSend();if(!n.isValid){let{code:e,message:t=""}=n.error||{},s=new $s({code:e,message:t});throw r.setError(s).end(),s}this._reportMessageSendQuality({name:e,message:u});let l=!1;var c=(Bt.message||{})["messageDataHandler"];try{let r=(t||{})["messageControlInfo"],n=null,o=(c.addRandomOfSentMessage(u.random),Date.now());if(u.conversationType===Lh.CONV_C2C?(l=!0===(null==t?void 0:t.onlineUserOnly),n=yield dg(u,t)):u.conversationType===Lh.CONV_GROUP&&(yield this._validateBeforeSendGroupMessage(u),n=yield dg(u,t)),n){let{messageDropReason:e,sequence:t,time:s}=n;if(this._updateNickAndAvatarOfSentMessageByMe(u),e&&this._logRateLimitInfo(u,t),this._reportMessageSendQuality({name:a,message:u}),this._reportMessageSendQuality({name:i,message:u,startTs:o}),!0===u.isResend){let e=c.findMessage(u.ID);e&&(console.log("sendMessage resend ok. ID:"+e.ID),c.deleteConversationMessage(e))}return u.status=es.SUCCESS,u.time=s,u.conversationType===Lh.CONV_GROUP&&(u.sequence=t),l?u._onlineOnlyFlag=!0:(c.storeConversationMessage(u),this._applySentMessageControlInfo(u,r),this._emitOnlineMessageSent(u)),{code:0,data:{message:u}}}}catch(e){u.status=es.FAIL,c.removeRandomOfSentMessage(u.random);let{errorCode:t,errorMessage:s="",errorInfo:r=s}=e||{},n=(this._hasRiskContent(t)&&(u.hasRiskContent=!0),l||this._isRejectedByRestApi(t)||c.storeConversationMessage(u),this._reportMessageSendQuality({name:o,message:u,error:e}),new $s({code:t,message:r,data:{message:u}}));throw this._logSendMessageError({message:u,error:n}),n}})}_hasRiskContent(e){return 80001===e||80004===e}_isRejectedByRestApi(e){return 10100<=e&&e<=10200||120001<=e&&e<=13e4}_logSendMessageError({message:e,error:t}){var s=Bt.ssoLog.createSSOLogData({method:"sendMessage"});let r=`head.seq: type:${e.type} from:${e.from} to:`+e.to;if(Bt.utils.IN_BROWSER){if("connection"in navigator){let e=navigator.connection;r+=` downlink:${e.downlink} effectiveType:${e.effectiveType} rtt:`+e.rtt}if("memory"in window.performance){let e=window.performance.memory;r+=` usedJSHeapSize:${e.usedJSHeapSize} totalJSHeapSize:${e.totalJSHeapSize} jsHeapSizeLimit:`+e.jsHeapSizeLimit}}s.setLogInfo({message:r}).setError(t).end()}_emitOnlineMessageSent(e){var t=e._isExcludedFromLastMessage?"":e,{conversationID:s,conversationType:r}=e,n=Zs(s)?Jt.TOPIC_NEW_MESSAGE:Jt.NEW_MESSAGE;Bt.notificationCenter.emitInnerEvent(n,{result:{conversationUpdateFieldList:[{conversationID:s,type:r,message:e,lastMessage:t,unreadCount:0}]}})}_applySentMessageControlInfo(e,t){t&&pg(t)&&(!0===t.excludedFromLastMessage&&(e._isExcludedFromLastMessage=!0),!0===t.excludedFromUnreadCount)&&(e._isExcludedFromUnreadCount=!0)}_logRateLimitInfo(e,t){var s=Bt.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=(Bt.message||{})["messageDataHandler"];let s=!1;var r,n=e["conversationID"],o=t.getLatestMsgSentByMe(n);o&&({nick:o,avatar:r}=o,s=o!==e.nick||r!==e.avatar||s)&&t.updateNickAndAvatarOfSentMessage({conversationID:n,latestNick:e.nick,latestAvatar:e.avatar,isSentByMe:!0})}_validateBeforeSendGroupMessage(n){return h(this,void 0,void 0,function*(){var{to:t,from:s}=n;let r=t,e=Eh.getGroup(r);if(Xs({groupID:r})&&null!=e&&e.isSupportTopic)throw new $s({code:_s.MSG_SEND_GRP_WITH_TOPIC_FAIL});if(Zs(t)&&([r]=t.split(ds.TOPIC),e=Eh.getGroup(r)),!e&&"function"==typeof(null==(t=Ah.getInstance().getApiMap())?void 0:t.getGroupProfile)){let e=yield Ah.getInstance().getApiMap().getGroupProfile({groupID:r});if((null==(t=null==(t=null==e?void 0:e.data)?void 0:t.group)?void 0:t.type)===gs.GRP_AVCHATROOM){let e=Fs({code:_s.MSG_SEND_FAIL_NOT_IN_AV,replacement1:s,replacement2:r});throw new $s({code:_s.MSG_SEND_FAIL_NOT_IN_AV,message:e})}}return!0})}_reportMessageSendQuality(e){Bt.notificationCenter.emitInnerEvent(Jt.QUALITY_STAT,{label:Ss.MESSAGE_SEND_SUCCESS_RATE,data:e})}}class Ig{constructor(e){this.value=e,this.next=null}}class Sg{constructor(e){this.head=null,this.tail=null,this.size=0,this.capacity=e}append(e){this.size>=this.capacity&&this.removeHead();e=new Ig(e);this.head?this.tail.next=e:this.head=e,this.tail=e,this.size+=1}delete(t){if(this.head)if(this.head.value===t)this.head=this.head.next;else{let e=this.head;for(;e.next;){if(e.next.value===t)return void(e.next=e.next.next);e=e.next}}}has(e){if(!this.head)return!1;let t=this.head,s=!1;for(;t;)t.value===e&&(s=!0),t=t.next;return s}removeHead(){this.head&&(this.head===this.tail?(this.head=null,this.tail=null):this.head=this.head.next,--this.size)}peek(){var e;return null==(e=this.head)?void 0:e.value}length(){return this.size}isEmpty(){return 0===this.size}isFull(){return this.size===this.capacity}clear(){this.head=null,this.tail=null,this.size=0}}var Eg=new class{constructor(){this._sparseMessagesByConversation=new Map,this._latestMessageSentByPeerMap=new Map,this._latestMessageSentByMeMap=new Map,this._randomOfSentMessageList=new Sg(100)}init(){Bt.notificationCenter.subscribeInnerEvent(Jt.LOGOUT,this._reset,this),Bt.notificationCenter.subscribeInnerEvent(Jt.DESTROY,this._dispose,this)}get _messagesByConversation(){return Ch.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:n,checkResult:e=0}=t,o=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)?Ch.updateMessage(a,[e],{isModified:!0,version:s,_elements:t,payload:t[0].content,type:t[0].type,cloudCustomData:n,hasRiskContent:o,operation:ts.modify}):(i.version=s,i._elements=t,i.payload=i._elements[0].content,i.type=i._elements[0].type,i.cloudCustomData=n,i.isModified=!0,i.hasRiskContent=o),{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 n of e)if(s=n.get(t)||null,s)break}return s}deleteConversationMessageList(e){this._messagesByConversation.has(e)&&(this._messagesByConversation.delete(e),this._latestMessageSentByMeMap.delete(e),this._latestMessageSentByPeerMap.delete(e)),this._sparseMessagesByConversation.has(e)&&this._sparseMessagesByConversation.delete(e)}revokeMessage({conversationID:t,sequence:s,random:r,revoker:n}){let e=this._messagesByConversation.get(t),o=null;if(e){var i=Array.from(e.values());if(o=this._findMessageBySequenceAndRandom({messageList:i,random:r,sequence:s})){let e=this._getUniqueIdOfMessage(o);return Ch.updateMessage(t,[e],{isRevoked:!0,revoker:n,operation:ts.revoke}),o}}if(this._sparseMessagesByConversation.has(t)){let e=Array.from(this._sparseMessagesByConversation.get(t).values());if(o=this._findMessageBySequenceAndRandom({messageList:e,random:r,sequence:s}))return o.isRevoked=!0,o.revoker=n,o}}_findMessageBySequenceAndRandom({messageList:t,sequence:s,random:r}){for(let e=0;e<t.length;e+=1){var n=t[e];if(n.sequence===s&&(g(r)||n.random===r))return n}return null}prependLocalMessageList(e){let{messageList:s,conversationID:t}=e;if(0===s.length)return[];var r=[],n=[],o=this._messagesByConversation.get(t)||new Map;for(let t of s){let e=this._getUniqueIdOfMessage(t);o.has(e)||(r.push(t),n.push([e,t]))}if(0<n.length){let e=new Map([...n,...o.entries()]);this._messagesByConversation.set(t,e),this._updateLatestMessageSentByMe(t),this._updateLatestMessageSentByPeer(t)}return r}storeSparseMessageList(r){if(0!==r.length){let e=r[0]["conversationID"],s=r.length;this._sparseMessagesByConversation.has(e)||this._sparseMessagesByConversation.set(e,new Map);var n=this._sparseMessagesByConversation.get(e);for(let t=0;t<s;t++){let e=r[t];n.has(e.ID)||n.set(e.ID,e)}}}_updateLatestMessageSentByMe(t){var e,s=Array.from((null==(e=this._messagesByConversation.get(t))?void 0:e.values())||[]);if(0!==s.length)for(let e=s.length-1;0<=e;e--)if("out"===s[e].flow){this._setLatestMsgSentByMe(t,s[e]);break}}_updateLatestMessageSentByPeer(t){var e,s=Array.from((null==(e=this._messagesByConversation.get(t))?void 0:e.values())||[]);if(0!==s.length&&t.startsWith("C2C"))for(let e=s.length-1;0<=e;e--)if("in"===s[e].flow){this._setLatestMsgSentByPeer(t,s[e]);break}}_getUniqueIdOfMessage(e){var{from:e,to:t,random:s,sequence:r,time:n}=e;return e+`-${t}-${s}-${r}-`+n}_setLatestMsgSentByPeer(e,t){this._latestMessageSentByPeerMap.set(e,t)}_setLatestMsgSentByMe(e,t){this._latestMessageSentByMeMap.set(e,t)}getLatestMsgSentByPeer(e){return this._latestMessageSentByPeerMap.get(e)}getLatestMsgSentByMe(e){return this._latestMessageSentByMeMap.get(e)}addRandomOfSentMessage(e){this._randomOfSentMessageList.append(e)}removeRandomOfSentMessage(e){this._randomOfSentMessageList.delete(e)}updateNickAndAvatarOfSentMessage(e){let{conversationID:t="",latestAvatar:o,latestNick:i,isSentByMe:s=!0}=e,r=this._messagesByConversation.get(t);if(r){let e=Array.from(r.values()),n=s?"out":"in";e.forEach(e=>{var{nick:t,avatar:s,flow:r}=e;r===n&&(t!==i&&(e.nick=i),s!==o)&&(e.avatar=o)})}}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(),Bt.notificationCenter.unSubscribeInnerEvent(Jt.LOGOUT,this._reset,this),Bt.notificationCenter.unSubscribeInnerEvent(Jt.DESTROY,this._dispose,this)}};function Cg(e,t){var s,r,n,o,i,a,l,c=Sh.getConversation(e);null!=c&&c.lastMessage&&(c=c["lastMessage"],{lastTime:s,lastSequence:r,version:n}=c,{time:t,sequence:o,messageVersion:i,elements:a,cloudCustomData:l}=t,s===t)&&r===o&&n!==i&&(c.type=a[0].type,c.payload=a[0].content,c.messageForShow=uo(c.type,c.payload),c.cloudCustomData=l,c.version=i,Sh.updateConversation(e,{lastMessage:c}))}class Mg{init(){Ah.getInstance().registerApi({apiName:"modifyMessage",context:this})}modifyMessage(u){return h(this,void 0,void 0,function*(){let r=Bt.ssoLog.createSSOLogData({method:"modifyMessage"}),{to:n,payload:e,sequence:o,conversationType:i,random:a,time:l,from:c,type:t}=u;if(this._canModifyMessageElement(t)){var s=u.getElements();1<s.length&&(s[0].type=t,s[0].content=e);try{let t=null,s;if(r.setLogInfo({message:"to:"+n}),i===Lh.CONV_C2C?t=yield function(u){return h(this,void 0,void 0,function*(){let{from:e,to:t,version:s=0,sequence:r,random:n,time:o,type:i,cloudCustomData:a}=u,l={From_Account:e,To_Account:t,MsgVersion:s,MsgSeq:r,MsgRandom:n,MsgTime:o,MsgType:i,MsgBody:u.transformElementsToServerFormat(),CloudCustomData:a},c=yield so({servcmd:"openim.modify_c2c_msg",data:l});if(c){let{MsgBody:e,MsgVersion:t,CloudCustomData:s}=c;return{elements:sg(e),messageVersion:t,cloudCustomData:s}}})}(u):i===Lh.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,n={GroupId:e,MsgVersion:t,MsgSeq:s,MsgBody:i.transformElementsToServerFormat(),CloudCustomData:r},o=yield so({servcmd:"openim.modify_group_msg",data:n});if(o){let{MsgBody:e,MsgVersion:t,CloudCustomData:s}=o;return{elements:sg(e),messageVersion:t,cloudCustomData:s}}})}(u)),t){r.end();let e=""+i+n;return n===ro()&&i===Lh.CONV_C2C&&(e=""+i+c),s={conversationType:i,from:c,to:n,time:l,random:a,sequence:o,elements:null==t?void 0:t.elements,cloudCustomData:null==t?void 0:t.cloudCustomData,messageVersion:null==t?void 0:t.messageVersion,conversationID:e},this._handleModifyMessageSuccess(s),{code:0,data:{message:u}}}}catch(e){let t=(e||{})["errorCode"],s=new $s({functionName:"modifyMessage",code:t});throw this._logModifyMessageError(s),s}}else r.setLogInfo({message:"can not modify message element. message type: "+t}).end()})}_logModifyMessageError(e){Bt.ssoLog.getSSOLogData("modifyMessage").setError(e).end()}_handleModifyMessageSuccess(e){var t=e["conversationID"],{isUpdated:s,message:r}=Bt.message.messageDataHandler.modifyConversationMessage(t,e);!0===s&&Bt.notificationCenter.emitOuterEvent(Yt.MESSAGE_MODIFIED,{name:Yt.MESSAGE_MODIFIED,data:[r]}),Bt.notificationCenter.emitInnerEvent(Jt.MESSAGE_MODIFIED,{conversationID:t,message:r}),Cg(t,e)}_canModifyMessageElement(e){return[bh.MSG_TEXT,bh.MSG_CUSTOM,bh.MSG_LOCATION,bh.MSG_FACE].includes(e)}}class yg{init(){var e=Bt["notificationCenter"],t=e["InnerEventSubType"];Js.getInstance().registerWorkflowStep(vs.RECEIVE_C2C_NEW_MESSAGE,fs.HANDLE_C2C_NEW_MESSAGE,this._handleC2CMessagePush,this),Js.getInstance().registerWorkflowStep(vs.RECEIVE_C2C_NEW_MESSAGE,fs.EMIT_C2C_MESSAGE_EVENT,this._emitMessageEventsAfterReceiveNewMessage,this),Js.getInstance().registerWorkflowStep(vs.SYNC_SERVER_INFO_AFTER_RE_ONLINE,fs.EMIT_C2C_MESSAGE_EVENT,this._emitMessageEventsAfterSyncUnreadMessage,this),e.subscribeInnerEvent(Jt.MESSAGE_PUSH,t.C2C_REALTIME_MESSAGE,this._executeReceiverNewMessageWorkFlow,this),e.subscribeInnerEvent(Jt.MESSAGE_PUSH,t.C2C_MESSAGE_MODIFIED,this._handleC2CMessageModify,this),e.subscribeInnerEvent(Jt.DESTROY,this._dispose,this)}_executeReceiverNewMessageWorkFlow(e){Js.getInstance().executeWorkflow(vs.RECEIVE_C2C_NEW_MESSAGE,e)}_handleC2CMessagePush(e){let t=e.data||{},s=(Bt.message||{})["messageDataHandler"],r=[],n=new Map;return t.C2cMsgArray.forEach(e=>{e=this._generateC2CMessage(e);this._updateMessageProfile(e);let t=1===e.isModified;s.isMessageSentByCurrentInstance(e)?e.isModified=t:t=!1,e.isOnlineMessage()?(e._onlineOnlyFlag=!0,s.isMessageSentByCurrentInstance(e)||r.push(e)):rg(e)&&(s.storeConversationMessage(e)&&ng({conversationUpdateFields:n,message:e}),s.isMessageSentByCurrentInstance(e)&&!t||r.push(e))}),{conversationUpdateFieldList:[...n.values()],messages:r}}_emitMessageEventsAfterReceiveNewMessage(e){var{messages:e=[]}=(null==(e=e.result)?void 0:e[fs.HANDLE_C2C_NEW_MESSAGE])||{};this._emitMessageEvents(e)}_emitMessageEventsAfterSyncUnreadMessage(e){var{messages:e=[]}=(null==(e=e.result)?void 0:e[fs.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&&Bt.notificationCenter.emitOuterEvent("onMessageModified",{name:"onMessageModified",data:t}),null==e?void 0:e.filter(e=>!(null!=e&&e.isModified)));0<t.length&&Bt.notificationCenter.emitOuterEvent("onMessageReceived",{name:"onMessageReceived",data:t})}_generateC2CMessage(e){var t=Lh.CONV_C2C,e=Xh(e),t=Bt.message.messageFactory.createMessage(Object.assign(Object.assign({},e),{conversationType:t,flow:Uh.IN})),e=e["elements"];return t.setElement(e),t}_updateMessageProfile(r){var e;let n=(Bt.message||{})["messageDataHandler"],t=null==(e=Bt.store.get("login"))?void 0:e.userId,{from:s,nick:o,avatar:i,conversationID:a=""}=r;if(s!==t){let s=n.getLatestMsgSentByPeer(a);if(s){let{nick:e,avatar:t}=s;g(o)||g(i)?(r.nick=_(e)?e:r.nick,r.avatar=_(t)?t:r.avatar):o===e&&i===t||(n.updateNickAndAvatarOfSentMessage({conversationID:a,latestNick:o,latestAvatar:i,isSentByMe:!1}),this._updateConversationUserProfile({conversationID:a,nick:o,avatar:i}))}}else{let e=n.getLatestMsgSentByMe(a);!e||o===e.nick&&i===e.avatar||n.updateNickAndAvatarOfSentMessage({conversationID:a,latestNick:o,latestAvatar:i,isSentByMe:!0})}}_updateConversationUserProfile(e){var{conversationID:e,nick:t,avatar:s}=e,{userProfile:r={}}=Sh.getConversation(e)||{};r.avatar===s&&r.nick===t||Sh.updateConversation(e,{userProfile:Object.assign(Object.assign({},r),{nick:t,avatar:s})})}_updateMessageListDueToModify(e){var t=e["conversationID"],{isUpdated:s,message:r}=Bt.message.messageDataHandler.modifyConversationMessage(t,e);!0===s&&Bt.notificationCenter.emitOuterEvent("onMessageModified",{name:"onMessageModified",data:[r]}),Bt.notificationCenter.emitInnerEvent("ModifyMessageSuccess",e),Cg(t,e)}_handleC2CMessageModify(e){e.C2cMsgModNotifys.forEach(e=>{var t=Lh.CONV_C2C,e=Zh(e),{to:s,from:r}=e;let n=""+t+s;s===(null==(s=Bt.store.get("login"))?void 0:s.userId)&&(n=""+t+r),e=Object.assign({conversationType:t,conversationID:n},e),this._updateMessageListDueToModify(e)})}_dispose(){var e=Bt["notificationCenter"],e=e["InnerEventSubType"];Bt.notificationCenter.unSubscribeInnerEvent(Jt.MESSAGE_PUSH,e.C2C_REALTIME_MESSAGE,this._handleC2CMessagePush,this),Bt.notificationCenter.unSubscribeInnerEvent(Jt.MESSAGE_PUSH,e.C2C_MESSAGE_MODIFIED,this._handleC2CMessageModify,this),Bt.notificationCenter.unSubscribeInnerEvent(Jt.DESTROY,this._dispose,this)}}class Ag{init(){var e=Bt["notificationCenter"],t=e["InnerEventSubType"];Js.getInstance().registerWorkflowStep(vs.RECEIVE_GROUP_NEW_MESSAGE,fs.HANDLE_GROUP_NEW_MESSAGE,this._handleGroupMessagePush,this),Js.getInstance().registerWorkflowStep(vs.RECEIVE_GROUP_NEW_MESSAGE,fs.EMIT_GROUP_MESSAGE_EVENT,this._emitMessageEvents,this),e.subscribeInnerEvent(Jt.MESSAGE_PUSH,t.GROUP_REALTIME_MESSAGE,this._executeReceiverNewMessageWorkFlow,this),e.subscribeInnerEvent(Jt.MESSAGE_PUSH,t.GROUP_MESSAGE_MODIFIED,this._handleGroupMessageModify,this),e.subscribeInnerEvent(Jt.DESTROY,this._dispose,this)}_executeReceiverNewMessageWorkFlow(e){this._canExecuteReceiverNewMessageWorkFlow(e)&&Js.getInstance().executeWorkflow(vs.RECEIVE_GROUP_NEW_MESSAGE,e)}_handleGroupMessagePush(e){let t=e.data||{},s=Bt.message["messageDataHandler"],r=[],n=new Map,o=null==t?void 0:t.GroupMsgArray;return null!=o&&o.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)):rg(e)&&s.storeConversationMessage(e)&&(r.push(e),ng({conversationUpdateFields:n,message:e})))}),{conversationUpdateFieldList:[...n.values()],messages:r}}_emitMessageEvents(e){var e=((null==(e=e.result)?void 0:e[fs.HANDLE_GROUP_NEW_MESSAGE])||{})["messages"],t=(null==e?void 0:e.filter(e=>!0===(null==e?void 0:e.isModified)))||[],t=(0<t.length&&Bt.notificationCenter.emitOuterEvent("onMessageModified",{name:"onMessageModified",data:t}),(null==e?void 0:e.filter(e=>!(null!=e&&e.isModified)))||[]);0<t.length&&Bt.notificationCenter.emitOuterEvent("onMessageReceived",{name:"onMessageReceived",data:t})}_generateGroupMessage(e){var t=Lh.CONV_GROUP,e=eg(e),t=Bt.message.messageFactory.createMessage(Object.assign(Object.assign({},e),{conversationType:t,flow:Uh.IN})),e=e["elements"];return t.setElement(e),t}updateMessageProfile(n){var e;let t=(Bt.message||{})["messageDataHandler"],s=null==(e=Bt.store.get("login"))?void 0:e.userId,{from:r,nick:o,avatar:i,conversationID:a="",_elements:l}=n;if(r===s){let e=t.getLatestMsgSentByMe(a);!e||o===e.nick&&i===e.avatar||t.updateNickAndAvatarOfSentMessage({conversationID:a,latestNick:o,latestAvatar:i,isSentByMe:!0})}else if(r===gs.CONV_SYSTEM){let{operationType:e,memberInfoList:t,operatorInfo:s}=l,r={};if(me(t)?me(s)||(r=s):[ps.JOINED,ps.KICKED,ps.ADMIN_SET,ps.ADMIN_CANCELED].includes(e)&&(r=Object.assign({},t[0])),!me(r)){let{nick:e="",avatar:t=""}=r;n.nick=e,n.avatar=t}}}_updateMessageListDueToModify(e){var t=e["conversationID"],{isUpdated:s,message:r}=Bt.message.messageDataHandler.modifyConversationMessage(t,e);!0===s&&Bt.notificationCenter.emitOuterEvent("onMessageModified",{name:"onMessageModified",data:[r]}),Cg(t,e)}_handleGroupMessageModify(e){e.GroupMsgModNotifys.forEach(e=>{var t=Lh.CONV_GROUP,{topicID:s,groupID:r}=e=og(e),s=s||r,e=Object.assign({conversationType:t,conversationID:""+t+s,to:s},e);this._updateMessageListDueToModify(e)})}_dispose(){var e=Bt["notificationCenter"],{GROUP_REALTIME_MESSAGE:t,GROUP_MESSAGE_MODIFIED:s}=e["InnerEventSubType"];e.unSubscribeInnerEvent(Jt.MESSAGE_PUSH,t,this._handleGroupMessagePush,this),e.unSubscribeInnerEvent(Jt.MESSAGE_PUSH,s,this._handleGroupMessageModify,this),e.unSubscribeInnerEvent(Jt.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===ls.GRP_AVCHATROOM;return!(!Eh.getGroup(e)&&t)}}var Tg=new class{constructor(){this.c2cMessageReceiver=new yg,this.groupMessageReceiver=new Ag}init(){this.c2cMessageReceiver.init(),this.groupMessageReceiver.init()}};let Og={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."}}}},Dg={createCustomMessage:!0,sendMessage:!0,modifyMessage:!0};var Rg=new class{getGroupRoamingMessagesByAnchor(s){return h(this,void 0,void 0,function*(){try{var i=Bt.ssoLog.createSSOLogData({method:"getGroupRoamingMessagesByAnchor"}),{conversationID:t,count:e,direction:a,sequence:l}=s,c=t.replace(as.CONV_GROUP,""),u=[];let o=l;if(a===ss.BACKWARD){if("number"!=typeof l)return{messageList:[],hasNoMoreHistoryMessage:!1,nextReqMessageIDFromServer:""};o=l+e-1}var d=yield function(r){return h(this,void 0,void 0,function*(){var{groupID:e,count:t,messageSequence:s}=r,e={GroupId:e,ReqMsgNumber:t,WithRecalledMsg:1,Version:1};return s&&(e.ReqMsgSeq=s),yield so({servcmd:"group_open_http_svc.group_msg_get",data:e})})}({groupID:c,count:e,messageSequence:o});if(d){let{RspMsgList:t=[],NextReqMsgSeq:e=0,IsFinished:s,InvisibleMsgSeq:r}=d;i.setLogInfo({message:`groupID:${c} sequence:${l} reqSeq:${o} direction:${a}
|
|
5
|
+
complete:${s} nextSequence:${e} remoteMsgCount:${t.length} invisibleSequenceList:`+r}).end();var p=[];for(let e=0;e<t.length;e++){var g=t[e],_=(g.From_Account===gs.CONV_SYSTEM&&u.push(g),this._parseMessage(g));p.push(_)}p.reverse();let n=s===kh;return a===ss.BACKWARD&&(n=p[p.length-1].sequence>=l),{messageList:ig(p),invisibleSequenceList:r,nextReqMessageIDFromServer:e,hasNoMoreHistoryMessage:n,serverGroupTipList:u}}}catch(e){t=new $s({code:null==e?void 0:e.code});Bt.ssoLog.getSSOLogData("getGroupRoamingMessagesByAnchor").setError(t).end()}})}_parseMessage(e){var t=as.CONV_GROUP,e=(4===e.Event&&(e.MsgBody.MsgType=gs.MSG_GRP_TIP),eg(e)),t=Bh.createMessage(Object.assign(Object.assign({},e),{conversationType:t,flow:"in"}));return t.setElement(e.elements),t}};class Lg{constructor(){this.messageHelper=ag,this.messageFactory=Bh,this.messageSender=new fg,this.messageAction=new Mg,this.messageReceiver=Tg,this.messageDataHandler=Eg,this.messageHistory=Rg,this.messageSender.init(),this.messageFactory.init(),this.messageAction.init(),this.messageReceiver.init(),this.messageDataHandler.init(),Ys({auth:Dg,params:Og})}}let Ng="User",bg="Tag_Profile_IM_",Gg={NICK:bg+"Nick",GENDER:bg+"Gender",BIRTHDAY:bg+"BirthDay",LOCATION:bg+"Location",SELFSIGNATURE:bg+"SelfSignature",ALLOWTYPE:bg+"AllowType",LANGUAGE:bg+"Language",AVATAR:bg+"Image",MESSAGESETTINGS:bg+"MsgSettings",ADMINFORBIDTYPE:bg+"AdminForbidType",LEVEL:bg+"Level",ROLE:bg+"Role"},wg="Tag_Profile_Custom",Pg="profileCustomField",Ug="USER_STATUS",kg=1,Fg=1e3,$g={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:[]},qg=new Map([[Gg.NICK,"nick"],[Gg.GENDER,"gender"],[Gg.BIRTHDAY,"birthday"],[Gg.LOCATION,"location"],[Gg.SELFSIGNATURE,"selfSignature"],[Gg.ALLOWTYPE,"allowType"],[Gg.LANGUAGE,"language"],[Gg.AVATAR,"avatar"],[Gg.MESSAGESETTINGS,"messageSettings"],[Gg.ADMINFORBIDTYPE,"adminForbidType"],[Gg.LEVEL,"level"],[Gg.ROLE,"role"]]);var n_,i_,r_,xg=new class{createProfile(e,t){let s={userID:e,profileCustomField:[]};return t.forEach(e=>{var{tag:e,value:t}=e;e&&-1<e.indexOf(wg)?s.profileCustomField.push({key:e,value:t}):qg.has(e)&&(s[qg.get(e)]=t)}),Object.assign(Object.assign({},$g),s)}parseProfileItem(e=[]){let t=[];return e.forEach(e=>{t.push({tag:e.Tag,value:e.Value})}),t}parseProfileList(e=[]){let t=[];return e.forEach(e=>{t.push({tag:e.Tag,value:e.ValueBytes})}),t}convertParamsToProfile(t){let s=[];return Object.keys(t).forEach(e=>{e!==Pg&&s.push({tag:Gg[e.toUpperCase()],value:t[e]})}),t.profileCustomField&&v(t.profileCustomField)&&t.profileCustomField.forEach(e=>{s.push({tag:e.key,value:e.value})}),s}normalizeProfileFields(e){let r={},n=[];return e.forEach(e=>{var{tag:t,value:s}=e;if(t&&-1<t.indexOf(wg)&&n.push({key:t,value:s}),qg.has(t)&&void 0!==s){let e=qg.get(t);r[e]=s}}),0<n.length&&(r.profileCustomField=n),r}};let Vg=Bt.common["generateProtocolData"];function Bg(r){return h(this,void 0,void 0,function*(){let e="profile.portrait_get_all",t={From_Account:ro(),UserItem:[]};r.forEach(e=>{t.UserItem.push({CustomSequence:0,StandardSequence:0,To_Account:e})});var o=Vg({servcmd:e,data:t}),s=o.head.seq+e,o=yield Bt.channel.sendPacket(o,{requestId:s});if(o){let{ActionStatus:e,ErrorCode:t,ErrorDisplay:s,ErrorInfo:r,UserProfileItem:n}=o,i=[];return n.map(e=>{var{To_Account:e,CustomSequence:t,ResultCode:s,ResultInfo:r,StandardSequence:n,ProfileItem:o}=e,o=xg.parseProfileItem(o);i.push({userId:e,customSequence:t,resultCode:s,resultInfo:r,standardSequence:n,profileItem:o})}),{actionStatus:e,errorCode:t,errorDisplay:s,errorInfo:r,userProfile:i}}})}function jg(e){return Mh.getFriendMap().has(e)}let Kg=Bt.utils["isEmpty"];class Wg{constructor(){this._strangerProfileMap=new Map}init(){Ah.getInstance().registerApi({apiName:"getMyProfile",context:this}),Ah.getInstance().registerApi({apiName:"getUserProfile",context:this}),Ah.getInstance().registerApi({apiName:"updateMyProfile",context:this}),this.createProfile=xg.createProfile.bind(xg);var e=Bt["notificationCenter"];Js.getInstance().registerWorkflowStep(vs.SYNC_SERVER_INFO_AFTER_LOGIN,fs.USER_PROFILE_SYNC,this.getMyProfileCacheThenServer,this),e.subscribeInnerEvent(Jt.MESSAGE_PUSH,e.InnerEventSubType.PROFILE_MODIFIED,this._onProfileDataModify,this),e.subscribeInnerEvent(Jt.LOGOUT,this._reset,this),e.subscribeInnerEvent(Jt.DESTROY,this._dispose,this)}getMyProfile(){return h(this,void 0,void 0,function*(){let t=Bt.ssoLog.createSSOLogData({method:"getMyProfile"});try{var s=ro(),r=yield Bg([s]);if(r){let e=this._handleProfileFormResponse(r)[0];return Mh.getUserProfileMap().set(s,e),{code:0,data:e}}t.end()}catch(e){var{errorCode:r,errorInfo:s}=e,r=new $s({functionName:"getMyProfile",code:r,message:s});throw t.setError(r).end(),e}})}getUserProfile(d){return h(this,void 0,void 0,function*(){var t=Bt.ssoLog.createSSOLogData({method:"getUserProfile"});try{var s=d["userIDList"],{userIdListToRequest:r,profileFromCache:n}=this._filterRequestAndCacheUsers(s),o="User.getUserProfile userIDList.length:"+s.length;if(0===r.length)return t.setLogInfo({message:o}).end(),{code:0,data:n};r.length>Fg&&(console.warn("userIdListToRequest.length > 1000"),r.length=Fg);var{data:i,error:e}=yield this._batchFetchUserProfiles(r),a=r.length,l=i.length,c=a-l,u=`getUserProfile query:${a} success:${l} fail:${c} from cache:`+n.length;if(0===n.length&&a===c&&!Kg(e))throw console.error(u+` error:${JSON.stringify(e)}}`),e;if(v(i)){i.forEach(e=>{(jg(e.userID)?Mh.getUserProfileMap():this._strangerProfileMap).set(e.userID,e)});let e=i.concat(n);return t.setLogInfo({message:o}).end(),{code:0,data:e}}}catch(e){s=e["errorCode"],r=new $s({functionName:"getUserProfile",code:s});throw t.setError(r).end(),r}})}getMyProfileCacheThenServer(){return h(this,void 0,void 0,function*(){var e=ro(),e=Mh.getUserProfileMap().has(e);return e?{code:0,data:e}:this.getMyProfile()})}updateMyProfile(l){return h(this,void 0,void 0,function*(){let n=Bt.ssoLog.createSSOLogData({method:"updateMyProfile"}),t=ro(),s={};for(let e in l)void 0!==l[e]&&(s[e]=l[e]);let r=xg.convertParamsToProfile(s);try{let e={From_Account:t,ProfileItem:r};n.setLogInfo({message:JSON.stringify(r)}),yield function(r){return h(this,void 0,void 0,function*(){let e="profile.portrait_set",t=Vg({servcmd:e,data:r}),s=""+t.head.seq+e,n=yield Bt.channel.sendPacket(t,{requestId:s});if(n){let{ActionStatus:e,ErrorCode:t,ErrorDisplay:s,ErrorInfo:r}=n;return{actionStatus:e,errorCode:t,errorDisplay:s,errorInfo:r}}})}(e);var o=Mh.getUserProfile(t),i=o?Object.assign(Object.assign({},o),s):xg.createProfile(t,r),a=!Kt(o,i,["lastUpdatedTime"]);return i.lastUpdatedTime=Date.now(),Mh.getUserProfileMap().set(t,i),a&&this._emitProfileUpdated(i),n.end(),{code:0,data:i}}catch(e){let{errorCode:t,errorInfo:s}=e,r=new $s({functionName:"updateMyProfile",code:t,message:s});throw n.setError(r).end(),r}})}updateMyNickAndAvatar(n){return h(this,void 0,void 0,function*(){var e=ro(),t=Date.now(),s=Mh.getUserProfile(e),r={};(r=s?Object.assign(s,n):xg.createProfile(e,n)).lastUpdatedTime=t,Mh.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:xg.parseProfileList(s)}}();Kg(t)||({isProfileUpdated:t,profile:e}=this._handleProfileModified(t),t&&this._emitProfileUpdated(e))}_emitProfileUpdated(e){Bt.notificationCenter.emitInnerEvent(Jt.PROFILE_UPDATE,{name:Jt.PROFILE_UPDATE,data:[e]}),Bt.notificationCenter.emitOuterEvent(Yt.PROFILE_UPDATED,{name:Yt.PROFILE_UPDATED,data:[e]}),Sh.updateConversation("C2C"+(null==e?void 0:e.userID),{userProfile:e})}_dispose(){var e=Bt["notificationCenter"];e.unSubscribeInnerEvent(Jt.LOGOUT,this._reset,this),e.unSubscribeInnerEvent(Jt.MESSAGE_PUSH,e.InnerEventSubType.PROFILE_MODIFIED,this._onProfileDataModify,this),e.unSubscribeInnerEvent(Jt.DESTROY,this._dispose,this),this._reset()}_handleProfileModified(e){let{userId:t,profileList:s}=e,r=Mh.getUserProfile(t);if(!(ro()===t||jg(t)&&r))return{isProfileUpdated:!1,profile:null};let n=xg.normalizeProfileFields(s),o=Object.keys(n).some(e=>e===Pg?!Kt(r.profileCustomField,n.profileCustomField):r[e]!==n[e]);return o?(e=Date.now(),e=Object.assign(Object.assign(Object.assign({},r),n),{lastUpdatedTime:e}),Mh.getUserProfileMap().set(t,e),{isProfileUpdated:o,profile:e}):{isProfileUpdated:!1,profile:r}}_filterRequestAndCacheUsers(e){let s=[],r=[];return e.forEach(e=>{var t=Mh.getUserProfileMap().has(e);jg(e)&&t?r.push(Mh.getUserProfile(e)):this._isStrangerAndProfileValid(e)?r.push(this._strangerProfileMap.get(e)):s.push(e)}),{userIdListToRequest:s,profileFromCache:r}}_handleProfileFormResponse(e){e=e.userProfile;if(!Array.isArray(e))return[];let t=e.filter(e=>"@TLS#NOT_FOUND"!==e.userId&&""!==e.userId&&!Kg(e.profileItem)),s=Date.now();return t.map(e=>{e=xg.createProfile(e.userId,e.profileItem);return e.lastUpdatedTime=s,e})}_isStrangerAndProfileValid(e){var t;return!jg(e)&&({lastUpdatedTime:e=0}=this._strangerProfileMap.get(e)||{},t=(null==(t=Bt.store.get("cloudConfig"))?void 0:t.stranger_profile_expiration_time)||6e5,Date.now()-e<=t)}_chunkUserIDList(s,r){return Array.from({length:Math.ceil(s.length/r)},(e,t)=>s.slice(t*r,(t+1)*r))}_batchFetchUserProfiles(e){return h(this,void 0,void 0,function*(){let t=[],r=[],n={};return this._chunkUserIDList(e,100).forEach(e=>{t.push(Bg(e))}),(yield Promise.allSettled(t)).forEach(s=>{if("fulfilled"===s.status){let e=s.value,t=this._handleProfileFormResponse(e);v(t)&&r.push(...t)}else if("rejected"===s.status){let{code:e,message:t}=s.reason||{};n={errorCode:e,message:t}}}),{data:r,error:n}})}_reset(){Mh.getUserProfileMap().clear(),this._strangerProfileMap.clear()}}let Hg=new Map,Yg=["0","1","2","3","4","5","6","7","8","9","A","B","C","D","E","F"];for(let e=0,t=Yg.length;e<t;e++)Hg.set(e,Yg[e]);function zg(e){if(!e)return"";var n=String(e).replace(/[=]+$/,"");let o="";if(n.length%4==1)return"";for(let e,t,s=0,r=0;t=n.charAt(r++);~t&&(e=s%4?64*e+t:t,s++%4)&&(o+=String.fromCharCode(255&e>>(-2*s&6))))t="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=".indexOf(t);try{return decodeURIComponent(escape(o))}catch(e){return console.warn(e),""}}let Jg=Bt.utils["isEmpty"],Qg=Bt.common["generateProtocolData"];function Xg(n){return h(this,void 0,void 0,function*(){var e,t,s="im_open_status.ws_get_user_status",r=Qg({servcmd:s,data:{To_Account:n}}),s=r.head.seq+s,r=yield Bt.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:zg(s)}}),failureUserList:e.map(e=>{var{To_Account:e,Invalid_Account:t,ErrorCode:s,ErrorInfo:r}=e;return{userID:Jg(t)?e:t,code:s,message:r}})}})}class Zg{constructor(){this._customStatus=""}init(){var e=Bt["notificationCenter"];Ah.getInstance().registerApi({apiName:"getUserStatus",context:this}),Ah.getInstance().registerApi({apiName:"setSelfStatus",context:this}),Ah.getInstance().registerApi({apiName:"subscribeUserStatus",context:this}),Ah.getInstance().registerApi({apiName:"unsubscribeUserStatus",context:this}),Js.getInstance().registerWorkflowStep(vs.SYNC_SERVER_INFO_AFTER_RE_ONLINE,fs.USER_STATUS_UPDATE,this._onReOnline,this),e.subscribeInnerEvent(Jt.MESSAGE_PUSH,e.InnerEventSubType.USER_STATUS_UPDATE,this._onUserStatusUpdate,this),e.subscribeInnerEvent(Jt.LOGOUT,this._reset,this),e.subscribeInnerEvent(Jt.DESTROY,this._dispose,this)}setSelfStatus(s){return h(this,void 0,void 0,function*(){let n=Bt.ssoLog.createSSOLogData({method:"setSelfStatus"}),e=ro(),t=s["customStatus"];try{return yield function(n){return h(this,void 0,void 0,function*(){let e="im_open_status.ws_set_custom_status",t=Qg({servcmd:e,data:{CustomStatus:n}}),s=""+t.head.seq+e,r=yield Bt.channel.sendPacket(t,{requestId:s});if(r){let{ErrorCode:e,ErrorInfo:t}=r;return{errorCode:e,errorInfo:t}}})}(t),this._customStatus=t,n.setLogInfo({message:"customStatus: "+t}).end(),{code:0,data:{userID:e,statusType:kg,customStatus:t}}}catch(e){let{errorCode:t,errorInfo:s}=e,r=new $s({functionName:"setSelfStatus",code:t,message:s});throw n.setError(r).end(),r}})}getUserStatus(s){return h(this,void 0,void 0,function*(){var e=Bt.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=zg(e);this._customStatus=e}subscribeUserStatus(r){return h(this,void 0,void 0,function*(){try{console.log(Ng+" 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=Bt["channel"],t="im_open_status.ws_status_subscribe",s=Qg({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(Ng+" subscribeUserStatus error:",e),e}})}unsubscribeUserStatus(r){return h(this,void 0,void 0,function*(){try{console.log(Ng+" 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=Bt["channel"],t="im_open_status.ws_status_unsubscribe",s=0===r.length?{UnsubscribeAll:1}:{To_Account:r},s=Qg({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(Ng+" 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:zg(s)}});this._emitUserStatusUpdatedEvent(e)}_onReOnline(e){var e=zg(e.data.customStatus);this._customStatus!==e&&(this._customStatus=e,e={userID:ro(),statusType:kg,customStatus:e},this._emitUserStatusUpdatedEvent(e))}_emitUserStatusUpdatedEvent(e){Bt.notificationCenter.emitOuterEvent(Yt.USER_STATUS_UPDATED,{name:Yt.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:Bt.utils.isEmpty(t)?e:t,code:s,message:r}})}_checkBusinessCapabilityBits(e){if(!Bt.store.get("commercialConfig").get(Ug))throw new $s({functionName:e,code:_s.NO_USE,replacement1:e})}_getMaxUserCount(e){var t=Bt.store.get("cloudConfig")||{},{key:e,default:s}={query:{key:"status_query_count",default:500},subscribe:{key:"status_sub_count",default:100},unsubscribe:{key:"status_unsub_count",default:100}}[e],t=t[e]||s;return parseInt(t,10)}_getMyStatus(){var e=Bt.ssoLog.getSSOLogData("getUserStatus"),t=(e.setLogInfo({moreMessage:"getUserStatus._getMyStatus"}),{userID:ro(),statusType:kg,customStatus:this._customStatus});return e.end(),{code:0,data:{successUserList:[t],failureUserList:[]}}}_getUserStatus(n){return h(this,void 0,void 0,function*(){var t=Bt.ssoLog.getSSOLogData("getUserStatus");t.setLogInfo({moreMessage:"getUserStatus._getUserStatus"});try{this._checkBusinessCapabilityBits("getUserStatus");var s=this._getMaxUserCount("query"),{successUserList:r,failureUserList:e}=(yield Xg(this._sliceUserIDList(n,s)))||{};return t.end(),{code:0,data:{successUserList:r,failureUserList:e}}}catch(e){s=e["errorCode"],r=new $s({functionName:"getUserStatus",code:s});throw t.setError(r).end(),r}})}_isOnlyMeInArray(e){var t=ro();return 1===e.length&&-1<e.indexOf(t)}_dispose(){var e=Bt["notificationCenter"];e.unSubscribeInnerEvent(Jt.MESSAGE_PUSH,e.InnerEventSubType.USER_STATUS_UPDATE,this._onUserStatusUpdate,this),e.unSubscribeInnerEvent(Jt.DESTROY,this._dispose,this),e.unSubscribeInnerEvent(Jt.LOGOUT,this._reset,this),this._reset()}_reset(){this._customStatus=""}}let e_={getUserProfile:{userIDList:{required:!0,rules:["array"],allowEmpty:!1}},updateMyProfile:{nick:{required:!1,rules:["string"],allowEmpty:!0},avatar:{required:!1,rules:["string"],allowEmpty:!0},gender:{required:!1,rules:["string"],allowEmpty:!0},selfSignature:{required:!1,rules:["string"],allowEmpty:!0},allowType:{required:!1,rules:["string"],allowEmpty:!0},birthday:{required:!1,rules:["number"],allowEmpty:!1},language:{required:!1,rules:["string"],allowEmpty:!0},messageSettings:{required:!1,rules:["string"],allowEmpty:!0},adminForbidType:{required:!1,rules:["string"],allowEmpty:!0},level:{required:!1,rules:["number"],allowEmpty:!1},role:{required:!1,rules:["number"],allowEmpty:!0},profileCustomField:{required:!1,rules:["array"],allowEmpty:!0,customValidator:function(e){for(var t of e){if("object"!=typeof t)return"Each item in profileCustomField must be an object";if("string"!=typeof(null==t?void 0:t.key))return"Each item.key in profileCustomField must be a string";if(null==t||!t.key.startsWith(wg))return'Each item.key in profileCustomField must start with "Tag_Profile_Custom"'}return!0}}},setSelfStatus:{customStatus:{required:!0,rules:["string"],allowEmpty:!0}},getUserStatus:{userIDList:{required:!0,rules:["array"],allowEmpty:!1}},subscribeUserStatus:{userIDList:{required:!0,rules:["array"],allowEmpty:!1}},unsubscribeUserStatus:{userIDList:{required:!1,rules:["array"],allowEmpty:!0}}},t_={getMyProfile:!0,getUserProfile:!0,updateMyProfile:!0,setSelfStatus:!0,getUserStatus:!0,subscribeUserStatus:!0,unsubscribeUserStatus:!0};class s_{constructor(){this.userProfile=new Wg,this.userStatus=new Zg,this.userProfile.init(),this.userStatus.init(),Ys({auth:t_,params:e_})}}function o_(t){var s=[];if(_(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(e){e.NOT_START="notStart",e.PENDING="pending",e.RESOLVED="resolved",e.REJECTED="rejected"}(n_=n_||{}),function(e){e[e.C2C=1]="C2C",e[e.GROUP=2]="GROUP"}(i_=i_||{}),function(e){e[e.C2C=8]="C2C",e[e.GROUP=2]="GROUP"}(r_=r_||{});class a_{constructor(){this._name="SyncConversationHandler",this._pagingStatus=n_.NOT_START,this._pagingTimeStamp=0,this._pagingStartIndex=0,this._pagingPinnedTimeStamp=0,this._pagingPinnedStartIndex=0}init(){var e=Bt["notificationCenter"];Js.getInstance().registerWorkflowStep(vs.SYNC_SERVER_INFO_AFTER_RE_ONLINE,fs.CONVERSATION_RECOVER,this._syncConversationList,this),Js.getInstance().registerWorkflowStep(vs.SYNC_SERVER_INFO_AFTER_LOGIN,fs.CONVERSATION_LIST_SYNC,this._syncConversationListAfterLogin,this),e.subscribeInnerEvent(Jt.LOGOUT,this._reset,this),e.subscribeInnerEvent(Jt.DESTROY,this._dispose,this),console.log(this._name+".init")}isSyncCompleted(){return this._pagingStatus===n_.RESOLVED}_syncConversationListAfterLogin(){return h(this,void 0,void 0,function*(){return this._pagingStatus=n_.NOT_START,this._pagingTimeStamp=0,this._pagingStartIndex=0,this._pagingPinnedTimeStamp=0,this._pagingPinnedStartIndex=0,this._syncConversationList()})}_syncConversationList(){return h(this,void 0,void 0,function*(){let e=Bt["ssoLog"],t=e.createSSOLogData({method:"syncConversationList"});try{let e=yield this._pagingGetConversationList(!0);this._pagingStatus=n_.RESOLVED;var{conversationList:s=[]}=e||{};return t.setLogInfo({message:"count:"+s.length}).end(),console.log(this._name+"._syncConversationList ok, count:"+s.length),e}catch(e){var{errorCode:s,errorInfo:r}=e,s=new $s({functionName:"syncConversationList",code:s,message:r});t.setError(s).end(),console.error(this._name+"._syncConversationList fail:",s)}})}_pagingGetConversationList(u){return h(this,void 0,void 0,function*(){try{var e,t=[],s=(this._pagingStatus=n_.PENDING,yield function(o){return h(this,void 0,void 0,function*(){var{fromAccount:e,pagingTimeStamp:t,pagingStartIndex:s,pagingPinnedTimeStamp:r,pagingPinnedStartIndex:n}=o;return so({servcmd:"recentcontact.page_get",data:{AssistFlags:31,MsgAssistFlags:15,OrderType:1,From_Account:e,StartIndex:s,TimeStamp:t,TopStartIndex:n,TopTimeStamp:r}})})}({fromAccount:ro(),pagingTimeStamp:u?this._pagingTimeStamp:0,pagingStartIndex:u?this._pagingStartIndex:0,pagingPinnedTimeStamp:u?this._pagingPinnedTimeStamp:0,pagingPinnedStartIndex:u?this._pagingPinnedStartIndex:0})),{CompleteFlag:r,SessionItem:n=[],TimeStamp:o,StartIndex:i,TopTimeStamp:a,TopStartIndex:l}=s||{};if(0<n.length){let e=this._getConversationOptions(n);t.push(...e);var c=Bt["notificationCenter"];c.emitInnerEvent(Jt.SYNC_CONVERSATION_LIST,{conversationUpdateFieldList:e})}return this._pagingTimeStamp=o,this._pagingStartIndex=i,this._pagingPinnedTimeStamp=a,this._pagingPinnedStartIndex=l,1!==r&&(e=(yield this._pagingGetConversationList(u))["conversationList"],t.push(...e)),{conversationList:t}}catch(e){throw console.error(this._name+"._pagingGetConversationList fail:",e),e}})}_getConversationOptions(e){let{isUndefined:t}=Bt["utils"],s=this._convertConversationKey(e);return this._filterValidConversations(s).map(e=>(t(e.lastMsg)&&(e.lastMsg={elements:[]}),e.type===i_.C2C?this._assembleC2COption(e):this._assembleGroupOption(e)))}_filterValidConversations(e){return e.filter(({type:e,userID:t})=>e===i_.C2C&&!function(e){let t;return"@TLS#ERROR"===(t=e.startsWith(gs.CONV_C2C)?e.replace(gs.CONV_C2C,""):t)||"@TLS#NOT_FOUND"===t}(t)||2===e)}_assembleC2COption(e){var t,s=this._createUserprofile(e);return{conversationID:""+gs.CONV_C2C+e.userID,type:gs.CONV_C2C,lastMessage:{lastTime:e.time,lastSequence:e.sequence,fromAccount:e.lastC2CMsgFromAccount,type:null!=(t=e.lastMsg)&&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===r_.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:o_(e.standardMark),conversationGroupList:[],remark:e.friendRemark||"",messageRemindType:this._transMsgRemindType(e.messageRemindType)}}_createUserprofile(e){var{userID:e,nick:t,peerAvatar:s}=e,t=[{tag:"Tag_Profile_IM_Nick",value:t},{tag:"Tag_Profile_IM_Image",value:s}];return null==(s=Bt.user.userProfile)?void 0:s.createProfile(e,t)}_computeIsPeerRead(e){var{lastC2CMsgFromAccount:e,time:t,c2cPeerReadTime:s}=e;return e===ro()&&t<=s}_assembleGroupOption(e){var t;return{conversationID:""+gs.CONV_GROUP+e.groupID,type:gs.CONV_GROUP,lastMessage:Object.assign(Object.assign({lastTime:e.time,lastSequence:e.sequence,fromAccount:e.msgGroupFromAccount},this._patchTypeAndPayload(e)),{cloudCustomData:(null==(t=e.lastMsg)?void 0:t.cloudCustomData)||"",isRevoked:e.lastMessageFlag===r_.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:o_(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=Bt["utils"]["isEmpty"];if(t(e))return null;let s="",r=null;return e.MsgBody&&(s=null==(t=e.MsgBody[0])?void 0:t.MsgType,r=this._parseContent(s,e.MsgBody[0])),{event:e.Event,elements:[{type:s,content:r,cloudCustomData:e.CloudCustomData}],revokerInfo:{revoker:null==(t=e.RevokerInfo)?void 0:t.revoker}}}_parseContent(e,t){return t&&((e=Bt.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){let t="";return 0===e?t=gs.MSG_REMIND_ACPT_AND_NOTE:1===e?t=gs.MSG_REMIND_DISCARD:2===e?t=gs.MSG_REMIND_ACPT_NOT_NOTE:3===e&&(t=gs.NOT_RECEIVE_OFFLINE_PUSH_EXCEPT_AT),t}_patchTypeAndPayload(e){var t=Bt["utils"]["isUndefined"],{event:e,elements:s=[]}=e.lastMsg||{};return t(e)?{type:s[0]?s[0].type:null,payload:s[0]?this._amendLayersOverLimitProp(s[0].content):null}:{type:gs.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=n_.NOT_START,this._pagingTimeStamp=0,this._pagingStartIndex=0,this._pagingPinnedTimeStamp=0,this._pagingPinnedStartIndex=0}_dispose(){this._reset();var e=Bt["notificationCenter"];e.unSubscribeInnerEvent(Jt.LOGOUT,this._reset,this),e.unSubscribeInnerEvent(Jt.DESTROY,this._dispose,this)}}class c_{constructor(){this.syncConversationHandler=new a_,this.syncConversationHandler.init()}}console.log("TencentCloudLiteChat.VERSION:"+He);var u_={create:function(e){var{SDKAppID:e,testEnv:t=!1,devMode:s=!1,unlimitedAVChatRoom:r=!1,scene:n="",oversea:o=!1,instance:i,disableIndependentDomain:a=!1}=e,l=e;if("number"!=typeof l&&(e=Number(l),Number.isNaN(e)))return console.error("Create SDK instance failed. Failed to parse the SDKAppID, please check the arguments"),null;if(l=Number(l),Qs.has(l))return Qs.get(l);let c=null;if(i)(c=i)._workflowManager&&Js.setInstance(c._workflowManager),c._pluginManager&&c._pluginManager.installBuiltInPlugin(vh),!i.isReady()||null!=(i=(e=Js.getInstance()).executeWorkflow)&&i.call(e,vs.SYNC_SERVER_INFO_AFTER_LOGIN);else{let e=""+(u()+u())+u()+u()+u()+u()+u()+u();Bt.init({sdkAppId:l,instanceId:e,testEnv:t,devMode:s,unlimitedAVChatRoom:r,disableIndependentDomain:a,scene:n,oversea:o,sdkEdition:mh}),Js.getInstance().init(),Bt.message=new Lg,Bt.user=new s_,Bt.login=new Rh,Bt.conversation=new c_,Ih.getInstance().installBuiltInPlugin(vh),(c=Ah.getInstance().exposeApiForClient())._workflowManager=Js.getInstance(),c._pluginManager=Ih.getInstance()}function u(){return(65536*(1+Math.random())|0).toString(16).substring(1)}return Qs.set(l,c),c},TSignaling:Qt,EVENT:Yt,VERSION:He,TYPES:gs};export{u_ as default};
|