@tencentcloud/lite-chat 1.6.0 → 1.6.2-beta.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/professional.js CHANGED
@@ -1 +1 @@
1
- !function(e,t){"object"==typeof exports&&"undefined"!=typeof module?module.exports=t():"function"==typeof define&&define.amd?define(t):(e="undefined"!=typeof globalThis?globalThis:e||self).TencentCloudChat=t()}(this,function(){class P{constructor(){this.listeners={}}on(e,t,s){this.listeners[e]||(this.listeners[e]=[]),this.listeners[e].push({fn:t,context:s})}off(e,s,r){s&&(this.listeners[e]=null==(e=this.listeners[e])?void 0:e.filter(e=>{var t=e.fn===s,e=!r||e.context===r;return!(t&&e)}))}emit(e,...s){e=this.listeners[e];e&&e.forEach(e=>{var{fn:e,context:t}=e;e.apply(t,s)})}once(t,s,r){let i=(...e)=>{s.apply(r,e),this.off(t,i)};this.on(t,i)}}let w={ANDROID:2,IOS:3,MAC:4,WEB:7,WX_MP:8,QQ_MP:9,TT_MP:10,BAIDU_MP:11,ALI_MP:12,IPAD:13,UNI_NATIVE_APP:15,DONUT_NATIVE_APP:19,NS_NATIVE_APP:20,RN_NATIVE_APP:21},U=["heartbeat.alive","im_open_status.wslogin","im_open_status.wslogout","group_open_long_polling_http_svc.get_msg","group_open_long_polling_http_noauth_svc.get_msg"];var i,q;(e=i=i||{})[e.DEBUG=0]="DEBUG",e[e.INFO=1]="INFO",e[e.WARN=2]="WARN",e[e.ERROR=3]="ERROR",e[e.NONE=4]="NONE";let x="LiteChat",V={[i.DEBUG]:console.debug,[i.INFO]:console.info,[i.WARN]:console.warn,[i.ERROR]:console.error},B={[i.INFO]:4,[i.WARN]:5,[i.ERROR]:6};(e=q=q||{})[e.CONV_DELETED=1]="CONV_DELETED",e[e.CONV_PINED=2]="CONV_PINED",e[e.CONV_UNPINED=3]="CONV_UNPINED",e[e.CONV_MARK_UPDATED=4]="CONV_MARK_UPDATED",e[e.CONV_GROUP_ADDED=5]="CONV_GROUP_ADDED",e[e.CONV_GROUP_DELETED=6]="CONV_GROUP_DELETED",e[e.CONV_GROUP_UPDATED=7]="CONV_GROUP_UPDATED";var r,j,K,e=Object.freeze({__proto__:null,CONSOLE_METHOD:V,CloudConfigReportLevelMap:B,get ConvModifyPushType(){return q},DEFAULT_GLOBAL_MAX_TOTAL_COUNT:50,DEFAULT_GLOBAL_THROTTLE_TIME:5e3,DEFAULT_SINGLE_MAX_TOTAL_COUNT:2,DEFAULT_SINGLE_THROTTLE_TIME:1e3,ENUM_PLATFORM:w,IS_TOPIC_MESSAGE:2,get LogLevel(){return i},NOT_NEED_CRC_SERVCMD:U,SDK_NAME:x});(t=r=r||{}).BUSINESS_COMMAND="business_command",t.C2C_REALTIME_MESSAGE="c2c_realtime_message",t.C2C_MESSAGE_MODIFIED="c2c_message_modified",t.C2C_REVOKED_MESSAGE="c2c_message_revoked",t.GROUP_REALTIME_MESSAGE="group_realtime_message",t.GROUP_MESSAGE_MODIFIED="group_message_modified",t.GROUP_MESSAGE_REVOKED="group_message_revoked",t.C2C_MESSAGE_READ_RECEIPT="c2c_message_read_receipt",t.MESSAGE_REACTION_UPDATED="message_reaction_updated",t.MESSAGE_REACTION_UPDATED_SYNC="message_reaction_updated_sync",t.GROUP_AT_TIPS="group_at_tips",t.USER_STATUS_UPDATE="user_status_update",t.FRIEND_LIST_MODIFIED="friend_list_modified",t.PROFILE_MODIFIED="profile_modified",t.CONV_MODIFIED="conversation_modified",t.GROUP_TIPS_NOTIFICATION="group_tips_notification",t.GROUP_MESSAGE_READ_RECEIPT="group_message_read_receipt",t.GROUP_MESSAGE_READ_SYNC="group_message_read_sync",t.GROUP_SYSTEM_NOTIFICATION="group_system_notification",t.C2C_MESSAGE_PEER_READ="c2c_message_peer_read",t.C2C_MESSAGE_READ_SYNC="c2c_message_read_sync",t.C2C_REMIND_TYPE_SYNC="c2c_remind_type_sync",t.FOLLOW_LIST_UPDATED="follow_list_updated",t.MESSAGE_EXTENSIONS_UPDATED="message_extensions_updated",t.ALL_MESSAGE_READ="all_message_read",t.CONVERSATION_MARK_UPDATED="conversation_mark_updated",t.CONVERSATION_GROUP_ADD="conversation_group_add",t.CONVERSATION_GROUP_DELETED="conversation_group_deleted",t.CONVERSATION_GROUP_UPDATED="conversation_group_updated",t.ALL_RECEIVE_MESSAGE_OPTION="all_receive_message_option",t.TOPIC_AT_TIPS="topic_at_tips",t.TOPIC_TIPS_NOTIFICATION="topic_tips_notification",t.TOPIC_SYSTEM_NOTIFICATION="topic_system_notification",t.TOPIC_MESSAGE_READ_SYNC="topic_message_read_sync",t.TOPIC_LATEST_MESSAGE="topic_latest_message",t.GROUP_MESSAGE_PINNED="group_message_pinned";let W=[16,17];function H(e){let t,s=[];return null!=(t=null==e?void 0:e.GroupTips)&&t.forEach(e=>{2===e.GroupInfo.MillionGroupFlag?s.push(r.TOPIC_TIPS_NOTIFICATION):W.includes(null==(e=null==e?void 0:e.MsgBody)?void 0:e.OpType)?s.push(r.GROUP_MESSAGE_PINNED):s.push(r.GROUP_TIPS_NOTIFICATION)}),s}let Y=[{conditions:[{type:"event",value:100}],subType:r.BUSINESS_COMMAND},{conditions:[{type:"event",value:24}],subType:r.ALL_RECEIVE_MESSAGE_OPTION},{conditions:[{type:"event",value:26}],subType:r.TOPIC_LATEST_MESSAGE},{conditions:[{type:"hasKey",value:"C2cMsgArray"}],subType:r.C2C_REALTIME_MESSAGE},{conditions:[{type:"hasKey",value:"C2cMsgModNotifys"}],subType:r.C2C_MESSAGE_MODIFIED},{conditions:[{type:"hasKey",value:"ProfileDataMod"}],subType:r.PROFILE_MODIFIED},{conditions:[{type:"hasKey",value:"UserStatusList"}],subType:r.USER_STATUS_UPDATE},{conditions:[{type:"hasKey",value:"FriendListMod"}],subType:r.FRIEND_LIST_MODIFIED},{conditions:[{type:"hasKey",value:"GroupMsgArray"}],subType:r.GROUP_REALTIME_MESSAGE},{conditions:[{type:"hasKey",value:"GroupMsgModNotifys"}],subType:r.GROUP_MESSAGE_MODIFIED},{conditions:[{type:"hasKey",value:"C2cNotifyMsgArray"}],subTypeParser:function(e){let t,s=[];return null!=(t=null==e?void 0:e.C2cNotifyMsgArray)&&t.forEach(e=>{e.WithdrawC2cMsgNotify&&s.push(r.C2C_REVOKED_MESSAGE),e.C2cReadedReceipt&&s.push(r.C2C_MESSAGE_PEER_READ),e.ReadC2cMsgNotify&&s.push(r.C2C_MESSAGE_READ_SYNC),e.MuteNotificationsSync&&s.push(r.C2C_REMIND_TYPE_SYNC)}),s}},{conditions:[{type:"hasKey",value:"GroupTips"},{type:"event",value:4}],subTypeParser:H},{conditions:[{type:"hasKey",value:"GroupTips"},{type:"event",value:5}],subTypeParser:function(e){let t,s=[];return null!=(t=null==e?void 0:e.GroupTips)&&t.forEach(e=>{Array.isArray(e.MsgBody.GroupWithdrawInfoArray)?s.push(r.GROUP_MESSAGE_REVOKED):Array.isArray(e.MsgBody.GroupMsgReceiptList)?s.push(r.GROUP_MESSAGE_READ_RECEIPT):Array.isArray(e.MsgBody.GroupReadInfoArray)?e.MsgBody.GroupReadInfoArray[0].TopicId?s.push(r.TOPIC_MESSAGE_READ_SYNC):s.push(r.GROUP_MESSAGE_READ_SYNC):2===e.GroupInfo.MillionGroupFlag?s.push(r.TOPIC_SYSTEM_NOTIFICATION):s.push(r.GROUP_SYSTEM_NOTIFICATION)}),s}},{conditions:[{type:"hasKey",value:"GroupTips"},{type:"event",value:6}],subTypeParser:H},{conditions:[{type:"hasKey",value:"GroupTips"},{type:"event",value:12}],subTypeParser:function(e){let t,s=[];return null!=(t=null==e?void 0:e.GroupTips)&&t.forEach(e=>{var e=e["GroupAtTips"]["TopicId"];e?s.push(r.TOPIC_AT_TIPS):s.push(r.GROUP_AT_TIPS)}),s}},{conditions:[{type:"hasKey",value:"RecentContactMod"}],subTypeParser:function(e){let t,s=[];return null!=(t=null==e?void 0:e.RecentContactMod)&&t.forEach(e=>{switch(e.PushType){case q.CONV_MARK_UPDATED:s.push(r.CONVERSATION_MARK_UPDATED);break;case q.CONV_GROUP_ADDED:s.push(r.CONVERSATION_GROUP_ADD);break;case q.CONV_GROUP_DELETED:s.push(r.CONVERSATION_GROUP_DELETED);break;case q.CONV_GROUP_UPDATED:s.push(r.CONVERSATION_GROUP_UPDATED);break;default:s.push(r.CONV_MODIFIED)}}),s}},{conditions:[{type:"hasKey",value:"MsgReactionNotifyList"}],subType:r.MESSAGE_REACTION_UPDATED},{conditions:[{type:"hasKey",value:"MsgReactionNotify"}],subType:r.MESSAGE_REACTION_UPDATED_SYNC},{conditions:[{type:"hasKey",value:"C2cMsgInfo"}],subType:r.C2C_MESSAGE_READ_RECEIPT},{conditions:[{type:"hasKey",value:"FollowChangeList"}],subType:r.FOLLOW_LIST_UPDATED},{conditions:[{type:"hasKey",value:"MsgExtensionNotify"}],subType:r.MESSAGE_EXTENSIONS_UPDATED},{conditions:[{type:"hasKey",value:"C2CReadAllMsg"}],subType:r.ALL_MESSAGE_READ}];function $(r){let e,t=Array.isArray(null==(e=null==r?void 0:r.body)?void 0:e.EventArray)?r.body.EventArray:[],i=[];return t.forEach(t=>{t.Flag=r.body.Flag;var e=Y.find(e=>e.conditions.every(e=>{switch(e.type){case"event":return t.Event===e.value;case"hasKey":return Object.prototype.hasOwnProperty.call(t,e.value);default:return!1}}));if(!e)return null;let s=[];"function"==typeof e.subTypeParser?s=e.subTypeParser(t):e.subType&&(s=e.subType),Array.isArray(s)?s.forEach(e=>{i.push({type:j.SERVER_PUSH_MESSAGE+":"+e,data:t})}):i.push({type:j.SERVER_PUSH_MESSAGE+":"+s,data:t})}),i}(t=j=j||{}).SERVER_PUSH_MESSAGE="im_open_push.msg_push",t.SERVER_PUSH_MESSAGE_MULTIPLE="im_open_push.multi_msg_push_ws",t.ERROR="error";let z={[j.SERVER_PUSH_MESSAGE]:$,[j.SERVER_PUSH_MESSAGE_MULTIPLE]:$,[j.ERROR]:function(e){var t=e["errorCode"];return[{type:"error:"+t,data:e}]}},J=new class{constructor(){this._outerEventEmitter=null,this._innerEventEmitter=null,this._outerEventEmitter=new P,this._innerEventEmitter=new P,this.InnerEventSubType=r}subscribeInnerEvent(s,r,i,n){var o,t;if(["string","number"].includes(typeof r)){let e=r,t=i;null!=(o=this._innerEventEmitter)&&o.on(s+":"+e,t,n)}else{let e=r;null!=(t=this._innerEventEmitter)&&t.on(s,e,i)}}emitInnerEvent(t,s){var e;if(null!=(e=this._innerEventEmitter)&&e.emit(t,s),Object.keys(z).includes(t)){let e=null==(t=z[t])?void 0:t.call(z,s);null!=e&&e.forEach(e=>{var t;e&&null!=(t=this._innerEventEmitter)&&t.emit(e.type,e.data)})}}unSubscribeInnerEvent(s,r,i,n){var o,t;if(["string","number"].includes(typeof r)){let e=r,t=i;null!=(o=this._innerEventEmitter)&&o.off(s+":"+e,t,n)}else{let e=r;null!=(t=this._innerEventEmitter)&&t.off(s,e,i)}}subscribeOuterEvent(e,t,s){var r;null!=(r=this._outerEventEmitter)&&r.on(e,t,s)}unSubscribeOuterEvent(e,t,s){var r;null!=(r=this._outerEventEmitter)&&r.off(e,t,s)}emitOuterEvent(e,t){var s;null!=(s=this._outerEventEmitter)&&s.emit(e,t)}getOuterEventEmitter(){return this._outerEventEmitter}rest(){this._outerEventEmitter=null,this._innerEventEmitter=null}};function f(e,t){var s={};for(i in e)Object.prototype.hasOwnProperty.call(e,i)&&t.indexOf(i)<0&&(s[i]=e[i]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols)for(var r=0,i=Object.getOwnPropertySymbols(e);r<i.length;r++)t.indexOf(i[r])<0&&Object.prototype.propertyIsEnumerable.call(e,i[r])&&(s[i[r]]=e[i[r]]);return s}function I(e,o,a,u){return new(a=a||Promise)(function(s,t){function r(e){try{n(u.next(e))}catch(e){t(e)}}function i(e){try{n(u.throw(e))}catch(e){t(e)}}function n(e){var t;e.done?s(e.value):((t=e.value)instanceof a?t:new a(function(e){e(t)})).then(r,i)}n((u=u.apply(e,o||[])).next())})}let Q=e=>void 0===e,X=e=>"string"==typeof e,Z=e=>{return null==(e=Object.prototype.toString.call(e).match(/^\[object (.*)\]$/))?void 0:e[1].toLowerCase()},ee=e=>"function"==typeof Array.isArray?Array.isArray(e):"array"===Z(e),te=e=>null!==e&&"object"==typeof e,se=e=>ee(e)||te(e),re=e=>{return"string"==typeof e&&(e=e[0],!/[^a-zA-Z0-9]/.test(e))},ie=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 ne(e=99999999){return Math.round(Math.random()*e)}let oe=(s,r,i,n)=>{if(!se(s)||!se(r))return 0;let o=0;var a,u=Object.keys(r);for(let e=0,t=u.length;e<t;e++)if(a=u[e],!(Q(r[a])||i&&i.includes(a)))if(se(s[a])&&se(r[a]))o+=oe(s[a],r[a],i,n);else{if(n&&n.includes(r[a]))continue;s[a]!==r[a]&&(s[a]=r[a],o+=1)}return o};function ae(s){let r,i,n=s,o="";for(let e=0,t=(n=s.length%8!=0?"0".repeat(8-s.length%8)+s:n)["length"];e<t;e+=8)r=parseInt(n.slice(e,e+4),2),i=parseInt(n.slice(e+4,e+8),2),o+=base16Map.get(r)+base16Map.get(i);return o}let ue="undefined"!=typeof wx&&"function"==typeof wx.getSystemInfoSync&&("mac"===wx.getSystemInfoSync().platform||"windows"===wx.getSystemInfoSync().platform),le="undefined"!=typeof wx&&"function"==typeof wx.getSystemInfoSync&&Boolean(wx.getSystemInfoSync().fontSizeSetting)||ue,ce=le&&"function"==typeof wx.createGamePortal,de="undefined"!=typeof qq&&"function"==typeof qq.getSystemInfoSync&&Boolean(qq.getSystemInfoSync().fontSizeSetting),pe="undefined"!=typeof tt&&"function"==typeof tt.getSystemInfoSync&&Boolean(tt.getSystemInfoSync().fontSizeSetting),he="undefined"!=typeof swan&&"function"==typeof swan.getSystemInfoSync&&Boolean(swan.getSystemInfoSync().fontSizeSetting),ge="undefined"!=typeof my&&"function"==typeof my.getSystemInfoSync&&Boolean(my.getSystemInfoSync().fontSizeSetting),_e="undefined"!=typeof jd&&"function"==typeof jd.getSystemInfoSync,me="undefined"!=typeof uni&&"undefined"==typeof window&&"function"==typeof uni.requireNativePlugin,ve=le&&"object"==typeof wx.miniapp,fe="undefined"!=typeof uni,Ie=le||de||pe||he||ge||me||_e,Ee="undefined"==typeof window&&!Ie&&"undefined"!=typeof global&&void 0!==global.NativeScriptGlobals,Ce="undefined"!=typeof global&&(void 0!==global.nativeModuleProxy||void 0!==global.ReactNative),Se="undefined"!=typeof wx&&"function"==typeof wx.getAccountInfoSync&&Boolean(wx.getAccountInfoSync().plugin),Me="undefined"!=typeof uni?!Ie:"undefined"!=typeof window&&!Ie&&!Ce,ye=de?qq:pe?tt:he?swan:ge?my:le?wx:me?uni:_e?jd:{},s=Me&&window&&window.navigator&&window.navigator.userAgent||"",Te=/(micromessenger|webbrowser)/i.test(s),Ae=function(){let e="WEB";return Te?e="WEB":de?e="QQ_MP":pe?e="TT_MP":he?e="BAIDU_MP":ge?e="ALI_MP":le?e=ve?"DONUT_NATIVE_APP":"WX_MP":me?e="UNI_NATIVE_APP":Ee?e="NS_NATIVE_APP":Ce&&(e="RN_NATIVE_APP"),w[e]}(),Oe=/iPad/i.test(s),De=/iPhone/i.test(s)&&!Oe,Re=/iPod/i.test(s),Le=De||Oe||Re,Ne=(t=s.match(/OS (\d+)_/i))&&t[1]?t[1]:null,be=/Android/i.test(s),Ge=(t=s.match(/Android (\d+)(?:\.(\d+))?(?:\.(\d+))*/i))?(it=t[1]&&parseFloat(t[1]),K=t[2]&&parseFloat(t[2]),it&&K?parseFloat(t[1]+"."+t[2]):it||null):null,Pe=/Firefox/i.test(s),we=/Edge/i.test(s),Ue=!we&&/Chrome/i.test(s),ke=/MSIE/.test(s)||-1<s.indexOf("Trident")&&-1<s.indexOf("rv:11.0"),Fe=function(){var e=/MSIE\s(\d+)\.\d/.exec(s);let t=e&&parseFloat(e[1]);return t=!t&&/Trident\/7.0/i.test(s)&&/rv:11.0/.test(s)?11:t}(),qe=/Safari/i.test(s)&&!Ue&&!be&&!we,xe=/Windows/i.test(s),Ve=/MAC OS X/i.test(s),Be=Me&&"undefined"!=typeof Worker&&!ke,je=be||Le,Ke=Me&&void 0!==window.tencent_cloud_im_csig_flutter_for_web_25F_cy,We="undefined"!=typeof window&&void 0!==window.navigator&&(K=window.navigator["standalone"],!(!Le||K||qe));function He(){let e="unknown";if(Ve&&(e="mac"),xe&&(e="windows"),Le&&(e="ios"),be&&(e="android"),Ie)try{var t=ye.getSystemInfoSync()["platform"];void 0!==t&&(e=t)}catch(e){console.error(e)}return e}let Ye="application/x-www-form-urlencoded;charset=UTF-8";function $e(e){return I(this,arguments,void 0,function*({method:i,url:n,data:o,timeout:a=3e3}){return new Promise(Ie?(t,e)=>{ye.request({url:n,data:o,method:i,timeout:a,header:{"content-type":Ye},success:e=>t(e.data),fail:()=>e(new Error('{"message":"Network error","code":2800}'))})}:(t,e)=>{let s=new XMLHttpRequest,r=setTimeout(()=>{s.abort(),e(new Error('{"message":"Request timeout","code":2801}'))},a);s.onreadystatechange=function(){if(4===s.readyState)if(clearTimeout(r),200===s.status||304===s.status)try{t(s.responseText?JSON.parse(s.responseText):null)}catch(e){t(s.responseText)}else e(new Error('{"message":"Network error","code":2800}'))},s.open(i,n,!0),s.setRequestHeader("Content-type",Ye),s.send(o||null)})})}function ze(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(ie(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 Je(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(Je(t),Je(e))}),s}if(r instanceof Set){let t=new Set;return r.forEach(e=>{t.add(Je(e))}),t}if(Array.isArray(r))return r.map(e=>Je(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]=Je(r[e]))}),s}function Qe(e,s,t){let r=new WeakSet;try{return JSON.stringify(e,(e,t)=>{if(void 0===(t=s?s(e,t):t))return"undefined";if(null===t)return null;if(Number.isNaN(t))return"NaN";if(t===1/0)return"Infinity";if(t===-1/0)return"-Infinity";if("function"==typeof t)return`[Function: ${t.name||"anonymous"}]`;if("symbol"==typeof t)return t.toString();if("bigint"==typeof t)return t.toString()+"n";if("object"==typeof t&&null!==t){if(r.has(t))return"[Circular]";r.add(t)}return t instanceof Date?t.toISOString():t instanceof Error?{name:t.name,message:t.message,stack:t.stack}:t instanceof Map?{dataType:"Map",value:Array.from(t.entries())}:t instanceof Set?{dataType:"Set",value:Array.from(t.values())}:t},t)}catch(e){return console.error("Failed to stringify:",e),""}}function Xe(){let s,r;return{promise:new Promise((e,t)=>{s=e,r=t}),resolve:s,reject:r}}var t=Object.freeze({__proto__:null,ANDROID_VERSION:Ge,IE_VERSION:Fe,IN_ALIPAY_MINI_APP:ge,IN_BAIDU_MINI_APP:he,IN_BROWSER:Me,IN_DONUT_NATIVE_APP:ve,IN_JD_MINI_APP:_e,IN_MINI_APP:Ie,IN_NS_NATIVE_APP:Ee,IN_QQ_MINI_APP:de,IN_RN_APP:Ce,IN_TT_MINI_APP:pe,IN_UNI_APP:fe,IN_UNI_NATIVE_APP:me,IN_WX_MINI_APP:le,IN_WX_MINI_APP_DESK:ue,IN_WX_MINI_GAME:ce,IN_WX_MINI_PLUGIN:Se,IOS_VERSION:Ne,IS_ANDROID:be,IS_CHROME:Ue,IS_EDGE:we,IS_FIREFOX:Pe,IS_IE:ke,IS_IOS:Le,IS_IPAD:Oe,IS_IPHONE:De,IS_IPOD:Re,IS_MAC:Ve,IS_SAFARI:qe,IS_WECHAT:Te,IS_WIN:xe,IS_WORKER_AVAILABLE:Be,MINI_APP_NAMESPACE:ye,USER_AGENT:s,base16EncodeBinaryString:ae,deepCopyWithMethods:Je,deepMerge:oe,generatePromise:Xe,getPlatformType:He,getType:Z,httpRequest:$e,isArray:ee,isArrayOrObject:se,isEmpty:ze,isFlutterWeb:Ke,isH5:je,isIOSWebView:We,isNumber:e=>null!==e&&("number"==typeof e&&!Number.isNaN(+e)||"object"==typeof e&&e.constructor===Number),isObject:te,isPlainObject:ie,isString:X,isUndefined:Q,isValidRequestKey:re,platform:Ae,randomInt:ne,randomString:function(){let t="";for(let e=32;0<e;--e)t+="0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"[Math.floor(62*Math.random())];return t},safeStringify:Qe});class Ze{constructor(){this._socket=null}connectSocket(e){return this._socket=new WebSocket(e),this._socket}send(e){var t;try{null!=(t=this._socket)&&t.send(e)}catch(e){null!=(t=this._onSendFail)&&t.call(this,e)}}bindSocketHandlers(e){var{onOpen:e,onMessage:t,onClose:s,onError:r,onSendFail:i}=e;this._socket&&(this._socket.binaryType="arraybuffer",this._socket.onopen=e,this._socket.onmessage=t,this._socket.onclose=s,this._socket.onerror=r,this._onSendFail=i)}unbindSocketHandlers(){this._socket&&(this._socket.onopen=null,this._socket.onmessage=null,this._socket.onclose=null,this._socket.onerror=null)}disconnect(){this._socket&&(this._socket.close(),this._socket=null)}}class et{connectSocket(e){return this._socket=ye.connectSocket({url:e,header:{"content-type":"application/json"},complete:()=>{}}),this._socket}send(e){var t;null!=(t=this._socket)&&t.send({data:e,fail:this._onSendFail})}bindSocketHandlers(e){var{onOpen:e,onMessage:t,onClose:s,onError:r,onSendFail:i}=e;this._socket.onClose(s),this._socket.onOpen(e),this._socket.onMessage(t),this._socket.onError(r),this._onSendFail=i}unbindSocketHandlers(){this._socket&&(this._socket.onClose(()=>{}),this._socket.onOpen(()=>{}),this._socket.onMessage(()=>{}),this._socket.onError(()=>{}))}disconnect(){this._socket&&(this._socket.close(),this._socket=null)}}class st{constructor(){this._worker=null,this._blobUrl=null}connectSocket(e){var t=new Blob(["\n let _socket = null;\n\n self.onmessage = (event) => {\n const { type, url, data } = event.data;\n\n switch (type) {\n case 'CONNECT':\n connectSocket(url);\n break;\n case 'SEND':\n send(data);\n break;\n case 'DISCONNECT':\n disconnect();\n break;\n }\n };\n\n function connectSocket(url) {\n _socket = new WebSocket(url);\n _socket.binaryType = 'arraybuffer';\n bindSocketHandlers();\n return _socket;\n }\n\n function send(packet) {\n try {\n _socket?.send(packet);\n } catch (error) {\n self.postMessage({\n type: 'SEND_FAIL', \n error: {\n message: error.message,\n name: error.name,\n },\n });\n }\n }\n\n function bindSocketHandlers() {\n if (_socket) {\n _socket.onopen = (event) => {\n self.postMessage({\n type: 'OPEN',\n data: {\n type: event.type,\n timeStamp: event.timeStamp,\n },\n });\n };\n\n _socket.onmessage = (event) => {\n self.postMessage({ \n type: 'MESSAGE',\n data: event.data,\n });\n };\n\n _socket.onclose = (event) => {\n self.postMessage({ \n type: 'CLOSE', \n data: { \n code: event.code,\n reason: event.reason,\n timeStamp: event.timeStamp,\n },\n });\n };\n\n _socket.onerror = (error) => {\n self.postMessage({\n type: 'ERROR',\n data: {\n message: error.message,\n name: error.name\n },\n });\n };\n }\n }\n\n function unbindSocketHandlers() {\n if (_socket) {\n _socket.onopen = null;\n _socket.onmessage = null;\n _socket.onclose = null;\n _socket.onerror = null;\n }\n }\n\n function disconnect() {\n if (_socket) {\n _socket.close();\n _socket = null;\n }\n }\n"],{type:"application/javascript"});this._worker=new Worker(URL.createObjectURL(t)),this._worker.postMessage({type:"CONNECT",url:e})}send(e){var t;try{null!=(t=this._worker)&&t.postMessage({type:"SEND",data:e})}catch(e){null!=(t=this._onSendFail)&&t.call(this,e)}}bindSocketHandlers(e){var{onOpen:t,onMessage:r,onClose:i,onError:n,onSendFail:o}=e;if(this._worker){let s={OPEN:t,MESSAGE:r,CLOSE:i,ERROR:n,SEND_FAIL:o};this._onSendFail=o,this._worker.onmessage=e=>{var t=((null==e?void 0:e.data)||{})["type"];"function"==typeof s[t]&&null!=(t=s[t])&&t.call(s,null==e?void 0:e.data)}}}unbindSocketHandlers(){this._worker&&(this._worker.onmessage=null)}disconnect(){this._worker&&(this._worker.postMessage({type:"DISCONNECT"}),this._worker.terminate(),this._worker=null),this._blobUrl&&(URL.revokeObjectURL(this._blobUrl),this._blobUrl=null)}}var rt,it,c=new class{constructor(){this._store=new Map}get(e){return this._store.get(e)}getStorage(e){return Ie?ge?my.getStorageSync({key:e}).data:ye.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){Ie?ge?my.setStorageSync({key:e,data:JSON.stringify(t)}):ye.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}};(it=rt=rt||{})[it.CONNECTED=0]="CONNECTED",it[it.CONNECTING=1]="CONNECTING",it[it.DISCONNECTED=2]="DISCONNECTED";class nt{constructor(e){this._url="",this._readyState=rt.DISCONNECTED,this._url=e,this._id=ne(),this._emitter=new P,le||me?this._socket=new et:this._canUseWebWorker()?this._socket=new st:this._socket=new Ze,this.connect()}connect(){this.doOpen(),this._bindSocketHandlers()}doOpen(){[rt.CONNECTED,rt.CONNECTING].includes(this._readyState)||(this._readyState=rt.CONNECTING,this._ws=this._socket.connectSocket(this._url))}send(e){this._readyState!==rt.CONNECTED?this.reconnect():this._socket.send(e)}reconnect(){[rt.CONNECTED,rt.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===rt.CONNECTED}disconnect(){this._readyState=rt.DISCONNECTED,this._unbindSocketHandlers(),this._socket.disconnect()}_onOpen(e){this._readyState===rt.CONNECTING&&(this._readyState=rt.CONNECTED,this._emitter.emit("connect",{socketId:this._id,event:e}))}_onMessage(e){this._emitter.emit("message",e)}_onClose(e){this._readyState=rt.DISCONNECTED,this._emitter.emit("close",{socketId:this._id,event:e})}_onError(e){this._readyState=rt.DISCONNECTED,this._emitter.emit("error",{socketId:this._id,error:e})}_onSendFail(e){this._readyState=rt.DISCONNECTED,this._emitter.emit("sendFail",{socketId:this._id,error:e})}_bindSocketHandlers(){this._socket.bindSocketHandlers({onOpen:this._onOpen.bind(this),onMessage:this._onMessage.bind(this),onClose:this._onClose.bind(this),onError:this._onError.bind(this),onSendFail:this._onSendFail.bind(this)})}_unbindSocketHandlers(){this._socket.unbindSocketHandlers()}_canUseWebWorker(){var e=c.get("cloudConfig")||{};return(Q(e.isWorkerEnabled)||"1"===e.isWorkerEnabled)&&Be}}let ot={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"}}},at={SINGAPORE:[[2e7,3e7],[172e7,173e7]],KOREA:[[3e7,4e7],[173e7,174e7]],GERMANY:[[4e7,5e7],[174e7,175e7]],IND:[[5e7,6e7],[175e7,176e7]],JPN:[[6e7,7e7],[176e7,177e7]],USA:[[7e7,8e7],[177e7,178e7]],INDONESIA:[[8e7,9e7],[178e7,179e7]]};function ut(t){var e;if(null!=(e=c.get("instance"))&&e.oversea)return"OVERSEA";for(let e of Object.keys(at))for(var[s,r]of at[e])if(t>=s&&t<r)return e;return"CHINA"}var a,lt="1.6.0";(n=a=a||{}).INITIAL="INITIAL",n.DEFAULT="DEFAULT",n.BACKUP="BACKUP",n.BACKUP_WEB_ONLY="BACKUP_WEB_ONLY",n.BACKUP_CN="BACKUP_CN",n.ANYCAST="ANYCAST",n.IPV6="IPV6";let ct=a.INITIAL;function dt(e,t){var s,{isBinary:t=!1}=t||{},{sdkAppId:r,instanceId:i}=c.get("instance"),n=function e(){var t=Math.random();return 0===t?e():t}(),o=He(),a=function(){var e=He();let t=-1;return"ios"===e?t=Ne||-1:"android"===e&&(t=Ge||-1),t}(),r=(s={sdkappid:r,instanceid:i,random:n,platform:Ae,host:o,version:a,sdkversion:lt},Object.keys(s).map(e=>e+"="+s[e]).join("&"));return t?e+`/binfo?${r}&compress=gzip`:e+"/info?"+r}function pt(e){var{sdkAppId:t,testEnv:s}=c.get("instance"),t=ut(t);if(s)return dt(ot.TEST[t].DEFAULT,{isBinary:e});let r=ot.PRODUCTION[t],i=Me&&r.ANYCAST,n=Me,o=!!r.BACKUP_CN;return dt({[a.INITIAL]:()=>(ct=a.DEFAULT,r.DEFAULT),[a.DEFAULT]:()=>(ct=a.IPV6,r.IPV6),[a.IPV6]:()=>(ct=a.BACKUP,r.BACKUP),[a.BACKUP]:()=>{return n?(ct=a.BACKUP_WEB_ONLY,e=r.BACKUP_WEB_ONLY,t=Math.floor(10001*Math.random())+1e4,e.replace("*",String(t))):o?(ct=a.BACKUP_CN,r.BACKUP_CN):i?(ct=a.ANYCAST,r.ANYCAST):r.DEFAULT;var e,t},[a.BACKUP_WEB_ONLY]:()=>o?(ct=a.BACKUP_CN,r.BACKUP_CN):i?(ct=a.ANYCAST,r.ANYCAST):r.DEFAULT,[a.BACKUP_CN]:()=>(ct=i?a.ANYCAST:a.DEFAULT,r[ct]),[a.ANYCAST]:()=>(ct=a.DEFAULT,r.ANYCAST="",r.DEFAULT)}[ct](),{isBinary:e})}var ht=new class{constructor(){this._timeOffsetWithServer=0}getServerTimeMs(){return Date.now()+this._timeOffsetWithServer}getServerTimeSeconds(){return Math.floor(this.getServerTimeMs()/1e3)}getTimeOffsetWithServer(){return this._timeOffsetWithServer}calculateTimeOffsetWithServer(e,t){var s=Date.now();this._timeOffsetWithServer=t+(s-e)-s}};var gt=new class{constructor(){this._tasks=[],this._timer=null,this._taskMap=new Map}_addTaskToScheduler(e){var t=e["id"];this.removeTask(t),this._tasks.push(e),this._taskMap.set(t,e),this._sort(),this._scheduleNextTask()}_createTask(e){var{id:e,callback:t,context:s,isOnce:r=!1,intervalMs:i=16}=e,n=Math.max(i,16);return{id:e,nextExecuteTime:Date.now()+n,intervalMs:i,callback:t,context:s,isOnce:r}}addTask(e){e=this._createTask(e);this._addTaskToScheduler(e)}addOnceTask(e){e=this._createTask(Object.assign(Object.assign({},e),{isOnce:!0}));this._addTaskToScheduler(e)}removeTask(t){var e=this._tasks.findIndex(e=>e.id===t);-1<e&&(this._tasks.splice(e,1),this._taskMap.delete(t),this._scheduleNextTask())}updateTaskInterval(e,t){e=this._taskMap.get(e);e&&(e.intervalMs=t,e.nextExecuteTime=Date.now()+t,this._sort(),this._scheduleNextTask())}clearAllTasks(){this._tasks=[],this._taskMap.clear(),this._timer&&(clearTimeout(this._timer),this._timer=null)}dispose(){this.clearAllTasks()}_sort(){this._tasks.sort((e,t)=>e.nextExecuteTime-t.nextExecuteTime)}_scheduleNextTask(){this._timer&&(clearTimeout(this._timer),this._timer=null);var e=this._tasks[0];e&&(e=Math.max(0,e.nextExecuteTime-Date.now()),this._timer=setTimeout(()=>this._execute(),e))}_execute(){for(var e=Date.now();this._tasks.length&&this._tasks[0].nextExecuteTime<=e;){var t=this._tasks[0];try{t.context?t.callback.call(t.context):t.callback(),t.isOnce?this.removeTask(t.id):(t.nextExecuteTime=e+t.intervalMs,this._sort())}catch(e){console.warn(`Task ${t.id} execution failed:`,e),t.isOnce&&this.removeTask(t.id)}}this._scheduleNextTask()}};function _t(t){var s=[];for(let e=0;e<t.length;e+=1){var r,i=t.charCodeAt(e);55296<=i&&i<=56319?(r=t.charCodeAt(++e)-56320+(i-55296<<10)+65536,s.push(240|r>>18,128|r>>12&63,128|r>>6&63,128|63&r)):i<=127?s.push(i):i<=2047?s.push(192|i>>6,128|63&i):s.push(224|i>>12,128|i>>6&63,128|63&i)}return new Uint8Array(s)}function mt(e){var t,s=Array.isArray(e)?[]:Object.create(null);for(t in e)Object.prototype.hasOwnProperty.call(e,t)&&re(t)&&null!=e[t]&&(null===e[t]||"object"!=typeof e[t]?s[t]=e[t]:s[t]=mt(e[t]));return s}function vt(e,t){if(U.includes(e))return 0;var s=_t(JSON.stringify(t));let r=4294967295;var i=s["length"];for(let e=0;e<i;e++){r^=s[e];for(let e=0;e<8;e++)1&~r?r>>>=1:r=r>>>1^3988292384}return(4294967295^r)>>>0}function ft(e){var t,{servcmd:e,data:s}=e,r=(r=e,t=c.get("login")||{},i=c.get("instance")||{},{servcmd:r,ver:"v4",platform:Ae,websdkappid:537048168,websdkversion:"1.7.3",a2:t.a2Key||void 0,tinyid:t.tinyID||void 0,status_instid:t.statusInstanceId||0,sdkappid:i.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:ae(""),cappid:t.cappid||0,tjgID:"",seq:Ct(),cs:0}),i=mt(s);return r.cs=vt(e,i),{head:r,body:i}}function It(e){var t,{servcmd:e,data:s}=e,r=(r=e,t=c.get("login")||{},i=c.get("instance")||{},{servcmd:r,ver:"v4",platform:Ae,websdkappid:537048168,websdkversion:"1.7.3",sdkappid:i.sdkAppId,contenttype:"",reqtime:Math.floor(Date.now()/1e3),identifier:"",usersig:"",status_instid:t.statusInstanceId||0,sdkability:75689843,sdkability_ext:ae(""),cappid:t.cappid||0,seq:Ct(),cs:0}),i=mt(s);return r.cs=vt(e,i),{head:r,body:i}}let Et=ne();function Ct(){return Et=Et<2415919103?Et+1:ne()}function St(){var e=c.get("login")||{},t=c.get("instance")||{};return{sdk_type:30,sdk_app_id:t.sdkAppId,sdk_version:"1.6.0",tiny_id:Number(e.tinyID),user_id:e.userId,platform:Ae,instance_id:t.instanceId,trace_id:(new Date).getTime()}}var Mt,n=Object.freeze({__proto__:null,generateCosSpecifiedData:function(e){var t,{servcmd:e,data:s}=e,r=(r=e,t=c.get("login")||{},i=c.get("instance")||{},{servcmd:r,ver:"v4",platform:Ae,websdkappid:537048168,websdkversion:"1.7.3",sdkappid:i.sdkAppId,contenttype:"json",reqtime:Math.floor(Date.now()/1e3),identifier:t.userId,usersig:t.userSig,status_instid:t.statusInstanceId||0,sdkability:75689843,sdkability_ext:ae(""),cappid:t.cappid||0,seq:Ct(),cs:0}),i=mt(s);return r.cs=vt(e,i),{head:r,body:i}},generateProtocolData:ft,generateSSOLogProtocolData:It,generateSequence:Ct,getCommonHead:St,taskScheduler:gt,timeManager:ht});(_=Mt=Mt||{})[_.info=4]="info",_[_.warning=5]="warning",_[_.error=6]="error";let yt={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 Tt{constructor(e){this.level=Mt.info,this._canSendLog=!0,this._logCreatedAt=ht.getServerTimeMs(),this.timestamp=0,this.networkType=8,this.code=0,this.moreMessage="",this.method="",this.message="",this.costTime=0,this.duplicate=!1,this.eventType=0,this.uiPlatform=this._getUiPlatform(),this._sdkEdition=this._getSDKEdition();var{method:e,eventType:t=0,message:s="",costTime:r=0,error:i,moreMessage:n=""}=e||{};this.eventType=t,this.method=e,this.message=s,this.costTime=r,this.moreMessage=n,i&&this.setError(i)}setMoreMessage(e){this.moreMessage=this.moreMessage+" "+e}updateLogCreatedAtByTimeOffset(){this._logCreatedAt+=ht.getTimeOffsetWithServer()}end(){this._canSendLog&&(this._canSendLog=!1,this.timestamp=ht.getServerTimeMs(),this._ssoLogModule.pushToLogQueue(this._convertSSOLogDataKeyToServe()))}setError(e){var t;return e instanceof Error?this._canSendLog&&(null!=(t=c.get("netWorkMonitor"))&&t.isNetworkOnline&&(e.errorCode&&(this.code=e.errorCode),e.errorMessage)&&this.setMoreMessage(e.errorMessage),this.level=Mt.error):console.warn("SSOLogData.setError value not instanceof Error, please check!"),this}setLogInfo(t){return Object.keys(t).forEach(e=>{Object.keys(yt).includes(e)&&(this[e]=t[e])}),this}setSSOLogModule(e){this._ssoLogModule=e}_convertSSOLogDataKeyToServe(){let t={};return Object.keys(this).forEach(e=>{yt[e]&&(t[yt[e]]=this[e])}),t}_getUiPlatform(){var e,t=null==(e=c.get("instance"))?void 0:e.scene;if("string"==typeof t){let e=Number(t);return isNaN(e)?void 0:e}}_getSDKEdition(){var e;return null==(e=c.get("instance"))?void 0:e.sdkEdition}}(_=N=N||{}).RECONNECTED="reconnected",_.CLOUD_CONFIG_UPDATE="cloud_config_update",_.SOCKET_DISCONNECTED="socket_disconnected";var At=N;let Ot=[4,5,6],Dt=[],Rt=[],Lt="report-logger";var Nt=new class{constructor(){this._sdkAppIdBlackList=[],this._tinyIdWhiteList=[],this._reportLevel=[4,5,6],this._minThreshold=20,this._maxThreshold=100,this._waitingTime=6e4,this._lastReportAt=Date.now(),this._ssoLogMap=new Map,this._logLevel=i.DEBUG,this._throttleConfig={global:{throttleTime:5e3,maxCount:50},single:{throttleTime:1e3,maxCount:2}},this._globalThrottle={count:0,startTime:Date.now()},this._singleThrottleMap=new Map,J.subscribeInnerEvent(At.CLOUD_CONFIG_UPDATE,this._handleCloudConfigUpdate,this),gt.addTask({id:Lt,intervalMs:1e3,callback:this._checkAndReportIfDue,context:this}),this._logQueue=[],this._savePlatFormInfo()}_handleCloudConfigUpdate(e){var{evt_rpt_threshold:e=20,evt_rpt_waiting:t=6e4,evt_rpt_level:s=Ot,evt_rpt_sdkappid_bl:r=Dt,evt_rpt_tinyid_wl:i=Rt,evt_rpt_global_throttle_time:n=5e3,evt_rpt_global_throttle_count:o=50,evt_rpt_single_throttle_time:a=1e3,evt_rpt_single_throttle_count:u=2}=e||{};this._sdkAppIdBlackList=r,this._waitingTime=t,this._minThreshold=e,this._reportLevel=s,this._tinyIdWhiteList=i,this._throttleConfig={global:{throttleTime:n,maxCount:o},single:{throttleTime:a,maxCount:u}}}createSSOLogData(e){var t=new Tt(e);return t.setSSOLogModule(this),this._ssoLogMap.set(e.method,t),t}getSSOLogData(e){return this._ssoLogMap.get(e)||{}}pushToLogQueue(e){e&&(this._logQueue.push(e),this._shouldUploadImmediately())&&this.uploadSSOLogData()}setLogLevel(e){[i.DEBUG,i.ERROR,i.INFO,i.NONE,i.WARN].includes(e)&&(this._logLevel=e)}debug(e,t="",s){this._log(i.DEBUG,e,t,s)}info(e,t="",s){this._log(i.INFO,e,t,s)}warn(e,t="",s){this._log(i.WARN,e,t,s)}error(e,t="",s){this._log(i.ERROR,e,t,s)}_shouldUploadImmediately(){return this._logQueue.length>=this._minThreshold}_isReportDue(){return Date.now()>=this._lastReportAt+this._waitingTime}_checkAndReportIfDue(){this._isReportDue()&&0<this._logQueue.length&&this.uploadSSOLogData()}uploadSSOLogData(){return I(this,void 0,void 0,function*(){var e,t;0!==this._logQueue.length&&(t=this._logQueue.slice(),t=this._filterLogs(t),this._logQueue=[],0===t.length||ze((t={Header:St(),Event:t}).Header.user_id)||(e=(t=It({servcmd:e="imopenstat.tim_web_report_v2",data:t})).head.seq+e,yield void xt.sendPacket(t,{requestId:e})),this._lastReportAt=Date.now())})}_savePlatFormInfo(){var e,t;if(le){var s=null==(t=null==(e=wx.getAccountInfoSync)?void 0:e.call(wx))?void 0:t.miniProgram;if(s){let{appId:e,envVersion:t}=s;c.set("instance",{appId:e,envVersion:t})}}else Me&&c.set("instance",{href:window.location.href})}_filterLogs(e){var t=(c.get("login")||{})["tinyID"],s=(c.get("instance")||{})["sdkAppId"];return this._sdkAppIdBlackList.includes(s)&&!this._tinyIdWhiteList.includes(t)?[]:e.filter(e=>this._reportLevel.includes(e.level))}_checkThrottle(e){return!!this._checkGlobalThrottle()||this._checkSingleThrottle(e)}_checkGlobalThrottle(){var e=Date.now();if(e-this._globalThrottle.startTime>=this._throttleConfig.global.throttleTime)this._globalThrottle.count=1,this._globalThrottle.startTime=e;else if(this._globalThrottle.count++,this._globalThrottle.count>this._throttleConfig.global.maxCount)return!0;return!1}_checkSingleThrottle(e){var t=Date.now(),s=this._singleThrottleMap.get(e);return s?t-s.startTime>=this._throttleConfig.single.throttleTime?(s.count=1,s.startTime=t,!1):s.count>=this._throttleConfig.single.maxCount||(s.count++,!1):(this._singleThrottleMap.set(e,{count:1,startTime:t}),!1)}_shouldLog(e){return e>=this._logLevel&&this._logLevel!==i.NONE}_shouldReport(e){return this._reportLevel.includes(B[e])}_formatLog(e,t,s){var r=new Date,r=`${r.getHours()}:${r.getMinutes()}:${r.getSeconds()}:`+r.getMilliseconds(),e=`<${i[e]}>`;return ke||Ie?[x+` [${r}] ${e} [${t}] `+s]:["%c%s%c%s","background: #C35831; padding:1px; border-radius:3px; color: #fff",x,"",`[${r}] ${e} [${t}] `+s]}_log(e,t,s,r){if(this._shouldLog(e)){var i=this._formatLog(e,t,s);if(V[e].apply(console,i),this._shouldReport(e)){let e=this._getThrottleKey(t,s,r);this._checkThrottle(e)||this.createSSOLogData(Object.assign(Object.assign({message:s},r),{method:t})).end()}}}_getThrottleKey(e,t,s){var e=""+e+t+Qe(Object.assign(Object.assign({},s),{costTime:""})),r=_t(JSON.stringify(e));let i=4294967295;var n=r["length"];for(let e=0;e<n;e++){i^=r[e];for(let e=0;e<8;e++)1&~i?i>>>=1:i=i>>>1^3988292384}return""+((4294967295^i)>>>0)}reset(){console.log("SSO_LOG_MODULE.reset"),gt.removeTask(Lt),J.unSubscribeInnerEvent(At.CLOUD_CONFIG_UPDATE,this._handleCloudConfigUpdate,this),this._lastReportAt=0,this.uploadSSOLogData(),this._sdkAppIdBlackList=[],this._tinyIdWhiteList=[],this._minThreshold=20,this._maxThreshold=100,this._waitingTime=6e4,this._logQueue=[],this._logLevel=i.DEBUG,this._globalThrottle={count:0,startTime:Date.now()},this._singleThrottleMap.clear()}};let u="Channel",bt="channel_schedule_task",Gt="channel_reconnect_task",Pt="connected",wt="disconnected",Ut="network_status_change";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 qt=function s(r,i,n){function o(t,e){if(!i[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=i[t]={exports:{}};r[t][0].call(e.exports,function(e){return o(r[t][1][e]||e)},e,e.exports,s,r,i,n)}return i[t].exports}for(var a=Ft,e=0;e<n.length;e++)o(n[e]);return o}({1:[function(e,t,s){var r="undefined"!=typeof Uint8Array&&"undefined"!=typeof Uint16Array&&"undefined"!=typeof Int32Array,i=(s.assign=function(e){for(var t,s,r=Array.prototype.slice.call(arguments,1);r.length;){var i=r.shift();if(i){if("object"!=kt(i))throw new TypeError(i+"must be non-object");for(var n in i)t=i,s=n,Object.prototype.hasOwnProperty.call(t,s)&&(e[n]=i[n])}}return e},s.shrinkBuf=function(e,t){return e.length===t?e:e.subarray?e.subarray(0,t):(e.length=t,e)},{arraySet:function(e,t,s,r,i){if(t.subarray&&e.subarray)e.set(t.subarray(s,s+r),i);else for(var n=0;n<r;n++)e[i+n]=t[s+n]},flattenChunks:function(e){for(var t,s,r,i,n=t=0,o=e.length;n<o;n++)t+=e[n].length;for(i=new Uint8Array(t),n=s=0,o=e.length;n<o;n++)r=e[n],i.set(r,s),s+=r.length;return i}}),n={arraySet:function(e,t,s,r,i){for(var n=0;n<r;n++)e[i+n]=t[s+n]},flattenChunks:function(e){return[].concat.apply([],e)}};s.setTyped=function(e){e?(s.Buf8=Uint8Array,s.Buf16=Uint16Array,s.Buf32=Int32Array,s.assign(s,i)):(s.Buf8=Array,s.Buf16=Array,s.Buf32=Array,s.assign(s,n))},s.setTyped(r)},{}],2:[function(e,t,s){var u=e("./common"),i=!0,n=!0;try{String.fromCharCode.apply(null,[0])}catch(e){i=!1}try{String.fromCharCode.apply(null,new Uint8Array(1))}catch(e){n=!1}for(var l=new u.Buf8(256),r=0;r<256;r++)l[r]=252<=r?6:248<=r?5:240<=r?4:224<=r?3:192<=r?2:1;function c(e,t){if(t<65534&&(e.subarray&&n||!e.subarray&&i))return String.fromCharCode.apply(null,u.shrinkBuf(e,t));for(var s="",r=0;r<t;r++)s+=String.fromCharCode(e[r]);return s}l[254]=l[254]=1,s.string2buf=function(e){for(var t,s,r,i,n=e.length,o=0,a=0;a<n;a++)55296==(64512&(s=e.charCodeAt(a)))&&a+1<n&&56320==(64512&(r=e.charCodeAt(a+1)))&&(s=65536+(s-55296<<10)+(r-56320),a++),o+=s<128?1:s<2048?2:s<65536?3:4;for(t=new u.Buf8(o),a=i=0;i<o;a++)55296==(64512&(s=e.charCodeAt(a)))&&a+1<n&&56320==(64512&(r=e.charCodeAt(a+1)))&&(s=65536+(s-55296<<10)+(r-56320),a++),s<128?t[i++]=s:(s<2048?t[i++]=192|s>>>6:(s<65536?t[i++]=224|s>>>12:(t[i++]=240|s>>>18,t[i++]=128|s>>>12&63),t[i++]=128|s>>>6&63),t[i++]=128|63&s);return t},s.buf2binstring=function(e){return c(e,e.length)},s.binstring2buf=function(e){for(var t=new u.Buf8(e.length),s=0,r=t.length;s<r;s++)t[s]=e.charCodeAt(s);return t},s.buf2string=function(e,t){for(var s,r,i,n=t||e.length,o=new Array(2*n),a=s=0;a<n;)if((r=e[a++])<128)o[s++]=r;else if(4<(i=l[r]))o[s++]=65533,a+=i-1;else{for(r&=2===i?31:3===i?15:7;1<i&&a<n;)r=r<<6|63&e[a++],i--;1<i?o[s++]=65533:r<65536?o[s++]=r:(r-=65536,o[s++]=55296|r>>10&1023,o[s++]=56320|1023&r)}return c(o,s)},s.utf8border=function(e,t){for(var s=(t=(t=t||e.length)>e.length?e.length:t)-1;0<=s&&128==(192&e[s]);)s--;return!(s<0||0===s)&&s+l[e[s]]>t?s:t}},{"./common":1}],3:[function(e,t,s){t.exports=function(e,t,s,r){for(var i=65535&e,n=e>>>16&65535,o=0;0!==s;){for(s-=o=2e3<s?2e3:s;n=n+(i=i+t[r++]|0)|0,--o;);i%=65521,n%=65521}return i|n<<16}},{}],4:[function(e,t,s){t.exports={Z_NO_FLUSH:0,Z_PARTIAL_FLUSH:1,Z_SYNC_FLUSH:2,Z_FULL_FLUSH:3,Z_FINISH:4,Z_BLOCK:5,Z_TREES:6,Z_OK:0,Z_STREAM_END:1,Z_NEED_DICT:2,Z_ERRNO:-1,Z_STREAM_ERROR:-2,Z_DATA_ERROR:-3,Z_BUF_ERROR:-5,Z_NO_COMPRESSION:0,Z_BEST_SPEED:1,Z_BEST_COMPRESSION:9,Z_DEFAULT_COMPRESSION:-1,Z_FILTERED:1,Z_HUFFMAN_ONLY:2,Z_RLE:3,Z_FIXED:4,Z_DEFAULT_STRATEGY:0,Z_BINARY:0,Z_TEXT:1,Z_UNKNOWN:2,Z_DEFLATED:8}},{}],5:[function(e,t,s){var a=function(){for(var e=[],t=0;t<256;t++){for(var s=t,r=0;r<8;r++)s=1&s?3988292384^s>>>1:s>>>1;e[t]=s}return e}();t.exports=function(e,t,s,r){var i=a,n=r+s;e^=-1;for(var o=r;o<n;o++)e=e>>>8^i[255&(e^t[o])];return~e}},{}],6:[function(e,t,s){t.exports=function(){this.text=0,this.time=0,this.xflags=0,this.os=0,this.extra=null,this.extra_len=0,this.name="",this.comment="",this.hcrc=0,this.done=!1}},{}],7:[function(e,t,s){t.exports=function(e,t){var s,r,i,n,o,a,u=e.state,l=e.next_in,c=e.input,d=l+(e.avail_in-5),p=e.next_out,h=e.output,g=p-(t-e.avail_out),_=p+(e.avail_out-257),m=u.dmax,v=u.wsize,f=u.whave,I=u.wnext,E=u.window,C=u.hold,S=u.bits,M=u.lencode,y=u.distcode,T=(1<<u.lenbits)-1,A=(1<<u.distbits)-1;e:do{for(S<15&&(C+=c[l++]<<S,S+=8,C+=c[l++]<<S,S+=8),s=M[C&T];;){if(C>>>=r=s>>>24,S-=r,0==(r=s>>>16&255))h[p++]=65535&s;else{if(!(16&r)){if(!(64&r)){s=M[(65535&s)+(C&(1<<r)-1)];continue}if(32&r){u.mode=12;break e}e.msg="invalid literal/length code",u.mode=30;break e}for(i=65535&s,(r&=15)&&(S<r&&(C+=c[l++]<<S,S+=8),i+=C&(1<<r)-1,C>>>=r,S-=r),S<15&&(C+=c[l++]<<S,S+=8,C+=c[l++]<<S,S+=8),s=y[C&A];;){if(C>>>=r=s>>>24,S-=r,!(16&(r=s>>>16&255))){if(!(64&r)){s=y[(65535&s)+(C&(1<<r)-1)];continue}e.msg="invalid distance code",u.mode=30;break e}if(n=65535&s,S<(r&=15)&&(C+=c[l++]<<S,(S+=8)<r)&&(C+=c[l++]<<S,S+=8),m<(n+=C&(1<<r)-1)){e.msg="invalid distance too far back",u.mode=30;break e}if(C>>>=r,S-=r,(r=p-g)<n){if(f<(r=n-r)&&u.sane){e.msg="invalid distance too far back",u.mode=30;break e}if(a=E,(o=0)===I){if(o+=v-r,r<i){for(i-=r;h[p++]=E[o++],--r;);o=p-n,a=h}}else if(I<r){if(o+=v+I-r,(r-=I)<i){for(i-=r;h[p++]=E[o++],--r;);if(o=0,I<i){for(i-=r=I;h[p++]=E[o++],--r;);o=p-n,a=h}}}else if(o+=I-r,r<i){for(i-=r;h[p++]=E[o++],--r;);o=p-n,a=h}for(;2<i;)h[p++]=a[o++],h[p++]=a[o++],h[p++]=a[o++],i-=3;i&&(h[p++]=a[o++],1<i)&&(h[p++]=a[o++])}else{for(o=p-n;h[p++]=h[o++],h[p++]=h[o++],h[p++]=h[o++],2<(i-=3););i&&(h[p++]=h[o++],1<i)&&(h[p++]=h[o++])}break}}break}}while(l<d&&p<_);l-=i=S>>3,C&=(1<<(S-=i<<3))-1,e.next_in=l,e.next_out=p,e.avail_in=l<d?d-l+5:5-(l-d),e.avail_out=p<_?_-p+257:257-(p-_),u.hold=C,u.bits=S}},{}],8:[function(e,t,s){var N=e("../utils/common"),b=e("./adler32"),G=e("./crc32"),P=e("./inffast"),w=e("./inftrees"),U=0,k=-2,F=1,r=852,i=592;function q(e){return(e>>>24&255)+(e>>>8&65280)+((65280&e)<<8)+((255&e)<<24)}function n(){this.mode=0,this.last=!1,this.wrap=0,this.havedict=!1,this.flags=0,this.dmax=0,this.check=0,this.total=0,this.head=null,this.wbits=0,this.wsize=0,this.whave=0,this.wnext=0,this.window=null,this.hold=0,this.bits=0,this.length=0,this.offset=0,this.extra=0,this.lencode=null,this.distcode=null,this.lenbits=0,this.distbits=0,this.ncode=0,this.nlen=0,this.ndist=0,this.have=0,this.next=null,this.lens=new N.Buf16(320),this.work=new N.Buf16(288),this.lendyn=null,this.distdyn=null,this.sane=0,this.back=0,this.was=0}function o(e){var t;return e&&e.state?(t=e.state,e.total_in=e.total_out=t.total=0,e.msg="",t.wrap&&(e.adler=1&t.wrap),t.mode=F,t.last=0,t.havedict=0,t.dmax=32768,t.head=null,t.hold=0,t.bits=0,t.lencode=t.lendyn=new N.Buf32(r),t.distcode=t.distdyn=new N.Buf32(i),t.sane=1,t.back=-1,U):k}function a(e){var t;return e&&e.state?((t=e.state).wsize=0,t.whave=0,t.wnext=0,o(e)):k}function u(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 l(e,t){var s;return e?(s=new n,(e.state=s).window=null,(s=u(e,t))!==U&&(e.state=null),s):k}var x,V,B=!0;function j(e,t,s,r){var i,e=e.state;return null===e.window&&(e.wsize=1<<e.wbits,e.wnext=0,e.whave=0,e.window=new N.Buf8(e.wsize)),r>=e.wsize?(N.arraySet(e.window,t,s-e.wsize,e.wsize,0),e.wnext=0,e.whave=e.wsize):(r<(i=e.wsize-e.wnext)&&(i=r),N.arraySet(e.window,t,s-r,i,e.wnext),(r-=i)?(N.arraySet(e.window,t,s-r,r,0),e.wnext=r,e.whave=e.wsize):(e.wnext+=i,e.wnext===e.wsize&&(e.wnext=0),e.whave<e.wsize&&(e.whave+=i))),0}s.inflateReset=a,s.inflateReset2=u,s.inflateResetKeep=o,s.inflateInit=function(e){return l(e,15)},s.inflateInit2=l,s.inflate=function(e,t){var s,r,i,n,o,a,u,l,c,d,p,h,g,_,m,v,f,I,E,C,S,M,y,T,A=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),o=e.next_out,i=e.output,u=e.avail_out,n=e.next_in,r=e.input,a=e.avail_in,l=s.hold,c=s.bits,d=a,p=u,M=U;e:for(;;)switch(s.mode){case F:if(0===s.wrap)s.mode=13;else{for(;c<16;){if(0===a)break e;a--,l+=r[n++]<<c,c+=8}if(2&s.wrap&&35615===l)O[s.check=0]=255&l,O[1]=l>>>8&255,s.check=G(s.check,O,2,0),c=l=0,s.mode=2;else if(s.flags=0,s.head&&(s.head.done=!1),!(1&s.wrap)||(((255&l)<<8)+(l>>8))%31)e.msg="incorrect header check",s.mode=30;else if(8!=(15&l))e.msg="unknown compression method",s.mode=30;else{if(c-=4,S=8+(15&(l>>>=4)),0===s.wbits)s.wbits=S;else if(S>s.wbits){e.msg="invalid window size",s.mode=30;break}s.dmax=1<<S,e.adler=s.check=1,s.mode=512&l?10:12,c=l=0}}break;case 2:for(;c<16;){if(0===a)break e;a--,l+=r[n++]<<c,c+=8}if(s.flags=l,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=l>>8&1),512&s.flags&&(O[0]=255&l,O[1]=l>>>8&255,s.check=G(s.check,O,2,0)),c=l=0,s.mode=3;case 3:for(;c<32;){if(0===a)break e;a--,l+=r[n++]<<c,c+=8}s.head&&(s.head.time=l),512&s.flags&&(O[0]=255&l,O[1]=l>>>8&255,O[2]=l>>>16&255,O[3]=l>>>24&255,s.check=G(s.check,O,4,0)),c=l=0,s.mode=4;case 4:for(;c<16;){if(0===a)break e;a--,l+=r[n++]<<c,c+=8}s.head&&(s.head.xflags=255&l,s.head.os=l>>8),512&s.flags&&(O[0]=255&l,O[1]=l>>>8&255,s.check=G(s.check,O,2,0)),c=l=0,s.mode=5;case 5:if(1024&s.flags){for(;c<16;){if(0===a)break e;a--,l+=r[n++]<<c,c+=8}s.length=l,s.head&&(s.head.extra_len=l),512&s.flags&&(O[0]=255&l,O[1]=l>>>8&255,s.check=G(s.check,O,2,0)),c=l=0}else s.head&&(s.head.extra=null);s.mode=6;case 6:if(1024&s.flags&&((h=a<(h=s.length)?a:h)&&(s.head&&(S=s.head.extra_len-s.length,s.head.extra||(s.head.extra=new Array(s.head.extra_len)),N.arraySet(s.head.extra,r,n,h,S)),512&s.flags&&(s.check=G(s.check,r,h,n)),a-=h,n+=h,s.length-=h),s.length))break e;s.length=0,s.mode=7;case 7:if(2048&s.flags){if(0===a)break e;for(h=0;S=r[n+h++],s.head&&S&&s.length<65536&&(s.head.name+=String.fromCharCode(S)),S&&h<a;);if(512&s.flags&&(s.check=G(s.check,r,h,n)),a-=h,n+=h,S)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(h=0;S=r[n+h++],s.head&&S&&s.length<65536&&(s.head.comment+=String.fromCharCode(S)),S&&h<a;);if(512&s.flags&&(s.check=G(s.check,r,h,n)),a-=h,n+=h,S)break e}else s.head&&(s.head.comment=null);s.mode=9;case 9:if(512&s.flags){for(;c<16;){if(0===a)break e;a--,l+=r[n++]<<c,c+=8}if(l!==(65535&s.check)){e.msg="header crc mismatch",s.mode=30;break}c=l=0}s.head&&(s.head.hcrc=s.flags>>9&1,s.head.done=!0),e.adler=s.check=0,s.mode=12;break;case 10:for(;c<32;){if(0===a)break e;a--,l+=r[n++]<<c,c+=8}e.adler=s.check=q(l),c=l=0,s.mode=11;case 11:if(0===s.havedict)return e.next_out=o,e.avail_out=u,e.next_in=n,e.avail_in=a,s.hold=l,s.bits=c,2;e.adler=s.check=1,s.mode=12;case 12:if(5===t||6===t)break e;case 13:if(s.last)l>>>=7&c,c-=7&c,s.mode=27;else{for(;c<3;){if(0===a)break e;a--,l+=r[n++]<<c,c+=8}switch(s.last=1&l,--c,3&(l>>>=1)){case 0:s.mode=14;break;case 1:R=L=void 0;var R,L=s;if(B){for(x=new N.Buf32(512),V=new N.Buf32(32),R=0;R<144;)L.lens[R++]=8;for(;R<256;)L.lens[R++]=9;for(;R<280;)L.lens[R++]=7;for(;R<288;)L.lens[R++]=8;for(w(1,L.lens,0,288,x,0,L.work,{bits:9}),R=0;R<32;)L.lens[R++]=5;w(2,L.lens,0,32,V,0,L.work,{bits:5}),B=!1}if(L.lencode=x,L.lenbits=9,L.distcode=V,L.distbits=5,s.mode=20,6!==t)break;l>>>=2,c-=2;break e;case 2:s.mode=17;break;case 3:e.msg="invalid block type",s.mode=30}l>>>=2,c-=2}break;case 14:for(l>>>=7&c,c-=7&c;c<32;){if(0===a)break e;a--,l+=r[n++]<<c,c+=8}if((65535&l)!=(l>>>16^65535)){e.msg="invalid stored block lengths",s.mode=30;break}if(s.length=65535&l,c=l=0,s.mode=15,6===t)break e;case 15:s.mode=16;case 16:if(h=s.length){if(0===(h=u<(h=a<h?a:h)?u:h))break e;N.arraySet(i,r,n,h,o),a-=h,n+=h,u-=h,o+=h,s.length-=h}else s.mode=12;break;case 17:for(;c<14;){if(0===a)break e;a--,l+=r[n++]<<c,c+=8}if(s.nlen=257+(31&l),l>>>=5,c-=5,s.ndist=1+(31&l),l>>>=5,c-=5,s.ncode=4+(15&l),l>>>=4,c-=4,286<s.nlen||30<s.ndist){e.msg="too many length or distance symbols",s.mode=30;break}s.have=0,s.mode=18;case 18:for(;s.have<s.ncode;){for(;c<3;){if(0===a)break e;a--,l+=r[n++]<<c,c+=8}s.lens[D[s.have++]]=7&l,l>>>=3,c-=3}for(;s.have<19;)s.lens[D[s.have++]]=0;if(s.lencode=s.lendyn,s.lenbits=7,y={bits:s.lenbits},M=w(0,s.lens,0,19,s.lencode,0,s.work,y),s.lenbits=y.bits,M){e.msg="invalid code lengths set",s.mode=30;break}s.have=0,s.mode=19;case 19:for(;s.have<s.nlen+s.ndist;){for(;v=(A=s.lencode[l&(1<<s.lenbits)-1])>>>16&255,f=65535&A,!((m=A>>>24)<=c);){if(0===a)break e;a--,l+=r[n++]<<c,c+=8}if(f<16)l>>>=m,c-=m,s.lens[s.have++]=f;else{if(16===f){for(T=m+2;c<T;){if(0===a)break e;a--,l+=r[n++]<<c,c+=8}if(l>>>=m,c-=m,0===s.have){e.msg="invalid bit length repeat",s.mode=30;break}S=s.lens[s.have-1],h=3+(3&l),l>>>=2,c-=2}else if(17===f){for(T=m+3;c<T;){if(0===a)break e;a--,l+=r[n++]<<c,c+=8}S=0,h=3+(7&(l>>>=m)),l>>>=3,c=c-m-3}else{for(T=m+7;c<T;){if(0===a)break e;a--,l+=r[n++]<<c,c+=8}S=0,h=11+(127&(l>>>=m)),l>>>=7,c=c-m-7}if(s.have+h>s.nlen+s.ndist){e.msg="invalid bit length repeat",s.mode=30;break}for(;h--;)s.lens[s.have++]=S}}if(30===s.mode)break;if(0===s.lens[256]){e.msg="invalid code -- missing end-of-block",s.mode=30;break}if(s.lenbits=9,y={bits:s.lenbits},M=w(1,s.lens,0,s.nlen,s.lencode,0,s.work,y),s.lenbits=y.bits,M){e.msg="invalid literal/lengths set",s.mode=30;break}if(s.distbits=6,s.distcode=s.distdyn,y={bits:s.distbits},M=w(2,s.lens,s.nlen,s.ndist,s.distcode,0,s.work,y),s.distbits=y.bits,M){e.msg="invalid distances set",s.mode=30;break}if(s.mode=20,6===t)break e;case 20:s.mode=21;case 21:if(6<=a&&258<=u){e.next_out=o,e.avail_out=u,e.next_in=n,e.avail_in=a,s.hold=l,s.bits=c,P(e,p),o=e.next_out,i=e.output,u=e.avail_out,n=e.next_in,r=e.input,a=e.avail_in,l=s.hold,c=s.bits,12===s.mode&&(s.back=-1);break}for(s.back=0;v=(A=s.lencode[l&(1<<s.lenbits)-1])>>>16&255,f=65535&A,!((m=A>>>24)<=c);){if(0===a)break e;a--,l+=r[n++]<<c,c+=8}if(v&&!(240&v)){for(I=m,E=v,C=f;v=(A=s.lencode[C+((l&(1<<I+E)-1)>>I)])>>>16&255,f=65535&A,!(I+(m=A>>>24)<=c);){if(0===a)break e;a--,l+=r[n++]<<c,c+=8}l>>>=I,c-=I,s.back+=I}if(l>>>=m,c-=m,s.back+=m,s.length=f,0===v){s.mode=26;break}if(32&v){s.back=-1,s.mode=12;break}if(64&v){e.msg="invalid literal/length code",s.mode=30;break}s.extra=15&v,s.mode=22;case 22:if(s.extra){for(T=s.extra;c<T;){if(0===a)break e;a--,l+=r[n++]<<c,c+=8}s.length+=l&(1<<s.extra)-1,l>>>=s.extra,c-=s.extra,s.back+=s.extra}s.was=s.length,s.mode=23;case 23:for(;v=(A=s.distcode[l&(1<<s.distbits)-1])>>>16&255,f=65535&A,!((m=A>>>24)<=c);){if(0===a)break e;a--,l+=r[n++]<<c,c+=8}if(!(240&v)){for(I=m,E=v,C=f;v=(A=s.distcode[C+((l&(1<<I+E)-1)>>I)])>>>16&255,f=65535&A,!(I+(m=A>>>24)<=c);){if(0===a)break e;a--,l+=r[n++]<<c,c+=8}l>>>=I,c-=I,s.back+=I}if(l>>>=m,c-=m,s.back+=m,64&v){e.msg="invalid distance code",s.mode=30;break}s.offset=f,s.extra=15&v,s.mode=24;case 24:if(s.extra){for(T=s.extra;c<T;){if(0===a)break e;a--,l+=r[n++]<<c,c+=8}s.offset+=l&(1<<s.extra)-1,l>>>=s.extra,c-=s.extra,s.back+=s.extra}if(s.offset>s.dmax){e.msg="invalid distance too far back",s.mode=30;break}s.mode=25;case 25:if(0===u)break e;if(s.offset>(h=p-u)){if((h=s.offset-h)>s.whave&&s.sane){e.msg="invalid distance too far back",s.mode=30;break}g=h>s.wnext?(h-=s.wnext,s.wsize-h):s.wnext-h,h>s.length&&(h=s.length),_=s.window}else _=i,g=o-s.offset,h=s.length;for(u-=h=u<h?u:h,s.length-=h;i[o++]=_[g++],--h;);0===s.length&&(s.mode=21);break;case 26:if(0===u)break e;i[o++]=s.length,u--,s.mode=21;break;case 27:if(s.wrap){for(;c<32;){if(0===a)break e;a--,l|=r[n++]<<c,c+=8}if(p-=u,e.total_out+=p,s.total+=p,p&&(e.adler=s.check=(s.flags?G:b)(s.check,i,p,o-p)),p=u,(s.flags?l:q(l))!==s.check){e.msg="incorrect data check",s.mode=30;break}c=l=0}s.mode=28;case 28:if(s.wrap&&s.flags){for(;c<32;){if(0===a)break e;a--,l+=r[n++]<<c,c+=8}if(l!==(4294967295&s.total)){e.msg="incorrect length check",s.mode=30;break}c=l=0}s.mode=29;case 29:M=1;break e;case 30:M=-3;break e;case 31:return-4;default:return k}return e.next_out=o,e.avail_out=u,e.next_in=n,e.avail_in=a,s.hold=l,s.bits=c,(s.wsize||p!==e.avail_out&&s.mode<30&&(s.mode<27||4!==t))&&j(e,e.output,e.next_out,p-e.avail_out)?(s.mode=31,-4):(d-=e.avail_in,p-=e.avail_out,e.total_in+=d,e.total_out+=p,s.total+=p,s.wrap&&p&&(e.adler=s.check=(s.flags?G:b)(s.check,i,p,e.next_out-p)),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===p||4===t)&&M===U?-5:M)},s.inflateEnd=function(e){var t;return e&&e.state?((t=e.state).window&&(t.window=null),e.state=null,U):k},s.inflateGetHeader=function(e,t){return e&&e.state&&2&(e=e.state).wrap?((e.head=t).done=!1,U):k},s.inflateSetDictionary=function(e,t){var s,r=t.length;return!e||!e.state||0!==(s=e.state).wrap&&11!==s.mode?k:11===s.mode&&b(1,t,r,0)!==s.check?-3:j(e,t,r,r)?(s.mode=31,-4):(s.havedict=1,U)},s.inflateInfo="pako inflate (from Nodeca project)"},{"../utils/common":1,"./adler32":3,"./crc32":5,"./inffast":7,"./inftrees":9}],9:[function(e,t,s){var P=e("../utils/common"),w=[3,4,5,6,7,8,9,10,11,13,15,17,19,23,27,31,35,43,51,59,67,83,99,115,131,163,195,227,258,0,0],U=[16,16,16,16,16,16,16,16,17,17,17,17,18,18,18,18,19,19,19,19,20,20,20,20,21,21,21,21,16,72,78],k=[1,2,3,4,5,7,9,13,17,25,33,49,65,97,129,193,257,385,513,769,1025,1537,2049,3073,4097,6145,8193,12289,16385,24577,0,0],F=[16,16,16,16,17,17,18,18,19,19,20,20,21,21,22,22,23,23,24,24,25,25,26,26,27,27,28,28,29,29,64,64];t.exports=function(e,t,s,r,i,n,o,a){for(var u,l,c,d,p,h,g,_,m,v=a.bits,f=0,I=0,E=0,C=0,S=0,M=0,y=0,T=0,A=0,O=0,D=null,R=0,L=new P.Buf16(16),N=new P.Buf16(16),b=null,G=0,f=0;f<=15;f++)L[f]=0;for(I=0;I<r;I++)L[t[s+I]]++;for(S=v,C=15;1<=C&&0===L[C];C--);if(C<S&&(S=C),0===C)i[n++]=20971520,i[n++]=20971520,a.bits=1;else{for(E=1;E<C&&0===L[E];E++);for(S<E&&(S=E),f=T=1;f<=15;f++)if((T=(T<<1)-L[f])<0)return-1;if(0<T&&(0===e||1!==C))return-1;for(N[1]=0,f=1;f<15;f++)N[f+1]=N[f]+L[f];for(I=0;I<r;I++)0!==t[s+I]&&(o[N[t[s+I]]++]=I);if(h=0===e?(D=b=o,19):1===e?(D=w,R-=257,b=U,G-=257,256):(D=k,b=F,-1),f=E,p=n,y=I=O=0,c=-1,d=(A=1<<(M=S))-1,1===e&&852<A||2===e&&592<A)return 1;for(;;){for(m=o[I]<h?(_=0,o[I]):o[I]>h?(_=b[G+o[I]],D[R+o[I]]):(_=96,0),u=1<<(g=f-y),E=l=1<<M;i[p+(O>>y)+(l-=u)]=g<<24|_<<16|m,0!==l;);for(u=1<<f-1;O&u;)u>>=1;if(0!==u?O=(O&u-1)+u:O=0,I++,0==--L[f]){if(f===C)break;f=t[s+o[I]]}if(S<f&&(O&d)!==c){for(p+=E,T=1<<(M=f-(y=0===y?S:y));M+y<C&&!((T-=L[M+y])<=0);)M++,T<<=1;if(A+=1<<M,1===e&&852<A||2===e&&592<A)return 1;i[c=O&d]=S<<24|M<<16|p-n}}0!==O&&(i[p+O]=f-y<<24|64<<16),a.bits=S}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"),p=e("./utils/common"),h=e("./utils/strings"),g=e("./zlib/constants"),r=e("./zlib/messages"),i=e("./zlib/zstream"),n=e("./zlib/gzheader"),_=Object.prototype.toString;function o(e){if(!(this instanceof o))return new o(e);this.options=p.assign({chunkSize:16384,windowBits:0,to:""},e||{});var t=this.options,e=(t.raw&&0<=t.windowBits&&t.windowBits<16&&(t.windowBits=-t.windowBits,0===t.windowBits)&&(t.windowBits=-15),!(0<=t.windowBits&&t.windowBits<16)||e&&e.windowBits||(t.windowBits+=32),15<t.windowBits&&t.windowBits<48&&!(15&t.windowBits)&&(t.windowBits|=15),this.err=0,this.msg="",this.ended=!1,this.chunks=[],this.strm=new i,this.strm.avail_out=0,d.inflateInit2(this.strm,t.windowBits));if(e!==g.Z_OK)throw new Error(r[e]);if(this.header=new n,d.inflateGetHeader(this.strm,this.header),t.dictionary&&("string"==typeof t.dictionary?t.dictionary=h.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 o(t);if(t.push(e,!0),t.err)throw t.msg||r[t.err];return t.result}o.prototype.push=function(e,t){var s,r,i,n,o,a=this.strm,u=this.options.chunkSize,l=this.options.dictionary,c=!1;if(this.ended)return!1;r=t===~~t?t:!0===t?g.Z_FINISH:g.Z_NO_FLUSH,"string"==typeof e?a.input=h.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 p.Buf8(u),a.next_out=0,a.avail_out=u),(s=(s=d.inflate(a,g.Z_NO_FLUSH))===g.Z_NEED_DICT&&l?d.inflateSetDictionary(this.strm,l):s)===g.Z_BUF_ERROR&&!0===c&&(s=g.Z_OK,c=!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?(i=h.utf8border(a.output,a.next_out),n=a.next_out-i,o=h.buf2string(a.output,i),a.next_out=n,a.avail_out=u-n,n&&p.arraySet(a.output,a.output,i,n,0),this.onData(o)):this.onData(p.shrinkBuf(a.output,a.next_out))),0===a.avail_in&&0===a.avail_out&&(c=!0),(0<a.avail_in||0===a.avail_out)&&s!==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))},o.prototype.onData=function(e){this.chunks.push(e)},o.prototype.onEnd=function(e){e===g.Z_OK&&("string"===this.options.to?this.result=this.chunks.join(""):this.result=p.flattenChunks(this.chunks)),this.chunks=[],this.err=e,this.msg=this.strm.msg},s.Inflate=o,s.inflate=a,s.inflateRaw=function(e,t){return(t=t||{}).raw=!0,a(e,t)},s.ungzip=a},{"./utils/common":1,"./utils/strings":2,"./zlib/constants":4,"./zlib/gzheader":6,"./zlib/inflate":8,"./zlib/messages":10,"./zlib/zstream":11}]},{},[])("/lib/inflate.js"),xt=new class{constructor(){this._socketAdapter=null,this._url="",this._isReconnecting=!1,this._pendingRequests=new Map,this._nextHeartbeatAt=0,this._lastDiagnoseAt=0,this._isHeartbeatInProgress=!1,this._connectionEstablishedTime=0,this._connectionStartTime=0,this._connectionId=-1,this._isBinarySupported=!0,this._intendedDelay=1e3,this._currentConnectState=Pt,this._beforeSendInterceptors=[]}init(){gt.addTask({id:bt,intervalMs:1e3,callback:this._executeScheduledTaskIfReady,context:this}),this._updateIsBinarySupported(),this._url=function(e){var{sdkAppId:t,testEnv:s,disableIndependentDomain:r}=c.get("instance"),i=ut(t);let n="";return s?n=ot.TEST[i].DEFAULT:r?(n=ot.PRODUCTION[i].DEFAULT,ct=a.DEFAULT):n=ot.PRODUCTION[i].INITIAL.replace("*",""+t),dt(n,{isBinary:e})}(this._isBinarySupported),J.subscribeInnerEvent("networkStatusChange",this._handleNetworkStatusChange,this),J.subscribeInnerEvent("activityStatusChange",this._handleActivityStatusChange,this),this.connect()}sendPacket(e,t){var s,{requestId:r,timeout:i=15e3,canResend:n=!0}=t||{};if(ze(e))return Nt.warn("sendPacket",u+".sendPacket: packet is empty "),null;this._executeBeforeSendInterceptors(e),this._currentConnectState===wt&&this._handleConnectStateChange({state:wt,shouldEmitEvent:!0,shouldAttemptReconnect:!0,reason:"send_fail"});var o=JSON.stringify(e);let a=null;if(r){let{resolve:e,reject:t,promise:s}=Xe();a=s,this._pendingRequests.set(r,{resolve:e,reject:t,timestamp:Date.now(),uplinkData:o,timeout:i,canResend:n})}t=this._isBinarySupported?_t(o).buffer:o;return null!=(s=this._socketAdapter)&&s.send(t),a}connect(){this._socketAdapter=new nt(this._url),this._connectionEstablishedTime=0,this._addEventListeners(),this._connectionStartTime=Date.now();var e=null==(e=this._socketAdapter)?void 0:e.getId(),t=u+`.connect isWorkerEnabled: false socketID:${e} url:`+this._url;this._connectionId=e,this._ssoLog({method:"connect",message:t})}disconnect(){var e=null==(e=this._socketAdapter)?void 0:e.getId(),e=u+".disconnect socketID:"+e;this._ssoLog({method:"disconnect",message:e}),this._removeEventListeners(),null!=(e=this._socketAdapter)&&e.disconnect()}getSocketAdapter(){return this._socketAdapter}dispose(){console.log(u+".dispose"),gt.removeTask(bt),gt.removeTask(Gt),J.unSubscribeInnerEvent("networkStatusChange",this._handleNetworkStatusChange,this),J.unSubscribeInnerEvent("activityStatusChange",this._handleActivityStatusChange,this),this.disconnect(),this._socketAdapter=null,this._isReconnecting=!1,this._isHeartbeatInProgress=!1,this._pendingRequests.clear(),this._nextHeartbeatAt=0,this._lastDiagnoseAt=0,this._intendedDelay=1e3,this._url=""}registerBeforeSendInterceptor(e,t){this._beforeSendInterceptors.push(e.bind(t))}_executeBeforeSendInterceptors(e){for(var t of this._beforeSendInterceptors){var{servcmd:s=""}=null==e?void 0:e.head;t(s.includes(".")?s.split(".").pop():"")}}_shouldSkipReconnect(){var e="connecting"===this._currentConnectState&&this._isReconnecting;return!this._socketAdapter||e}reconnect(){return I(this,void 0,void 0,function*(){var e=u+`.reconnect isReconnecting: ${this._isReconnecting} currentConnectState: `+this._currentConnectState;if(this._ssoLog({method:"reconnect",message:e}),!this._shouldSkipReconnect()){this._url=pt(this._isBinarySupported);try{this._isReconnecting=!0,this.disconnect(),this.connect()}catch(e){this._isReconnecting=!1,this._handleConnectStateChange({state:wt,shouldEmitEvent:!0,shouldAttemptReconnect:!0,reason:"reconnect_failed"}),console.warn(u+".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=u+`.onClose closeSocketID: ${e} currentSocketID: ${this._connectionId} connectionDuration: ${s} code: ${null==t?void 0:t.code} reason: `+(null==t?void 0:t.reason);this._ssoLog({method:"onClose",message:s}),e===this._connectionId&&this._handleConnectStateChange({state:wt,shouldEmitEvent:!0,shouldAttemptReconnect:!0,reason:"socket_close"}),this._isReconnecting&&(this._isReconnecting=!1)}_onError(e){var{socketId:e,error:t}=e||{},t=u+`.onError sourceSocketID: ${e} currentSocketID: ${this._connectionId} isReconnecting: ${this._isReconnecting} error: `+JSON.stringify(t);this._ssoLog({method:"onError",message:t}),e===this._connectionId&&this._handleConnectStateChange({state:wt,shouldEmitEvent:!0,shouldAttemptReconnect:!0,reason:"socket_error"}),this._isReconnecting&&(this._isReconnecting=!1)}_onSendFail(e){var{socketId:e,error:t}=e||{},e=u+`.onSendFail sendFailSocketId: ${e} currentSocketID: ${this._connectionId} isReconnecting: ${this._isReconnecting} error: `+t;this._ssoLog({method:"onSendFail",message:e}),this._isReconnecting&&(this._isReconnecting=!1)}_onMessage(t){let s,e;this._updateHeartbeatTime();try{s=this._isBinarySupported?(this._isCompressedData(t.data)?e=>{var t=new Uint8Array(e).slice(4);let s;try{s=qt.inflate(t,{to:"string"})}catch(e){console.error("inflate error",e)}return s}:function(e){var i=new Uint8Array(e);let n="",o=0;for(var a=i["length"];o<a;){let t=i[o],s=0,r=0;if(t<=127?(s=0,r=255&t):t<=223?(s=1,r=31&t):t<=239?(s=2,r=15&t):t<=244&&(s=3,r=7&t),0<a-o-s)for(let e=0;e<s;e+=1)t=i[o+e+1],r=r<<6|63&t;else r=65533,s=a-o;n+=String.fromCodePoint(r),o+=s+1}return n})(t.data):t.data,e=JSON.parse(s)}catch(s){let e=t.data;return void this._ssoLog({method:"jsonParseError",message:e})}var r;e&&e.head&&({seq:t,servcmd:r}=e.head,this._pendingRequests.has(""+t+r)?this._handleRequestResponse(e):this._handlePushMessage(e))}_handleRequestResponse(e){var{seq:t,servcmd:s}=e.head,{int32_error_code:r,str_error_message:i}=(null==e?void 0:e.body)||{},n=(null==(n=null==e?void 0:e.body)?void 0:n.ErrorCode)||r,r=(null==(r=null==e?void 0:e.body)?void 0:r.ErrorInfo)||i,i=""+t+s,{resolve:t,reject:s}=this._pendingRequests.get(i);this._pendingRequests.delete(i),n&&0!==n?(J.emitInnerEvent("error",{errorCode:n,errorInfo:r}),s({errorCode:n,errorInfo:r})):t(e.body)}_handlePushMessage(e){var t=e.head["servcmd"],{NeedAck:s,SessionData:r}=e.body;1===s&&this._sendAck(r),J.emitInnerEvent(t,e)}_checkPendingRequestsAndResend(){var e;Nt.debug("_checkPendingRequestsAndResend",` reConnectFlag:${this._isReconnecting} promiseMap.size:`+this._pendingRequests.size),null!=(e=this._pendingRequests)&&e.forEach((e,t)=>{var{uplinkData:s,canResend:r,resolve:i,reject:n,timeout:o}=e;if(r){this._pendingRequests.set(t,{resolve:i,reject:n,timestamp:Date.now(),uplinkData:s,timeout:o,canResend:r});let e=this._isBinarySupported?_t(s).buffer:s;null!=(i=this._socketAdapter)&&i.send(e)}else this._pendingRequests.delete(t)})}_onConnect(e){var{socketId:e,event:t={}}=e||{},s=(this._connectionId=e,this._connectionEstablishedTime=Date.now(),Date.now()-this._connectionStartTime),s=u+`.onConnect cost:${s} ms. socketID:${e} res:`+JSON.stringify(t);if(this._ssoLog({method:"onConnect",message:s}),this._checkPendingRequestsAndResend(),this._sendHeartbeatIfReady(),this._isReconnecting){u;this._ssoLog({method:"reconnectSuccess",message:"Channel.reconnect success"}),J.emitInnerEvent(At.RECONNECTED),this._isReconnecting=!1}this._resetReconnectDelay(),this._handleConnectStateChange({state:Pt,shouldEmitEvent:!0,shouldAttemptReconnect:!1})}_sendAck(e){e=ft({servcmd:"openim.ws_msg_push_ack",data:{SessionData:e}});this.sendPacket(e)}_executeScheduledTaskIfReady(){return I(this,void 0,void 0,function*(){this._clearTimeoutRequest(),this._sendHeartbeatIfReady()})}_canSendHeartbeat(){var e;return(null==(e=this._socketAdapter)?void 0:e.isConnected())&&Date.now()>=this._nextHeartbeatAt&&!this._isHeartbeatInProgress}_sendHeartbeat(){return I(this,void 0,void 0,function*(){var e,t=ft({servcmd:"heartbeat.alive",data:{}});try{let e=""+t.head.seq+t.head.servcmd;yield this.sendPacket(t,{requestId:e,timeout:3e3})}catch(t){var s=null==(e=c.get("netWorkMonitor"))?void 0:e.isNetWorkOnline,s=u+`.sendHeartbeat failed. isNetWorkOnline:${s} error: `+t;this._ssoLog({method:"sendHeartbeatError",message:s}),this._handleConnectStateChange({state:wt,shouldEmitEvent:!0,shouldAttemptReconnect:!0})}})}_sendHeartbeatIfReady(){return I(this,void 0,void 0,function*(){this._canSendHeartbeat()&&(this._isHeartbeatInProgress=!0,yield this._sendHeartbeat(),this._isHeartbeatInProgress=!1)})}_updateHeartbeatTime(){this._nextHeartbeatAt=me?Date.now()+5e3:Date.now()+1e4}_handleNetworkStatusChange(e){var t=u+".networkStatusChange "+JSON.stringify(e),{isNetworkOnline:t,networkType:e}=(this._ssoLog({method:"networkStatusChange",message:t}),e);t&&"none"!==e?this._handleConnectStateChange({state:Pt,shouldEmitEvent:!1,shouldAttemptReconnect:!0,reason:Ut}):this._handleConnectStateChange({state:wt,shouldEmitEvent:!1,shouldAttemptReconnect:!0,reason:Ut})}isPrivateNetWork(){var e=c.get("instance")||{};return e.proxyServer&&!e.fileDownloadProxy}_handleConnectStateChange(e){var{state:e,shouldAttemptReconnect:t,shouldEmitEvent:s,reason:r}=e,r=u+`._handleConnectStateChange currentConnectState: ${this._currentConnectState} shouldAttemptReconnect: ${t} shouldEmitEvent: ${s} reason: `+r;this._currentConnectState!==e&&(this._ssoLog({method:"handleConnectStateChange",message:r}),s&&(Nt.info("_handleConnectStateChange",` from ${this._currentConnectState} to `+e),J.emitOuterEvent("netStateChange",{name:"netStateChange",data:{state:e}}),(this._currentConnectState=e)===wt)&&J.emitInnerEvent(At.SOCKET_DISCONNECTED),t)&&(this._resetReconnectDelay(),gt.addTask({id:Gt,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=u+`.activityStatusChange ${JSON.stringify(e)} readyState: `+t;this._ssoLog({method:"activityStatusChange",message:e}),3===t&&this._handleConnectStateChange({state:wt,shouldEmitEvent:!0,shouldAttemptReconnect:!0,reason:"activity_status_change"})}_resetReconnectDelay(){var e;Nt.debug(u+"._resetReconnectDelay"),gt.removeTask(Gt),null!=(e=c.get("activityMonitor"))&&e.isActive;this._intendedDelay=1e3}_scheduleReconnectWithBackoff(){var e=null==(e=c.get("activityMonitor"))?void 0:e.isActive,e=(this._intendedDelay=e?Math.min(5e3,Math.max(1e3,1.5*this._intendedDelay)):Math.min(3e5,Math.max(1e3,1.5*this._intendedDelay)),(new Date).toTimeString().slice(0,8)),e=u+`.scheduleReconnectWithBackoff timeStr: ${e} intendedDelay: `+this._intendedDelay;Nt.debug(e),this.reconnect(),gt.updateTaskInterval(Gt,this._intendedDelay)}_ssoLog(e){var{method:e,message:t}=e;Nt.info(e,t)}_diagnose(){this.isPrivateNetWork()||(this._lastDiagnoseAt=Date.now(),function(t){I(this,void 0,void 0,function*(){var e=t.split("/")[2];if(e.startsWith("ws")){e=`https://${e}/v3/netcheck/getconninfo?${t.slice(t.indexOf("info?")+5)}&reqtime=`+Date.now();try{yield $e({method:"GET",url:e,data:{}})}catch(e){Nt.warn("diagnoseBySSO","diagnoseBySSO failed. error:"+e.message)}}})}(this._url),function(t){I(this,void 0,void 0,function*(){var e=`https://boce-cdn.my-imcloud.com/v3/netcheck/getconninfo?${t.slice(t.indexOf("info?")+5)}&reqtime=`+Date.now();try{yield $e({method:"GET",url:e,data:{}})}catch(e){Nt.warn("diagnoseByCDN', 'diagnoseByCDN failed. error:"+e.message)}})}(this._url),this._beforeSendInterceptors=[])}_clearTimeoutRequest(){for(var[e,t]of this._pendingRequests.entries()){var{reject:t,timestamp:s,timeout:r}=t;Date.now()-s>=r&&(this._pendingRequests.delete(e),3e4<=Date.now()-this._lastDiagnoseAt&&this._diagnose(),t({errorCode:2801,errorInfo:"NETWORK_TIMEOUT",data:{requestId:e}}))}}_updateIsBinarySupported(){var e;(null!=(e=c.get("instance"))&&e.devMode||(e=He(),ge)||le&&"windows"===e||me)&&(this._isBinarySupported=!1)}_isCompressedData(e){e=new Uint8Array(e);return 67===e[0]&&79===e[1]&&77===e[2]&&80===e[3]}};let k={init:function(e){c.set("instance",e),xt.init()},destroy:function(){xt.dispose(),c.clear(),gt.dispose()},notificationCenter:J,channel:xt,store:c,ssoLog:Nt,utils:t,common:n,constants:e},Vt=e=>"function"==typeof e;function Bt(t,s,r){let i=r||[];var e,n;return!(!t||!s)&&(e=Object.keys(t).filter(e=>!i.includes(e)),n=Object.keys(s).filter(e=>!i.includes(e)),e.length===n.length)&&e.every(e=>!!s.hasOwnProperty(e)&&("object"==typeof t[e]&&null!==t[e]?Bt(t[e],s[e],r):t[e]===s[e]))}(_=b=b||{}).SDK_READY="sdkStateReady",_.SDK_NOT_READY="sdkStateNotReady",_.SDK_DESTROY="sdkDestroy",_.MESSAGE_RECEIVED="onMessageReceived",_.ROOM_CUSTOM_DATA_RECEIVED="onRoomCustomDataReceived",_.MESSAGE_MODIFIED="onMessageModified",_.MESSAGE_REVOKED="onMessageRevoked",_.MESSAGE_READ_BY_PEER="onMessageReadByPeer",_.MESSAGE_READ_RECEIPT_RECEIVED="onMessageReadReceiptReceived",_.MESSAGE_EXTENSIONS_UPDATED="onMessageExtensionsUpdated",_.MESSAGE_EXTENSIONS_DELETED="onMessageExtensionsDeleted",_.MESSAGE_REACTIONS_UPDATED="onMessageReactionsUpdated",_.CONVERSATION_LIST_UPDATED="onConversationListUpdated",_.TOTAL_UNREAD_MESSAGE_COUNT_UPDATED="onTotalUnreadMessageCountUpdated",_.CONVERSATION_GROUP_LIST_UPDATED="onConversationGroupListUpdated",_.CONVERSATION_IN_GROUP_UPDATED="onConversationInGroupUpdated",_.GROUP_LIST_UPDATED="onGroupListUpdated",_.GROUP_ATTRIBUTES_UPDATED="groupAttributesUpdated",_.GROUP_COUNTER_UPDATED="onGroupCounterUpdated",_.TOPIC_CREATED="onTopicCreated",_.TOPIC_DELETED="onTopicDeleted",_.TOPIC_UPDATED="onTopicUpdated",_.PROFILE_UPDATED="onProfileUpdated",_.USER_STATUS_UPDATED="onUserStatusUpdated",_.BLACKLIST_UPDATED="blacklistUpdated",_.FRIEND_LIST_UPDATED="onFriendListUpdated",_.FRIEND_GROUP_LIST_UPDATED="onFriendGroupListUpdated",_.FRIEND_APPLICATION_LIST_UPDATED="onFriendApplicationListUpdated",_.MY_FOLLOWERS_LIST_UPDATED="onMyFollowersListUpdated",_.MY_FOLLOWING_LIST_UPDATED="onMyFollowingListUpdated",_.MUTUAL_FOLLOWERS_LIST_UPDATED="onMutualFollowersListUpdated",_.KICKED_OUT="kickedOut",_.ERROR="error",_.NET_STATE_CHANGE="netStateChange",_.ALL_RECEIVE_MESSAGE_OPT_UPDATED="onAllReceiveMessageOptUpdated",_.SERVER_CONFIG_UPDATED="onServerConfigUpdated",_.PINNED_GROUP_MESSAGE_UPDATED="onPinnedGroupMessageUpdated";var jt=b;(N=dr=dr||{}).LOGOUT="logout",N.DESTROY="destroy",N.CLOUD_CONFIG_UPDATE="cloud_config_update",N.PROFILE_UPDATE="profile_updated",N.ERROR="error",N.RECONNECTED="reconnected",N.FORCE_OFFLINE="im_open_status.stat_forceoffline",N.COMMERCIAL_CONFIG_PUSH="im_sdk_config_mgr.push_imsdk_purchase_bitsv2",N.OVERLOAD_PUSH="OverLoadPush.notify2",N.NEW_MESSAGE="new_message",N.MESSAGE_PUSH="im_open_push.msg_push",N.MESSAGE_DELETED="message_deleted",N.MESSAGE_REVOKED="message_revoked",N.MESSAGE_MODIFIED="message_modified",N.SOCKET_DISCONNECTED="socket_disconnected",N.CONVERSATION_UPDATED="conversation_updated",N.TOPIC_MESSAGE_DELETED="topic_message_deleted",N.TOPIC_MESSAGE_REVOKED="topic_message_revoked",N.TOPIC_MESSAGE_MODIFIED="topic_message_modified",N.TOPIC_NEW_MESSAGE="topic_new_message",N.QUALITY_STAT="quality_stat",N.SYNC_CONVERSATION_LIST="sync_conversation_list";var Kt,Wt,d=dr,Ht=((t=yi=yi||{}).NEW_INVITATION_RECEIVED="newInvitationReceived",t.INVITEE_ACCEPTED="ts_invitee_accepted",t.INVITEE_REJECTED="ts_invitee_rejected",t.INVITATION_CANCELLED="ts_invitation_cancelled",t.INVITATION_TIMEOUT="ts_invitation_timeout",t.INVITATION_MODIFIED="ts_invitation_modified",yi);let Yt=Object.assign({},{KICKED_OUT_MULT_ACCOUNT:"multipleAccount",KICKED_OUT_MULT_DEVICE:"multipleDevice",KICKED_OUT_USERSIG_EXPIRED:"userSigExpired",KICKED_OUT_REST_API:"REST_API_Kick"}),$t={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"},zt=((n=Kt=Kt||{}).UNSENT="unSend",n.SUCCESS="success",n.FAIL="fail",{modify:d.MESSAGE_MODIFIED,delete:d.MESSAGE_DELETED,revoke:d.MESSAGE_REVOKED}),Jt=((e=Wt=Wt||{})[e.FORWARD=0]="FORWARD",e[e.BACKWARD=1]="BACKWARD",Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},$t),{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:Kt,Direction:Wt})),Qt={[zt.modify]:d.TOPIC_MESSAGE_MODIFIED,[zt.delete]:d.TOPIC_MESSAGE_DELETED,[zt.revoke]:d.TOPIC_MESSAGE_REVOKED},Xt={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"},Zt=Object.assign({},Xt),es={CONV_C2C:"C2C",CONV_GROUP:"GROUP",CONV_TOPIC:"TOPIC",CONV_SYSTEM:"@TIM#SYSTEM"},ts=Object.assign(Object.assign(Object.assign(Object.assign({},es),{CONV_AT_ME:1,CONV_AT_ALL:2,CONV_AT_ALL_AT_ME:3}),{CONV_MARK_TYPE_STAR:1,CONV_MARK_TYPE_UNREAD:2,CONV_MARK_TYPE_FOLD:4,CONV_MARK_TYPE_HIDE:8}),{READ_ALL_C2C_MSG:"readAllC2CMessage",READ_ALL_GROUP_MSG:"readAllGroupMessage",READ_ALL_MSG:"readAllMessage"}),ss=Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},{SNS_TYPE_NO_RELATION:"CheckResult_Type_NoRelation",SNS_TYPE_A_WITH_B:"CheckResult_Type_AWithB",SNS_TYPE_B_WITH_A:"CheckResult_Type_BWithA",SNS_TYPE_BOTH_WAY:"CheckResult_Type_BothWay"}),{ALLOW_TYPE_ALLOW_ANY:"AllowType_Type_AllowAny",ALLOW_TYPE_NEED_CONFIRM:"AllowType_Type_NeedConfirm",ALLOW_TYPE_DENY_ANY:"AllowType_Type_DenyAny"}),{SNS_ADD_TYPE_SINGLE:"Add_Type_Single",SNS_ADD_TYPE_BOTH:"Add_Type_Both"}),{SNS_DELETE_TYPE_SINGLE:"Delete_Type_Single",SNS_DELETE_TYPE_BOTH:"Delete_Type_Both"}),{SNS_APPLICATION_TYPE_BOTH:"Pendency_Type_Both",SNS_APPLICATION_SENT_TO_ME:"Pendency_Type_ComeIn",SNS_APPLICATION_SENT_BY_ME:"Pendency_Type_SendOut",SNS_APPLICATION_AGREE:"Response_Action_Agree",SNS_APPLICATION_AGREE_AND_ADD:"Response_Action_AgreeAndAdd"}),{SNS_CHECK_TYPE_BOTH:"CheckResult_Type_Both",SNS_CHECK_TYPE_SINGLE:"CheckResult_Type_Single"}),{FORBID_TYPE_NONE:"AdminForbid_Type_None",FORBID_TYPE_SEND_OUT:"AdminForbid_Type_SendOut"}),rs={GRP_WORK:"Private",GRP_PUBLIC:"Public",GRP_MEETING:"ChatRoom",GRP_AVCHATROOM:"AVChatRoom",GRP_COMMUNITY:"Community",GRP_ROOM:"Room",GRP_LIVE:"Live"},is={COMMUNITY:"@TGS#_",TOPIC:"@TOPIC#_"},ns={JOINED:1,QUITTED:2,KICKED:3,ADMIN_SET:4,ADMIN_CANCELED:5,GROUP_PROFILE_UPDATED:6,GROUP_MEMBER_PROFILE_UPDATED:7,TOPIC_PROFILE_UPDATED:8},os=Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},rs),{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:is,GROUP_TIPS_OPERATION_TYPE:ns}),S=Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},Yt),Jt),Zt),ts),ss),os),{IOS_OFFLINE_PUSH_NO_SOUND:"push.no_sound",IOS_OFFLINE_PUSH_DEFAULT_SOUND:"default"}),{NET_STATE_CONNECTING:"connecting",NET_STATE_DISCONNECTED:"disconnected"}),as={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},us={BASIC:"1",STANDARD:"2",PROFESSIONAL:"3"},p={SYNC_SERVER_INFO_AFTER_RE_ONLINE:"sync-server-info-after-re-online",SYNC_SERVER_INFO_AFTER_LOGIN:"sync-server-info-after-login",RECEIVE_C2C_NEW_MESSAGE:"receive-c2c-new-message",RECEIVE_GROUP_NEW_MESSAGE:"receive-group-new-message",RECEIVE_GROUP_TIPS_NOTIFICATION:"receive-group-tips-notification"},o={USER_STATUS_UPDATE:"user-status-update",CONVERSATION_RECOVER:"conversation-recover",HISTORY_MESSAGE_RECOVER:"history-message-recover",BLACKLIST_RECOVER:"blacklist-recover",FRIEND_RECOVER:"friend-recover",GROUP_ATTRIBUTE_CACHE_CLEAR:"group-attribute-cache-clear",UNREAD_MESSAGE_RECOVER:"unread-message-recover",HANDLE_NEW_MESSAGE:"handle-new-message",HANDLE_CONVERSATION_PROFILE_UPDATED:"handle-conversation-profile-updated",COMMERCIAL_CONFIG_UPDATE:"commercial-config-update",UNREAD_MESSAGE_SYNC:"unread-message-sync",FRIEND_AND_BLACKLIST_SYNC:"friend-and-blacklist-sync",SIGNALING_MESSAGE_RECOVER:"signaling-message-recover",GROUP_LIST_SYNC:"group-list-sync",CONVERSATION_LIST_SYNC:"conversation-list-sync",USER_PROFILE_SYNC:"user-profile-sync",CONVERSATION_UPDATE_AFTER_UNREAD_SYNC_FINISHED:"conversation-update-after-unread-sync-finished",CONVERSATION_UPDATE_AFTER_GROUP_LIST_SYNC_FINISHED:"conversation-update-after-group-list-sync-finished",HANDLE_C2C_NEW_MESSAGE:"handle-c2c-new-message",HANDLE_GROUP_NEW_MESSAGE:"handle-group-new-message",CREATE_OR_UPDATE_CONVERSATION_BY_RECEIVE_NEW_MESSAGE:"create-or-update-conversation-by-receive-new-message",HANDLE_GROUP_TIPS_FROM_SYNC_UNREAD:"handle-group-tips-from-sync-unread",HANDLE_C2C_REVOKED_MESSAGE_FROM_SYNC_UNREAD:"handle-c2c-revoked-message-from-sync-unread",GROUP_REVOKED_NOTICE_RECOVER:"group-revoked-notice-recover",CLOUD_CONFIG_SYNC:"cloud-config-sync",UPDATE_GROUP_NEXT_SEQUENCE:"update-group-next-sequence",EMIT_C2C_MESSAGE_EVENT:"emit-c2c-message-event",EMIT_GROUP_MESSAGE_EVENT:"emit-group-message-event",CONVERSATION_GROUP_LIST_SYNC:"conversation-group-list-sync",CONVERSATION_GROUP_UPDATE:"conversation-group-update",UPDATE_TOPIC_AFTER_UNREAD_SYNC_FINISHED:"update-topic-after-unread-sync-finished",UPDATE_TOPIC_BY_RECEIVE_NEW_MESSAGE:"update-topic-by-received-new-message",TOPIC_REQUEST_INFO_RESET:"topic-request-info-reset",QUALITY_REPORT:"quality-report",GROUP_TIPS_RECOVER:"group-tips-recover",HANDLE_GROUP_TIPS_NOTIFICATION:"handle-group-tips-notification"},ls={[p.SYNC_SERVER_INFO_AFTER_RE_ONLINE]:[{stepId:o.USER_STATUS_UPDATE},{stepId:o.GROUP_ATTRIBUTE_CACHE_CLEAR},{stepId:o.UNREAD_MESSAGE_SYNC},{stepId:o.CONVERSATION_RECOVER},{stepId:o.HISTORY_MESSAGE_RECOVER,dependency:o.CONVERSATION_RECOVER},{stepId:o.BLACKLIST_RECOVER},{stepId:o.FRIEND_RECOVER},{stepId:o.GROUP_REVOKED_NOTICE_RECOVER,dependency:o.HISTORY_MESSAGE_RECOVER},{stepId:o.GROUP_TIPS_RECOVER,dependency:o.HISTORY_MESSAGE_RECOVER},{stepId:o.TOPIC_REQUEST_INFO_RESET},{stepId:o.HANDLE_C2C_REVOKED_MESSAGE_FROM_SYNC_UNREAD,dependency:o.UNREAD_MESSAGE_SYNC},{stepId:o.HANDLE_GROUP_TIPS_FROM_SYNC_UNREAD,dependency:o.UNREAD_MESSAGE_SYNC},{stepId:o.CONVERSATION_UPDATE_AFTER_UNREAD_SYNC_FINISHED,dependency:[o.UNREAD_MESSAGE_SYNC,o.CONVERSATION_RECOVER]},{stepId:o.EMIT_C2C_MESSAGE_EVENT,dependency:[o.UNREAD_MESSAGE_SYNC,o.CONVERSATION_UPDATE_AFTER_UNREAD_SYNC_FINISHED],skipIfDependencyMissing:!1}],[p.SYNC_SERVER_INFO_AFTER_LOGIN]:[{stepId:o.COMMERCIAL_CONFIG_UPDATE},{stepId:o.CLOUD_CONFIG_SYNC},{stepId:o.USER_PROFILE_SYNC},{stepId:o.UNREAD_MESSAGE_SYNC},{stepId:o.FRIEND_AND_BLACKLIST_SYNC},{stepId:o.GROUP_LIST_SYNC},{stepId:o.CONVERSATION_LIST_SYNC},{stepId:o.SIGNALING_MESSAGE_RECOVER,dependency:o.UNREAD_MESSAGE_SYNC},{stepId:o.UPDATE_TOPIC_AFTER_UNREAD_SYNC_FINISHED,dependency:[o.UNREAD_MESSAGE_SYNC]},{stepId:o.CONVERSATION_UPDATE_AFTER_UNREAD_SYNC_FINISHED,dependency:[o.UNREAD_MESSAGE_SYNC,o.CONVERSATION_LIST_SYNC]},{stepId:o.CONVERSATION_UPDATE_AFTER_GROUP_LIST_SYNC_FINISHED,dependency:[o.GROUP_LIST_SYNC,o.CONVERSATION_LIST_SYNC]},{stepId:o.CONVERSATION_GROUP_LIST_SYNC},{stepId:o.CONVERSATION_GROUP_UPDATE,dependency:[o.CONVERSATION_LIST_SYNC,o.CONVERSATION_GROUP_LIST_SYNC]},{stepId:o.QUALITY_REPORT}],[p.RECEIVE_C2C_NEW_MESSAGE]:[{stepId:o.HANDLE_C2C_NEW_MESSAGE},{stepId:o.UNREAD_MESSAGE_SYNC},{stepId:o.CREATE_OR_UPDATE_CONVERSATION_BY_RECEIVE_NEW_MESSAGE,dependency:o.HANDLE_C2C_NEW_MESSAGE},{stepId:o.EMIT_C2C_MESSAGE_EVENT,dependency:[o.HANDLE_C2C_NEW_MESSAGE,o.CREATE_OR_UPDATE_CONVERSATION_BY_RECEIVE_NEW_MESSAGE],skipIfDependencyMissing:!1},{stepId:o.CONVERSATION_UPDATE_AFTER_UNREAD_SYNC_FINISHED,dependency:[o.UNREAD_MESSAGE_SYNC]}],[p.RECEIVE_GROUP_NEW_MESSAGE]:[{stepId:o.HANDLE_GROUP_NEW_MESSAGE},{stepId:o.CREATE_OR_UPDATE_CONVERSATION_BY_RECEIVE_NEW_MESSAGE,dependency:o.HANDLE_GROUP_NEW_MESSAGE},{stepId:o.UPDATE_GROUP_NEXT_SEQUENCE,dependency:o.HANDLE_GROUP_NEW_MESSAGE},{stepId:o.UPDATE_TOPIC_BY_RECEIVE_NEW_MESSAGE,dependency:o.HANDLE_GROUP_NEW_MESSAGE},{stepId:o.EMIT_GROUP_MESSAGE_EVENT,dependency:[o.HANDLE_GROUP_NEW_MESSAGE,o.CREATE_OR_UPDATE_CONVERSATION_BY_RECEIVE_NEW_MESSAGE],skipIfDependencyMissing:!1}],[p.RECEIVE_GROUP_TIPS_NOTIFICATION]:[{stepId:o.HANDLE_GROUP_TIPS_NOTIFICATION},{stepId:o.CREATE_OR_UPDATE_CONVERSATION_BY_RECEIVE_NEW_MESSAGE,dependency:o.HANDLE_GROUP_TIPS_NOTIFICATION}]},cs={MESSAGE_SEND_SUCCESS_RATE:"messageSendSuccessRate"},ds={TOTAL_COUNT:"sendMessageTotalCount",SUCCESS_COUNT:"sendMessageSuccessCount",FAILED_COUNT:"sendMessageFailedCount",SEND_COST:"sendMessageCost"},ps=["login","getMyProfile","getUserProfile","updateMyProfile","setSelfStatus","getUserStatus","subscribeUserStatus","unsubscribeUserStatus","modifyMessage","deleteGroupMember","dismissGroup","getGroupMemberList","getGroupOnlineMemberCount","joinGroup","markGroupMemberList","quitGroup","searchCloudMessages","searchCloudGroups","searchCloudGroupMembers","searchCloudUsers","getMyFollowingList","getMyFollowersList","getMutualFollowersList","followUser","unfollowUser","getUserFollowInfo","checkFollowType","getFriendProfile","addFriend","deleteFriend","updateFriend","checkFriend","setFriendApplicationRead","createFriendGroup","deleteFriendGroup","addToFriendGroup","removeFromFriendGroup","renameFriendGroup","changeGroupOwner","createGroup","dismissGroup","getGroupList","getGroupOnlineMemberCount","getGroupProfile","searchGroupByID","updateGroupProfile","handleGroupApplication","deleteGroupAttributes","getGroupAttributes","initGroupAttributes","setGroupAttributes","addGroupMember","deleteGroupMember","getGroupMemberList","getGroupMemberProfile","setGroupMemberMuteTime","setGroupMemberNameCard","setGroupMemberRole","deleteMessage","revokeMessage","setMessageExtensions","getMessageExtensions","deleteMessageExtensions","getMessageList","addMessageReaction","removeMessageReaction","clearHistoryMessage","invite","accept","cancel","reject","modifyInvitation","deleteConversation","pinConversation","setMessageRead","setAllMessageRead","getConversationList","getTotalUnreadMessageCount","renameConversationGroup","deleteConversationGroup","markConversation","setConversationCustomData","deleteConversationsFromGroup","addConversationsToGroup","createConversationGroup"];var hs,gs,_s=Object.freeze({__proto__:null,ERROR_CODE:as,InnerEvent:d,NEED_LOG_API:ps,OuterConstant:S,OuterEvent:jt,QUALITY_METRICS:cs,SDK_EDITION:us,SDK_INFO:{VERSION:"1.7.3",APPID:537048168},SEND_MESSAGE_STAT:ds,SignalingEvent:Ht,WORKFLOW_DEFINITIONS:ls,WORKFLOW_NAME:p,WORKFLOW_STEP:o});(_=hs=hs||{})[_.USER_INITIATED=0]="USER_INITIATED",_[_.KICKED_OUT=1]="KICKED_OUT",(b=gs=gs||{})[b.multipleAccount=1]="multipleAccount",b[b.multipleDevice=2]="multipleDevice",b[b.restApi=3]="restApi",(N=ba=ba||{})[N.multipleDevice=3002]="multipleDevice",N[N.multipleAccount=3003]="multipleAccount",N[N.usersigExpired=70001]="usersigExpired",N[N.restApi=20002]="restApi";let ms={[gs.multipleAccount]:"multipleAccount",[gs.multipleDevice]:"multipleDevice",[gs.restApi]:"REST_API_Kick",[ba.multipleAccount]:"multipleAccount",[ba.multipleDevice]:"multipleDevice",[ba.restApi]:"REST_API_Kick",[ba.usersigExpired]:"userSigExpired"},vs="login_online_presence_task",{ERROR:fs,DESTROY:Is,FORCE_OFFLINE:Es}=d,{KICKED_OUT_MULT_ACCOUNT:Cs,KICKED_OUT_MULT_DEVICE:Ss,KICKED_OUT_REST_API:Ms,ACCOUNT_A2KEY_EXPIRED:ys,MSG_A2KEY_EXPIRED:Ts}=as;class As{init(){var e=k["notificationCenter"];e.subscribeInnerEvent(Es,this._handleForceOfflineFromServerPush,this),e.subscribeInnerEvent(fs,Ts,this._handleForceOfflineFromResponse,this),e.subscribeInnerEvent(fs,ys,this._handleForceOfflineFromResponse,this),e.subscribeInnerEvent(fs,Cs,this._handleForceOfflineFromResponse,this),e.subscribeInnerEvent(fs,Ss,this._handleForceOfflineFromResponse,this),e.subscribeInnerEvent(fs,Ms,this._handleForceOfflineFromResponse,this),e.subscribeInnerEvent(Is,this._dispose,this)}_handleForceOfflineFromServerPush(e){var{EventArray:e=[]}=(null==e?void 0:e.body)||{};this._extractKickedOutMessages(e).forEach(e=>{var{KickType:e,NewInstInfo:t}=e["KickoutMsgNotify"];this._processKickedOutReasonInfo({kickedOutReasonCode:e,newInstanceInfo:t})})}_extractKickedOutMessages(e){return e.reduce((e,t)=>[...e,...t.C2cNotifyMsgArray||[]],[]).filter(e=>{return this._isKickedOut(null==(e=null==e?void 0:e.KickoutMsgNotify)?void 0:e.KickType)})}_handleForceOfflineFromResponse(e){e=e.errorCode;this._processKickedOutReasonInfo({kickedOutReasonCode:e})}_processKickedOutReasonInfo(r){return I(this,void 0,void 0,function*(){var e=r["kickedOutReasonCode"],{ssoLog:t,utils:{safeStringify:s}}=k;try{this._logKickedOutEvent(r),yield k.login.loginAction.logout(hs.KICKED_OUT)}catch(e){t.debug("_processKickedOutReasonInfo"," fail "+s(e))}finally{k.notificationCenter.emitOuterEvent(jt.KICKED_OUT,{data:{type:ms[e]},name:jt.KICKED_OUT}),[gs.restApi,ys,Ts].includes(e)&&k.channel.reconnect()}})}_logKickedOutEvent(e){var{kickedOutReasonCode:e,newInstanceInfo:t={}}=e,e=`type:${ms[e]} newInstanceInfo: `+JSON.stringify(t);k.ssoLog.warn("kickedOut",e)}_isKickedOut(e){return[gs.multipleAccount,gs.multipleDevice,gs.restApi].includes(e)}_dispose(){var e=k["notificationCenter"];e.unSubscribeInnerEvent(Es,this._handleForceOfflineFromServerPush,this),e.unSubscribeInnerEvent(fs,ys,this._handleForceOfflineFromResponse,this),e.unSubscribeInnerEvent(fs,Ts,this._handleForceOfflineFromResponse,this),e.unSubscribeInnerEvent(fs,Cs,this._handleForceOfflineFromResponse,this),e.unSubscribeInnerEvent(fs,Ss,this._handleForceOfflineFromResponse,this),e.unSubscribeInnerEvent(fs,Ms,this._handleForceOfflineFromResponse,this),e.unSubscribeInnerEvent(Is,this._dispose,this)}}function Os(){return I(this,void 0,void 0,function*(){let e="im_open_status.wslogin",t=k.common.generateProtocolData({servcmd:e,data:{state:"Online",isWebUniapp:0,InstType:0,customInfo:""}}),s=""+t.head.seq+e,d=yield k.channel.sendPacket(t,{timeout:9e4,requestId:s});if(d){let{HelloInterval:e,InstId:t,TinyId:s,TimeStamp:r,CustomStatus:i,PurchaseBits:n,A2Key:o,RichMsgAuthKey:a,ErrorCode:u,ErrorInfo:l,ActionStatus:c}=d;return{helloInterval:e,instanceID:t,tinyID:s,timeStamp:r,customStatus:i,purchaseBits:n,a2Key:o,authKey:a,errorCode:u,errorInfo:l,actionStatus:c}}})}function Ds(t){var s;try{var r=c.getStorage("errorMessage");if(!t||!r)return"";var i=(null==(s=JSON.parse(r))?void 0:s.errorMessage)||{},{isIntl:n=!1,code:o,replacement1:a="",replacement2:u=""}=t;if(!o)return"";var l=n?o+"_en":o+"_cn";let e=i[i[l]?l:o]||"";return e=e&&(a&&(e=e.replace("$replacement1",a)),u)?e.replace("$replacement2",u):e}catch(t){return console.warn("Error parsing stored error messages:",t),""}}class m extends Error{constructor(e){var{functionName:t="Unknown",code:s,message:r="",data:i="",moreMessage:n=""}=e;let o=r;s&&!r&&(o=Ds(e));r=(s?`${t} failed. error: {"message": ${o}, "code": ${s}}`:`${t} failed. error: {"message": ${o}}`)+" "+n;super(),this.code=s,this.errorCode=s,this.errorMessage=r,this.message=r,this.data=i}}function Rs(e,t){if(e&&!0!==(null==(e=k.store.get("login"))?void 0:e.isLoggedIn))throw new m({code:as.USER_NOT_LOGGED_IN,functionName:t})}function Ls(t,s,r){if(Array.isArray(t))for(let e=0;e<t.length;e++)Ns.call(this,Object.assign(Object.assign({},t[e]),{value:s[e],name:r}));else for(var e in t)Ns.call(this,Object.assign(Object.assign({},t[e]),{value:s[0][e],name:r,key:e}))}function Ns({required:e,rules:r,value:t,allowEmpty:i,name:n,key:o,customValidator:a}){if(void 0===t){if(e)throw new m({functionName:n,message:`[${n}] Missing required params: "${o}"`})}else{let s="";if(!r.some(e=>{return e===Object.prototype.toString.call(t).match(/^\[object (.*)\]$/)[1].toLowerCase()})){for(let t=0;t<r.length;t++){let e=r[t];e=e.replace(e[0],e[0].toUpperCase()),s+=e+"/"}let e=`[${o}] must be type of ${s=s.substring(0,s.length-1)}, received type: ${Reflect.apply(Object.prototype.toString,t,[]).replace(/^\[object\s(\w+)\]$/,"$1").toLowerCase()}.`;throw new m({functionName:n,message:e})}if(!1===i){if(Array.isArray(t)&&(0===t.length||"string"==typeof t[0]&&""===t[0].trim()))throw new m({functionName:n,message:o+" can not be empty."});if("string"==typeof t&&""===t.trim())throw new m({functionName:n,message:o+" can not be empty."})}if(a&&"function"==typeof a){let e=a(t);if(!0!==e)throw new m({functionName:n,message:`[${o}] custom validation failed: `+(e||"Invalid value")})}}}let bs=[],Gs={},Ps={};function ws(e,t){var s;Rs(Gs[e],e),Ls(Ps[e],t,e),s=e,bs.forEach(e=>{var{interceptor:e,context:t}=e;e.apply(t,[s])})}function Us(e,t){bs.push({interceptor:e,context:t})}function ks(e){var{params:e,auth:t}=e;e&&"object"==typeof e&&Object.assign(Ps,e),t&&"object"==typeof t&&Object.assign(Gs,t)}function Fs(e){return k.store.get("commercialConfig").get(e)}class h{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),k.ssoLog.debug("_executeWorkflowStep",`[Workflow ${e}] Step ${t} started at `+new Date(s).toISOString())):(this._workflowStartTimes.set(e,s),k.ssoLog.debug("_executeWorkflowStep",`[Workflow ${e}] started at `+new Date(s).toISOString()))},success:(s,e)=>{var r=Date.now();if(e){var t=this._stepStartTimes.get(s+"-"+e),t=t?r-t:0;this._stepStartTimes.delete(s+"-"+e),k.ssoLog.debug("_executeWorkflowStep",`[Workflow ${s}] Step ${e} completed successfully at ${new Date(r).toISOString()} (${t}ms)`)}else{let e=this._workflowStartTimes.get(s),t=e?r-e:0;this._workflowStartTimes.delete(s),k.ssoLog.debug("_executeWorkflowStep",`[Workflow ${s}] completed successfully at ${new Date(r).toISOString()} (${t}ms)`)}},error:(s,e,r)=>{var{ssoLog:i,utils:{safeStringify:n}}=this._core,o=Date.now();if(e){var t=this._stepStartTimes.get(s+"-"+e),t=t?o-t:0;this._stepStartTimes.delete(s+"-"+e),i.error("_executeWorkflowStep",`[Workflow ${s}] Step ${e} failed at ${new Date(o).toISOString()} (${t}ms) `+n(r),{error:r})}else{let e=this._workflowStartTimes.get(s),t=e?o-e:0;this._workflowStartTimes.delete(s),i.error("_executeWorkflowStep",`[Workflow ${s}] failed at ${new Date(o).toISOString()} (${t}ms) `+n(r),{error:r})}}}}static getInstance(){return h._instance||(h._instance=new h),h._instance}static setInstance(e){h._instance=e}init(){this._initializeWorkflows()}registerWorkflowStep(e,t,s,r){var i;this._handlers.has(e)?ls[e].find(e=>e.stepId===t)?(i=this._handlers.get(e)).has(t)||i.set(t,r?s.bind(r):s):k.ssoLog.debug("registerWorkflowStep",`Step '${t}' not defined in workflow '${e}'`):k.ssoLog.debug("registerWorkflowStep",`Workflow '${e}' not defined in core`)}executeWorkflow(o,s){return I(this,void 0,void 0,function*(){if(this._validateWorkflow(o)){k.ssoLog.debug("executeWorkflow",`[Workflow ${o}] Started execution at `+(new Date).toISOString());let e=ls[o],n={cancelled:!1};this._activeWorkflows.set(o,{cancelToken:n});try{let t=new Map,i=(e.forEach(e=>{t.set(e.stepId,e)}),{workflowName:o,pendingSteps:new Set(e.map(e=>e.stepId)),completedSteps:new Set,runningSteps:new Set,stepMap:t,stepResults:{},data:s,cancelToken:n});yield new Promise((t,s)=>{let r=()=>{n.cancelled?t():this._getExecutableSteps({pendingSteps:i.pendingSteps,completedSteps:i.completedSteps,stepMap:i.stepMap,workflowName:o}).filter(e=>!i.runningSteps.has(e)).forEach(e=>{i.completedSteps.has(e)||i.runningSteps.has(e)||this._executeWorkflowStep(e,i,{onComplete:()=>{0===i.pendingSteps.size?t():0===this._getExecutableSteps({pendingSteps:i.pendingSteps,completedSteps:i.completedSteps,stepMap:i.stepMap,workflowName:o}).filter(e=>!i.runningSteps.has(e)).length&&0===i.runningSteps.size&&(k.ssoLog.debug("executeWorkflow",`Workflow ${o} completed with some steps skipped due to dependency failures`),t())},onError:s,onStepComplete:r})})};r()}),k.ssoLog.debug("executeWorkflow",`[Workflow ${o}] Completed execution at `+(new Date).toISOString())}catch(e){k.ssoLog.error("executeWorkflow",`[Workflow ${o}] Failed execution at `+(new Date).toISOString(),{error:e})}finally{this._activeWorkflows.delete(o)}}})}_executeWorkflowStep(a,u,l){return I(this,void 0,void 0,function*(){let{workflowName:n,runningSteps:e,stepMap:s,stepResults:r,data:i}=u;e.add(a),this._logWorkflowExecution(n,a,"start");try{let e=s.get(a),t=null;null!=e&&e.dependency&&(X(e.dependency)?t=r[e.dependency]:Array.isArray(e.dependency)&&(t={},e.dependency.forEach(e=>{t[e]=r[e]})));var o=this._handlers.get(n).get(a);if(o){let e=yield Promise.resolve(o({data:i,result:t}));r[a]=e,this._logWorkflowExecution(n,a,"success")}u.completedSteps.add(a)}catch(e){let t=`[Workflow].${n}.`+a,{errorCode:s,errorInfo:r=t+" failed"}=e||{},i=new m({functionName:t,code:s,message:r});k.ssoLog.error(t,r,{error:i}),this._logWorkflowExecution(n,a,"error",e),l.onError(e)}finally{e.delete(a),u.pendingSteps.delete(a),l.onStepComplete(),l.onComplete()}})}reset(){this._cancelAllWorkflows()}destroy(){this.reset(),this._handlers.clear()}_initializeWorkflows(){Object.keys(ls).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(ls).forEach(e=>{this._cancelWorkFlow(e)})}_validateWorkflow(e){return!!ls[e]&&!!this._handlers.get(e)}_getExecutableSteps(e){let{pendingSteps:t,completedSteps:s,stepMap:r,workflowName:i}=e;return Array.from(t).filter(e=>{var{dependency:t,skipIfDependencyMissing:e=!0}=r.get(e)||{};if(!t)return!0;if(X(t))return this._isStepRegistered({workflowName:i,stepId:t})?s.has(t):!e;if(ee(t)){if(0<t.filter(e=>!this._isStepRegistered({workflowName:i,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===S.GRP_COMMUNITY||(""+t).startsWith(is.COMMUNITY)&&!(""+t).includes(is.TOPIC),Vs=(e="")=>{e=e.startsWith("GROUP")?e.replace("GROUP",""):e;return e.startsWith(is.COMMUNITY)&&(""+e).includes(is.TOPIC)},Bs="openim",js="million_group_open_http_svc";function Ks(s){return I(this,void 0,void 0,function*(){var{servcmd:e,data:t}=Ws(e=s.data)||Hs(e)?function(e){let{servcmd:t,data:s}=e;var r,i,n;return Hs(s)?({servcmd:e,data:r}=e,{GroupId:i=""}=r,[i]=(n=i).split(is.TOPIC),{servcmd:Ys(e),data:Object.assign(Object.assign({},r),{GroupId:i,TopicId:n})}):{servcmd:t=Ws(s)?Ys(t):t,data:s}}(s):s,t=k.common.generateProtocolData({servcmd:e,data:t}),e=""+t.head.seq+e;return k.channel.sendPacket(t,{requestId:e})})}function Ws(e){var{Type:e,GroupId:t,GroupIdList:s=[]}=e,t=t||s[0]||"";return xs({type:e,groupID:t})}function Hs(e){var{GroupId:e=""}=e;return Vs(e)}function Ys(e){return e.includes(Bs)?e:(e=e.split(".")[1],js+"."+e)}function g(){var e;return null==(e=k.store.get("login"))?void 0:e.userId}let $s=e=>ee(e)||te(e),zs=(s,r,i,n)=>{if(!$s(s)||!$s(r))return 0;let o=0;var a,u=Object.keys(r);for(let e=0,t=u.length;e<t;e++)if(a=u[e],!(Q(r[a])||i&&i.includes(a)))if($s(s[a])&&$s(r[a]))o+=zs(s[a],r[a],i,n);else{if(n&&n.includes(r[a]))continue;s[a]!==r[a]&&(s[a]=r[a],o+=1)}return o},Js=(e,t)=>{if(Q(t))return"";switch(e){case S.MSG_TEXT:return t.text||"";case S.MSG_IMAGE:return"[Image]";case S.MSG_LOCATION:return"[Location]";case S.MSG_AUDIO:return"[Voice]";case S.MSG_VIDEO:return"[Video]";case S.MSG_FILE:return"[File]";case S.MSG_CUSTOM:return"[Custom Messages]";case S.MSG_GRP_TIP:return"[Group Notification]";case S.MSG_GRP_SYS_NOTICE:return"[Group System Message]";case S.MSG_FACE:return"[Animated Sticker]";case S.MSG_MERGER:return"[Chat Record]";default:return""}},Qs=[{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}],Xs="im_sdk_config_mgr.fetch_config",Zs="im_sdk_config_mgr.push_configv2",er="cloud-config",tr=new class{init(e){this.core=e}};function sr(s){return I(this,void 0,void 0,function*(){var e=(tr.core.store.get("instance")||{})["sdkAppId"],e=tr.core.helper.generateProtocolData({servcmd:Xs,data:{uint32_sdkappid:e,uint64_version:s}}),t=""+e.head.seq+Xs;return tr.core.channel.sendPacket(e,{requestId:t})})}var rr=new class{constructor(){this._core=null,this._expirationTime=0,this._version=0,this._isFetching=!1,this._cmdFrequencyLimitMap=new Map,this._methodCallFrequencyMap=new Map}install(e){var{notificationCenter:e,InnerEvent:t,helper:s,constants:{WORKFLOW_NAME:r,WORKFLOW_STEP:i},channel:n}=this._core=e;e.subscribeInnerEvent(Zs,this._handlePushedConfig,this),s.registerWorkflowStep(r.SYNC_SERVER_INFO_AFTER_LOGIN,i.CLOUD_CONFIG_SYNC,this._handleLoginSuccess,this),e.subscribeInnerEvent(t.LOGOUT,this._reset,this),e.subscribeInnerEvent(t.DESTROY,this._dispose,this),s.registerExperimentalAPI("getServerConfig",this),this._updateCmdFreqLimitMap(Qs),n.registerBeforeSendInterceptor(this.checkMethodCallOverLimit,this)}getServerConfig(s){return I(this,void 0,void 0,function*(){var e,t={code:0,data:""};return s&&(t.data=(null==(e=this._core.store.get("cloudConfig"))?void 0:e[s])||""),t})}checkMethodCallOverLimit(e){if(this._cmdFrequencyLimitMap.has(e))if(this._methodCallFrequencyMap.has(e)){var{count:t,interval:s}=this._cmdFrequencyLimitMap.get(e),{startTime:r,methodCallCounter:i}=this._methodCallFrequencyMap.get(e);if(Date.now()-r>1e3*s)this._methodCallFrequencyMap.set(e,{startTime:Date.now(),methodCallCounter:1});else if(this._methodCallFrequencyMap.set(e,{startTime:r,methodCallCounter:i+=1}),t<i)throw new this._core.helper.ChatError({code:2996,replacement1:e})}else this._methodCallFrequencyMap.set(e,{startTime:Date.now(),methodCallCounter:1})}_handlePushedConfig(s){return I(this,void 0,void 0,function*(){var{ssoLog:e,utils:{safeStringify:t}}=this._core;e.info("_handlePushedConfig",t(s)),yield this._updateCloudConfig(s)})}_handleLoginSuccess(){return I(this,void 0,void 0,function*(){var e,{ssoLog:t,utils:{safeStringify:s}}=this._core;try{this._canFetch()&&(e=yield sr(this._version),t.info("_fetchCloudConfigIfLogin",s(e)),yield this._updateCloudConfig(e)),this._core.helper.taskScheduler.addTask({id:er,intervalMs:1e3,callback:this._fetchCloudConfigIfReady,context:this})}catch(e){t.error("_fetchCloudConfigIfLogin",s(e))}})}_fetchCloudConfigIfReady(){return I(this,void 0,void 0,function*(){var{ssoLog:t,utils:{safeStringify:s}}=this._core;if(this._canFetch())try{var e=yield sr(this._version);t.info("_fetchCloudConfigIfReady",s(e)),yield this._updateCloudConfig(e)}catch(e){t.error("_fetchCloudConfigIfReady",s(e))}})}_updateCloudConfig(t){return I(this,void 0,void 0,function*(){var e=this._parseCloudConfig(t);e&&(this._core.store.set("cloudConfig",e),yield this._parseCmdFreqLimit(),this._core.notificationCenter.emitInnerEvent(this._core.InnerEvent.CLOUD_CONFIG_UPDATE,e),this._core.notificationCenter.emitOuterEvent(this._core.OuterEvent.SERVER_CONFIG_UPDATED,{name:this._core.OuterEvent.SERVER_CONFIG_UPDATED,data:{config:e}}))})}_canFetch(){var e=(this._core.store.get("login")||{})["isLoggedIn"];return e&&!this._isFetching&&Date.now()>=this._expirationTime}_parseCloudConfig(e){var{int32_error_code:t,str_json_config:s,uint32_expired_time:r,uint64_version:i}=e;let n=null;if(0===t){if(this._version!==i)try{n=JSON.parse(s),this._version=i}catch(e){}this._expirationTime=Date.now()+1e3*r}else this._expirationTime=void 0===t?Date.now()+36e5:Date.now()+12e4;return n}_parseCmdFreqLimit(){return I(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(er),this._core.store.clear("cloudConfig"),this._updateCmdFreqLimitMap(Qs),this._methodCallFrequencyMap.clear(),this._expirationTime=0,this._version=0,this._isFetching=!1}_dispose(){var{notificationCenter:e,InnerEvent:t}=this._core;e.unSubscribeInnerEvent(Zs,this._handlePushedConfig,this),e.unSubscribeInnerEvent(t.LOGOUT,this._reset,this),e.unSubscribeInnerEvent(t.DESTROY,this._dispose,this),this._reset()}};class l{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 ir={SEARCH_GRP_SNS:new l(0,Math.pow(2,1)).toString(),AV_HISTORY_MSG:new l(0,Math.pow(2,2)).toString(),GRP_COMMUNITY:new l(0,Math.pow(2,3)).toString(),MSG_TO_SPECIFIED_GRP_MBR:new l(0,Math.pow(2,4)).toString(),AV_MBR_LIST:new l(0,Math.pow(2,6)).toString(),USER_STATUS:new l(0,Math.pow(2,7)).toString(),CONV_MARK:new l(0,Math.pow(2,9)).toString(),CONV_GROUP:new l(0,Math.pow(2,10)).toString(),AV_BAN_MBR:new l(0,Math.pow(2,11)).toString(),MSG_EXT:new l(0,Math.pow(2,13)).toString(),GRP_COUNTER:new l(0,Math.pow(2,15)).toString(),PLUGIN_TRANSLATE:new l(Math.pow(2,6)).toString(),PLUGIN_VOICE_TO_TEXT:new l(Math.pow(2,7)).toString(),PLUGIN_CS:new l(Math.pow(2,8)).toString(),PLUGIN_PUSH:new l(Math.pow(2,9)).toString(),PLUGIN_BOT:new l(Math.pow(2,10)).toString(),MSG_REACTION:new l(Math.pow(2,16)).toString(),FOLLOW:new l(Math.pow(2,20)).toString()},nr="CommercialConfig",or="commercial-config";var ar,ur,lr=new class{constructor(){this._core=null,this._expirationTime=0,this._isFetching=!1,this._featureMap=new Map,this._methodKeyMap=new Map,this._purchaseBits="0"}install(e){var{helper:t,notificationCenter:s,constants:{WORKFLOW_NAME:r,WORKFLOW_STEP:i,InnerEvent:n}}=this._core=e;s.subscribeInnerEvent(n.COMMERCIAL_CONFIG_PUSH,this._handlePushedConfig,this),s.subscribeInnerEvent(n.LOGOUT,this._handleLogout,this),s.subscribeInnerEvent(n.DESTROY,this._dispose,this),t.registerWorkflowStep(r.SYNC_SERVER_INFO_AFTER_LOGIN,i.COMMERCIAL_CONFIG_UPDATE,this._syncCommercialConfig,this),e.helper.registerExperimentalAPI("isCommercialAbilityEnabled",this),e.helper.registerExperimentalAPI("queryCommercialAbility",this)}isCommercialAbilityEnabled(e){return I(this,void 0,void 0,function*(){var s=parseInt(e,10).toString(2),r=s["length"];let i,n=!0;for(let e=r-1,t=0;0<=e;e--,t++)if("1"===s.charAt(e)&&(i=(t<32?new l(0,2**t):new l(2**(t-32),0)).toString(),!this._featureMap.get(i))){n=!1;break}return this._core.ssoLog.debug("isFeatureEnabled",nr+`.isFeatureEnabled decimalNumber:${e} key:${i} ret:`+n),{code:0,data:{enabled:n}}})}queryCommercialAbility(){return this._purchaseBits}_fetchAndParseCommercialConfig(){return I(this,void 0,void 0,function*(){let s,{ssoLog:e,helper:r,utils:{safeStringify:t}}=this._core;try{this._isFetching=!0;let e=r.generateProtocolData({servcmd:"im_sdk_config_mgr.fetch_imsdk_purchase_bitsv2",data:{uint32_sdkappid:null==(s=this._core.store.get("instance"))?void 0:s.sdkAppId}}),t=yield this._core.channel.sendPacket(e);null!=t&&t.body&&(this._parseCommercialConfig(t.body),this._core.store.set("commercialConfig",this._methodKeyMap))}catch(s){e.error("_fetchAndParseCommercialConfig",t(s))}finally{this._isFetching=!1}})}_syncCommercialConfig(t){return I(this,void 0,void 0,function*(){var e=((null==t?void 0:t.data)||{})["purchaseBits"];e&&(this._parsePurchaseBits(e),this._core.store.set("commercialConfig",this._methodKeyMap)),this._canFetch()&&(yield this._fetchAndParseCommercialConfig()),this._core.helper.taskScheduler.addTask({id:or,intervalMs:1e3,callback:this._fetchCommercialConfigIfReady,context:this})})}_canFetch(){var e=null==(e=this._core.store.get("login"))?void 0:e.isLoggedIn,t=Date.now()>=this._expirationTime;return e&&!this._isFetching&&t}_handlePushedConfig(e){null!=e&&e.body&&(this._parseCommercialConfig(e.body),this._core.store.set("commercialConfig",this._methodKeyMap))}_fetchCommercialConfigIfReady(){return I(this,void 0,void 0,function*(){this._canFetch()&&(yield this._fetchAndParseCommercialConfig())})}_parseCommercialConfig(e){var t,s,r,i,n=this._core["ssoLog"];"object"==typeof e&&({int32_error_code:t,str_error_message:s,str_purchase_bits:r,uint32_expired_time:i}=e,0===t?(this._parsePurchaseBits(r),this._expirationTime=Date.now()+1e3*i):void 0===t?(n.warn("_parseCommercialConfig",nr+"._parseCommercialConfig failed. Invalid message format:",e),this._expirationTime=Date.now()+36e5):(n.warn("_parseCommercialConfig",nr+`._parseCommercialConfig errorCode:${t} errorMessage:`+s),this._expirationTime=Date.now()+12e4))}_isValidPurchaseBits(e){return e&&"string"==typeof e&&1<=e.length&&e.length<=64&&/[01]{1,64}/.test(e)}_parsePurchaseBits(s){var{ssoLog:e,utils:{safeStringify:t}}=this._core;if(this._isValidPurchaseBits(s)){this._purchaseBits=s,this._featureMap.clear(),this._methodKeyMap.clear();var r;for(let e=s.length-1,t=0;0<=e;e--,t++)if(r=(t<32?new l(0,2**t):new l(2**(t-32),0)).toString(),"1"===s[e]){this._featureMap.set(r,!0);let e=this._getKeyByValue(ir,r);e&&this._methodKeyMap.set(e,!0)}else{this._featureMap.set(r,!1);let e=this._getKeyByValue(ir,r);e&&this._methodKeyMap.set(e,!1)}}else e.warn("_parsePurchaseBits",nr+".parsePurchaseBits invalid purchases:"+t(s))}_getKeyByValue(e,t){e=Object.entries(e).find(([,e])=>e===t);return e?e[0]:void 0}_handleLogout(){this._reset()}_dispose(){this._reset(),this._core.notificationCenter.unSubscribeInnerEvent(this._core.InnerEvent.COMMERCIAL_CONFIG_PUSH,this._handlePushedConfig,this),this._core.notificationCenter.unSubscribeInnerEvent(this._core.InnerEvent.LOGOUT,this._reset,this),this._core.notificationCenter.unSubscribeInnerEvent(this._core.InnerEvent.DESTROY,this._dispose,this)}_reset(){this._core.helper.taskScheduler.removeTask(or),this._core.store.set("commercialConfig",{}),this._expirationTime=0,this._isFetching=!1,this._featureMap.clear(),this._purchaseBits="0"}},cr=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)}},dr=new class{constructor(){this.name="ConfigCenter"}install(e){tr.init(e),rr.install(e),lr.install(e),cr.install(e)}},t=new class{constructor(){this.name="ErrorMessage",this._core=null}install(e){return I(this,void 0,void 0,function*(){if(this._core=e,this._canFetch()){let e=yield this._fetchErrorMessage();var t;e&&(t=this._parseResponse(e),this._saveErrorMessage(t))}})}_canFetch(){var e=this._core.store.getStorage("errorMessage");return!e||this._isExpired(e)}_saveErrorMessage(e){this._core.store.setStorage("errorMessage",{errorMessage:e,errorMessageSavedTime:(new Date).getTime()})}_fetchErrorMessage(){return I(this,void 0,void 0,function*(){try{return yield this._core.helper.httpRequest({method:"GET",url:"https://web.sdk.qcloud.com/im/download/error-message/v3/0.0.6/tim-error-message.txt"})}catch(e){console.error(e)}})}_isExpired(e){return!e||(e=e["errorMessageSavedTime"],e&&6048e5<=(new Date).getTime()-e)}_parseResponse(e){if("string"==typeof e){var s=e.split(";\n"),r={},i=new RegExp(/'/g);for(let t=0;t<s.length;t++){var n=s[t].indexOf(":"),o=s[t].slice(0,n);let e=s[t].slice(n+1);o.startsWith("//")||""!==e&&(e=e.replace(i,""),r[o]=e)}return r}}};(yi=ar=ar||{})[yi.START_SYNC=0]="START_SYNC",yi[yi.SYNCING=1]="SYNCING",yi[yi.SYNC_COMPLETE=2]="SYNC_COMPLETE",(n=ur=ur||{})[n.LOGIN_SUCCESS=0]="LOGIN_SUCCESS",n[n.NEW_MESSAGE_RECEIVED=1]="NEW_MESSAGE_RECEIVED";var e=new class{constructor(){this.name="UnreadMessageSynchronizer",this._unreadDBMessageMap=new Map,this._cookie=""}install(e){var t=(this._core=e)["constants"];e.helper.registerWorkflowStep(t.WORKFLOW_NAME.SYNC_SERVER_INFO_AFTER_RE_ONLINE,t.WORKFLOW_STEP.UNREAD_MESSAGE_SYNC,this._syncUnreadDBMessageAfterReOnline,this),e.helper.registerWorkflowStep(t.WORKFLOW_NAME.RECEIVE_C2C_NEW_MESSAGE,t.WORKFLOW_STEP.UNREAD_MESSAGE_SYNC,this._syncUnreadDBMessageAfterNewMessageReceived,this),e.helper.registerWorkflowStep(t.WORKFLOW_NAME.SYNC_SERVER_INFO_AFTER_LOGIN,t.WORKFLOW_STEP.UNREAD_MESSAGE_SYNC,this._syncUnreadDBMessageAfterLogin,this),e.notificationCenter.subscribeInnerEvent(e.InnerEvent.LOGOUT,this._reset,this),e.notificationCenter.subscribeInnerEvent(e.InnerEvent.DESTROY,this._dispose,this)}_syncUnreadMessage(t){return I(this,void 0,void 0,function*(){let{isAfterReOnline:o=!1,isAfterNewMessageReceived:a=!1,isAfterLogin:e=!1}=t||{},u=ar.START_SYNC;for(var l=[],c=[],d=[],p=[];this._canContinueSync({cookie:this._cookie,syncFlag:u});){let e=yield this._fetchUnreadDBMessage({cookie:this._cookie,syncFlag:u,syncTriggerEvent:a?ur.NEW_MESSAGE_RECEIVED:ur.LOGIN_SUCCESS});if(!e)break;let{unreadMessageList:t=[],revokedMessageList:s=[],overflowUnreadCountList:r,unreadCountList:i,groupTipList:n}=e;if(this._cookie=(null==e?void 0:e.cookie)||"",u=null==e?void 0:e.syncFlag,this._parseAndSaveUnreadMessageList(t),d.push(...s),this._updateConversationUnreadOptions({unreadCountList:i,overflowUnreadCountList:r,conversationUpdateFieldList:l}),Array.isArray(n)&&c.push(...n),o){let e=this._handleNewMessageList(t)["messages"];p.push(...e)}}return o?{conversationUpdateFieldList:l,revokedMessageList:d,unreadMessageMap:this._unreadDBMessageMap,groupTipList:c,messages:p}:{conversationUpdateFieldList:l,isInstantMessage:!e,isUnreadC2CMessage:!0,revokedMessageList:d,unreadMessageMap:this._unreadDBMessageMap,groupTipList:c}})}_syncUnreadDBMessageAfterLogin(){return I(this,void 0,void 0,function*(){return this._cookie="",this._syncUnreadMessage({isAfterLogin:!0})})}_syncUnreadDBMessageAfterNewMessageReceived(e){return I(this,void 0,void 0,function*(){if(1===e.data.Flag)return this._syncUnreadMessage({isAfterNewMessageReceived:!0})})}_updateConversationUnreadOptions(e){let{unreadCountList:t,overflowUnreadCountList:s,conversationUpdateFieldList:r}=e,{OuterConstant:{CONV_C2C:i,CONV_SYSTEM:n}}=this._core["constants"];null!=t&&t.forEach(e=>{let{From_Account:t,UnreadCount:s}=e;if(t!==n){let e=r.find(({conversationID:e})=>e===""+i+t);e?e.unreadCount=s:r.push({conversationID:""+i+t,unreadCount:s,type:i})}}),null!=s&&s.forEach(e=>{let{From_Account:t,LastMsgTime:s}=e;t===n||r.find(({conversationID:e})=>e===""+i+t)||r.push({conversationID:""+i+t,type:i,lastMsgTime:s})})}_syncUnreadDBMessageAfterReOnline(){return I(this,void 0,void 0,function*(){return this._syncUnreadMessage({isAfterReOnline:!0})})}_updateMessageProfile(r){var e;let i=(this._core.message||{})["messageDataHandler"],t=null==(e=this._core.store.get("login"))?void 0:e.userId,{from:s,nick:n,avatar:o,conversationID:a=""}=r;if(s!==t){let s=i.getLatestMsgSentByPeer(a);if(s){let{nick:e,avatar:t}=s;n&&o?n===e&&o===t||i.updateNickAndAvatarOfSentMessage({conversationID:a,latestNick:n,latestAvatar:o,isSentByMe:!1}):(r.nick=e,r.avatar=t)}}else{let e=i.getLatestMsgSentByMe(a);!e||n===e.nick&&o===e.avatar||i.updateNickAndAvatarOfSentMessage({conversationID:a,latestNick:n,latestAvatar:o,isSentByMe:!0})}}_handleNewMessageList(e){let t=(this._core.message||{})["messageDataHandler"],u=new Map,s=[];return e.forEach(a=>{this._updateMessageProfile(a);let e=1===a.isModified;if(t.isMessageSentByCurrentInstance(a)?a.isModified=e:e=!1,a.isOnlineMessage())a._onlineOnlyFlag=!0,t.isMessageSentByCurrentInstance(a)||s.push(a);else if(!t.isInMessageList(a)){if(t.storeConversationMessage(a)){let{conversationID:e,conversationType:t,conversationSubType:s,flow:r,_isExcludedFromUnreadCount:i,_isExcludedFromLastMessage:n}=a,o=n?"":a;u.has(e)?(u.get(e).lastMessage=o,"in"!==r||i||u.get(e).unreadCount++):u.set(e,{conversationID:e,type:t,subType:s,unreadCount:i||"in"!==r?0:1,lastMessage:o})}t.isMessageSentByCurrentInstance(a)&&!e||s.push(a)}}),{messages:s,conversationOptions:u}}_fetchUnreadDBMessage(c){return I(this,void 0,void 0,function*(){var{ssoLog:e,utils:{safeStringify:t}}=this._core;try{e.debug("_fetchUnreadDBMessage","unread-message-synchronizer._fetchUnreadDBMessage options:"+t(c));var s,r,i,n,o,a,u,l=yield function(i,u){return I(this,void 0,void 0,function*(){let{cookie:e,syncFlag:t,syncTriggerEvent:s}=i,r="openim.getmsg",o=u.helper.generateProtocolData({servcmd:r,data:{Cookie:e,SyncFlag:t,IsOnlineSync:s,NeedAbstract:1,NeedSignaling:1,NeedCachedMsg:1}}),a=""+o.head.seq+r;try{let e=yield u.channel.sendPacket(o,{requestId:a});if(!e)return null;let{C2CPairUnreadCount:t,C2CRemainingUnreadCount:s,EventArray:r}=e,{unreadMessageList:i,revokedMessageList:n}=function(e,E){let r=[],i=[];return null!=e&&e.forEach(I=>{var e,t,s=function(){var{From_Account:e,From_AccountHeadurl:t,From_AccountNick:s,IsNeedReadReceipt:r,MsgBody:i,MsgClientTime:n,MsgRandom:o,MsgSeq:a,MsgTimeStamp:u,SendMsgControl:l,SupportMessageExtension:c,To_Account:d,TinyId:p,MsgCheckResult:h,CloudCustomData:g,IsPeerRead:_,MsgFlagBits:m,MsgVersion:v,EventArray:f}=I;return{from:e,avatar:t,nick:s,needReadReceipt:1===r,readReceiptSentByPeer:_,clientTime:n,messageFlagBits:m,random:o,sequence:a,time:u,messageControlInfo:l,isSupportExtension:c,to:d,tinyID:p,checkResult:h,cloudCustomData:g,messageVersion:v,eventArray:f,elements:E.message.messageHelper.parseServerPushMessageElement(i)}}();if(null!=(t=null==(e=null==(e=null==I?void 0:I.EventArray)?void 0:e[0])?void 0:e.hasOwnProperty)&&t.call(e,"C2cNotifyMsgArray"))i.push(...function(){let e,t=[];return null!=(e=I.EventArray)&&e.forEach(e=>{var e=e["C2cNotifyMsgArray"],e=null==(e=null==(e=null==e?void 0:e[0])?void 0:e.WithdrawC2cMsgNotify)?void 0:e.C2cWithdrawInfoArray;Array.isArray(e)&&t.push(...e)}),t}());else{let e=E.message.messageFactory.createMessage(Object.assign(Object.assign({},s),{conversationType:"C2C",flow:"in"})),t=s["elements"];e.setElement(t),r.push(e)}}),{unreadMessageList:r,revokedMessageList:i}}(e.MsgList,u);return{syncFlag:null==e?void 0:e.SyncFlag,unreadMessageList:i,revokedMessageList:n,unreadCountList:t,overflowUnreadCountList:s,cookie:null==e?void 0:e.Cookie,groupTipList:r}}catch(e){console.warn(e)}})}(c,this._core);return l?({syncFlag:s,unreadMessageList:r,revokedMessageList:i,cookie:n,unreadCountList:o,overflowUnreadCountList:a,groupTipList:u}=l,this._parseAndSaveUnreadMessageList(r),{syncFlag:s,cookie:n,unreadMessageList:r,revokedMessageList:i,unreadCountList:o,overflowUnreadCountList:a,groupTipList:u}):null}catch(e){console.log(e)}})}_canContinueSync({cookie:e,syncFlag:t}){return t===ar.START_SYNC||t===ar.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()}},pr=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()}},hr=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()}},gr=new class{init(e){var{IN_WX_MINI_APP:t,IN_WX_MINI_PLUGIN:s}=e.helper;s||(t?hr:pr).init(e)}};var _r=new class{init(e){this._core=e,this._activateNetworkMonitoring(),e.notificationCenter.subscribeInnerEvent(e.InnerEvent.DESTROY,this._dispose,this)}_activateNetworkMonitoring(){return I(this,void 0,void 0,function*(){navigator.onLine?this._onOnline():this._onOffline(),this._onOnlineCallback=this._onOnline.bind(this),this._onOfflineCallback=this._onOffline.bind(this),window.addEventListener("online",this._onOnlineCallback),window.addEventListener("offline",this._onOfflineCallback)})}_deactivateNetworkMonitoring(){null!==this._onOnlineCallback&&(window.removeEventListener("online",this._onOnlineCallback),this._onOnlineCallback=null),null!==this._onOfflineCallback&&(window.removeEventListener("offline",this._onOfflineCallback),this._onOfflineCallback=null)}_onNetworkStatusChange(e){var t,{isConnected:e,networkType:s}=e;null!=(t=this._core)&&t.store.set("netWorkMonitor",{isNetworkOnline:e,networkType:s}),null!=(t=this._core)&&t.notificationCenter.emitInnerEvent("networkStatusChange",{isNetworkOnline:e,networkType:s})}_onOnline(){this._onNetworkStatusChange({isConnected:!0,networkType:"online"})}_onOffline(){this._onNetworkStatusChange({isConnected:!1,networkType:"none"})}_reset(){var e;this._deactivateNetworkMonitoring(),null!=(e=this._core)&&e.store.clear("netWorkMonitor")}_dispose(){var e;null!=(e=this._core)&&e.notificationCenter.unSubscribeInnerEvent(null==(e=this._core)?void 0:e.InnerEvent.DESTROY,this._dispose,this),this._reset()}},mr=new class{init(e){this._core=e,this._activateNetworkMonitoring(),e.notificationCenter.subscribeInnerEvent(e.InnerEvent.DESTROY,this._dispose,this)}_activateNetworkMonitoring(){return I(this,void 0,void 0,function*(){try{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()}},vr=new class{init(e){var t=e.utils["IN_MINI_APP"];(t?mr:_r).init(e)}},_=new class{constructor(){this.name="SystemStateMonitor"}install(e){gr.init(e),vr.init(e)}};let fr=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.*"]),Ir="tui_room_svr.*",Er=new class{constructor(){this.name="BusinessCommandTransfer",this._transferredCommands=fr}install(e){var{notificationCenter:e,InnerEvent:t,helper:s}=this._core=e;e.subscribeInnerEvent(t.CLOUD_CONFIG_UPDATE,this._onCloudConfigUpdate,this),e.subscribeInnerEvent(t.LOGOUT,this._reset,this),e.subscribeInnerEvent(t.DESTROY,this._dispose,this),e.subscribeInnerEvent("im_open_push.msg_push",e.InnerEventSubType.BUSINESS_COMMAND,this._onServerPushBusinessCommand,this),s.registerExperimentalAPI("sendTRTCCustomData",this,"transferBusinessCommand"),s.registerExperimentalAPI("sendRoomCustomData",this,"transferBusinessCommand")}transferBusinessCommand(s){return I(this,void 0,void 0,function*(){var t="transferBusinessCommand";try{var{serviceCommand:e=Ir}=s||{};if(this._isValidTransferredCommand(e))return{code:0,data:(yield function(n,o){return I(this,void 0,void 0,function*(){var{helper:e,channel:t}=o,{serviceCommand:s=Ir,data:r}=n||{};let i={};try{i="string"==typeof r?JSON.parse(r):r}catch(e){console.warn(e)}r=e.generateProtocolData({servcmd:s,data:i}),e=""+r.head.seq+s;return t.sendPacket(r,{requestId:e})})}(s,this._core))||{}};throw new this._core.helper.ChatError({code:2995,functionName:t})}catch(e){throw console.warn(e),new this._core.helper.ChatError({code:null==e?void 0:e.errorCode,message:null==e?void 0:e.errorInfo,data:{},functionName:t})}})}_onCloudConfigUpdate(e={}){try{var t;"string"==typeof e.rtc_cmd&&(t=JSON.parse(e.rtc_cmd),Array.isArray(t))&&(this._transferredCommands=new Set([...this._transferredCommands,...t]))}catch(e){console.log(e)}}_isValidTransferredCommand(e=""){e=`${null==e?void 0:e.split(".")[0]}.*`;return this._transferredCommands.has(e)}_onServerPushBusinessCommand(e){var{OuterEvent:t,notificationCenter:s}=this._core,e=(e||{})["MsgContent"],t=t["ROOM_CUSTOM_DATA_RECEIVED"];s.emitOuterEvent(t,{name:t,data:e})}_reset(){this._transferredCommands=fr}_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)}},Cr="signaling",Sr="signaling-timeout";function Mr(e){return e.filter(e=>{var t,s;return"TIMCustomElem"===e.type&&({cloudCustomData:e="",payload:{data:s=""}={}}=e,e=e.match(/"type":"tsignaling"/),t=s.match(/inviteID/),s=s.match(/actionType/),e||t&&s)})}function yr(e){var t=e.payload["data"];try{return JSON.parse(t)}catch(e){return console.error(e),null}}function Tr(e,t){return e.toString(16).padStart(t,"0")}function Ar(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 Or,Dr,Rr,v=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){Cr;var{inviteID:e,groupID:t,inviter:s}=e,s=s===this._core.common.getCurrentUserID();if(!this._onlineSignalingMap.has(e))return!1;var r=this._onlineSignalingMap.get(e)["inviteeList"];if(console.log(`signaling.isInvitationValid inviteID:${e} inviteeList:${r} groupID:`+t),t){if(s)return 0<r.length;let e=this._core.common.getCurrentUserID();return r.includes(e)}return!0}updateSignaling(e){let s=Cr+".updateSignaling",{inviteID:r,inviter:t,inviteeList:i,groupID:n}=e;if(console.log(s+` inviteID:${r} inviter:${t} groupID:`+n),n&&this.hasSignaling(r)){let e=i[0],t=this._onlineSignalingMap.get(r)["inviteeList"];t.includes(e)&&(t.splice(t.indexOf(e),1),console.log(s+` remove ${e}. localInviteeList.length:`+t.length)),0===t.length&&this.removeSignaling(r)}else this.removeSignaling(r)}setSignalingListenStatus(e){this._isSignalingListening=e}getSignalingListenStatus(){return this._isSignalingListening}_dispose(){var e;this._reset(),null!=(e=this._core)&&e.notificationCenter.unSubscribeInnerEvent(this._core.InnerEvent.DESTROY,this._dispose,this),null!=(e=this._core)&&e.notificationCenter.unSubscribeInnerEvent(this._core.InnerEvent.LOGOUT,this._reset,this),this._isSignalingListening=!1}_reset(){this._onlineSignalingMap.clear()}},Lr=new class{init(e){this._core=e}createInviteSignaling(e){var t=this._generateInviteID(),t=this._createInviteSignalingData(Object.assign(Object.assign({},e),{inviteID:t})),{groupID:s,inviteeList:r}=t,s=s||r[0];return{signaling:this._createSignaling(t,s),signalingData:t,signalingExtensionOptions:this._createSignalingExtensionOptions(e)}}createAcceptSignaling(e){var t=this._createAcceptSignalingData(e),{groupID:s,inviter:r}=t;return{signaling:this._createSignaling(t,s||r),signalingData:t,signalingExtensionOptions:this._createSignalingExtensionOptions(e)}}createCancelSignaling(e){var t=this._createCancelSignalingData(e),{groupID:s,inviteeList:r}=t,s=s||r[0];return{signaling:this._createSignaling(t,s),signalingData:t,signalingExtensionOptions:this._createSignalingExtensionOptions(e)}}createRejectSignaling(e){var t=this._createRejectSignalingData(e),{groupID:s,inviter:r}=t;return{signaling:this._createSignaling(t,s||r),signalingData:t,signalingExtensionOptions:this._createSignalingExtensionOptions(e)}}createTimeoutSignaling(e){var{isInviter:t=!1}=e,e=this._createTimeoutSignalingData(e),{groupID:s,inviteeList:r,inviter:i}=e,s=s||(t?r[0]:i);return{signaling:this._createSignaling(e,s),signalingData:e,signalingExtensionOptions:this._createSignalingExtensionOptions(e)}}_createSignalingExtensionOptions(e){var{data:e="",onlineUserOnly:t,inviteID:s="",offlinePushInfo:r,actionType:i}=e,s=(null==(s=null==(s=v.getSignaling(s))?void 0:s.signaling)?void 0:s._onlineOnlyFlag)||!1;return{onlineUserOnly:t||s,offlinePushInfo:r,messageControlInfo:this._createMessageControlInfo(e,i)}}_createMessageControlInfo(e,t){t=5===t&&!!e.match(/excludeTimeoutSignalingFromHistoryMessage/),e=!!e.match(/excludeFromHistoryMessage/)||!!e.match(/excludeOriginalSignalingFromHistoryMessage/);return{excludedFromContentModeration:!0,excludedFromUnreadCount:t||e,excludedFromLastMessage:t||e}}_createInviteSignalingData(e){Cr;var{userID:t,timeout:s=0,groupID:r="",inviteeList:i=[]}=e,n=this._core.common.getCurrentUserID(),e=Object.assign(Object.assign({},this._generateBaseSignalData(e)),{actionType:1,inviter:n,inviteeList:r?i:[t],timeout:s});return console.log("signaling._createInviteSignalingData signalingData:",e),e}_createAcceptSignalingData(e){Cr;var t=e["inviteID"],s=this._core.common.getCurrentUserID(),{inviter:t,groupID:r}=v.getSignaling(t),e=Object.assign(Object.assign({},this._generateBaseSignalData(e)),{actionType:3,groupID:r,inviter:t,inviteeList:[s]});return console.log("signaling._createAcceptSignalingData signalingData:",e),e}_createCancelSignalingData(e){Cr;var t=e["inviteID"],s=this._core.common.getCurrentUserID(),{inviteeList:t,groupID:r}=v.getSignaling(t),e=Object.assign(Object.assign({},this._generateBaseSignalData(e)),{actionType:2,groupID:r,inviter:s,inviteeList:t});return console.log("signaling._createCancelSignalingData signalingData:",e),e}_createRejectSignalingData(e){Cr;var t=e["inviteID"],s=this._core.common.getCurrentUserID(),{inviter:t,groupID:r}=v.getSignaling(t),e=Object.assign(Object.assign({},this._generateBaseSignalData(e)),{actionType:4,groupID:r,inviter:t,inviteeList:[s]});return console.log("signaling._createRejectSignalingData signalingData:",e),e}_createTimeoutSignalingData(e){Cr;var{isInviter:t=!1,inviteID:s}=e,{inviteeList:s,inviter:r}=v.getSignaling(s),i=this._core.common.getCurrentUserID(),e=Object.assign(Object.assign({},this._generateBaseSignalData(e)),{actionType:5,inviter:r,inviteeList:t?s:[i]});return console.log("signaling._createTimeoutSignalingData signalingData:",e),e}_createSignaling(e,t){var{groupID:s=""}=e,t={to:t,conversationType:s?"GROUP":"C2C",priority:"High",payload:{data:JSON.stringify(e)}};return null==(s=null==(e=null==(s=this._core)?void 0:s.message)?void 0:e.messageFactory)?void 0:s.createCustomMessage(t)}_generateInviteID(){return[Tr(Ar(32),8),Tr(Ar(16),4),Tr(16384|Ar(12),4),Tr(32768|Ar(14),4),Tr(Ar(48),12)].join("-")}_generateBaseSignalData(e){var{data:e="",inviteID:t="",groupID:s=""}=e;return{businessID:1,timeout:0,data:e,inviteID:t,groupID:s}}},Nr=new class{constructor(){this._isProcessingSignaling=!1}init(e){(this._core=e).helper.registerApi({apiName:"invite",context:this}),e.helper.registerApi({apiName:"accept",context:this}),e.helper.registerApi({apiName:"cancel",context:this}),e.helper.registerApi({apiName:"reject",context:this}),e.helper.registerApi({apiName:"modifyInvitation",context:this}),e.helper.registerApi({apiName:"getSignalingInfo",context:this}),e.helper.registerApi({apiName:"addSignalingListener",context:this}),e.helper.registerApi({apiName:"removeSignalingListener",context:this}),e.notificationCenter.subscribeInnerEvent(e.InnerEvent.DESTROY,this._dispose,this),e.notificationCenter.subscribeInnerEvent(e.InnerEvent.LOGOUT,this._reset,this)}invite(t){return I(this,void 0,void 0,function*(){var s;try{this._validateBeforeInvite(t);var{signaling:r,signalingData:i,signalingExtensionOptions:e}=Lr.createInviteSignaling(t),n=yield this._sendSignaling(r,e);if(0!==(null==n?void 0:n.code))return n;{let{inviteID:e,timeout:t}=i;return v.saveSignaling(e,Object.assign(Object.assign({},i),{signaling:r})),0<t&&(null!=(s=this._core)&&s.helper.taskScheduler.addOnceTask({id:Sr+"-"+e,intervalMs:1e3*(t+5),callback:this.handleInvitationExpiryTimer.bind(this,e)})),Object.assign(Object.assign({},n),{inviteID:e})}}catch(e){throw e}})}accept(n){return I(this,void 0,void 0,function*(){try{var e=n["inviteID"],{signaling:t,signalingData:s,signalingExtensionOptions:r}=(this._validateBeforeAccept(e),this._isProcessingSignaling=!0,Lr.createAcceptSignaling(n)),i=yield this._sendSignaling(t,r);return 0===(null==i?void 0:i.code)?(v.updateSignaling(s),Object.assign(Object.assign({},i),{inviteID:e})):i}catch(e){throw e}finally{this._isProcessingSignaling=!1}})}cancel(i){return I(this,void 0,void 0,function*(){try{var e=i["inviteID"],{signaling:t,signalingExtensionOptions:s}=(this._validateBeforeCancel(e),this._isProcessingSignaling=!0,Lr.createCancelSignaling(i)),r=yield this._sendSignaling(t,s);return 0===(null==r?void 0:r.code)?(v.removeSignaling(e),Object.assign(Object.assign({},r),{inviteID:e})):r}catch(e){throw e}finally{this._isProcessingSignaling=!1}})}reject(i){return I(this,void 0,void 0,function*(){try{var e=i["inviteID"],{signaling:t,signalingExtensionOptions:s}=(this._validateBeforeReject(e),this._isProcessingSignaling=!0,Lr.createRejectSignaling(i)),r=yield this._sendSignaling(t,s);return 0===(null==r?void 0:r.code)?(v.removeSignaling(e),Object.assign(Object.assign({},r),{inviteID:e})):r}catch(e){throw e}finally{this._isProcessingSignaling=!1}})}modifyInvitation(e){return I(this,void 0,void 0,function*(){var r,i,{inviteID:n,data:o}=e;let a="";try{this._validateBeforeModifyInvitation(n);let e=v.getSignaling(n),t=e["signaling"],s=f(e,["signaling"]);a=t.payload.data,s.data=o,t.payload.data=JSON.stringify(s);var u=yield null==(i=null==(r=this._core)?void 0:r.message.messageAction)?void 0:i.modifyMessage(t);return v.hasSignaling(n)&&v.saveSignaling(n,Object.assign(Object.assign({},s),{signaling:t})),u}catch(e){if(a){let e=v.getSignaling(n)["signaling"];e.payload.data=a}throw e}})}getSignalingInfo(e){var{ssoLog:t,utils:{safeStringify:s}}=this._core;if(0!==Mr([e]).length)return e={businessID:(e=yr(e)).businessID||1,inviteID:e.inviteID,groupID:e.groupID||"",inviter:e.inviter||"",inviteeList:e.inviteeList||[],data:e.data||"",actionType:e.actionType||1,timeout:e.timeout||0},t.debug(Cr+" getSignalingInfo "+s(e)),e}addSignalingListener(e,t,s){var r;e===(null==(r=this._core)?void 0:r.SignalingEvent.NEW_INVITATION_RECEIVED)&&v.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)&&v.setSignalingListenStatus(!1),null!=(r=this._core)&&r.notificationCenter.unSubscribeOuterEvent(e,t,s)}handleInvitationExpiryTimer(e){var t=v.getOnlineSignalingMap(),s=this._core.common.getCurrentUserID();t.has(e)&&(t=t.get(e).inviter===s,this._sendTimeoutNotice({inviteID:e,isInviter:t}))}_sendSignaling(t,s){return I(this,void 0,void 0,function*(){var e;return null==(e=null==(e=null==(e=this._core)?void 0:e.message)?void 0:e.messageSender)?void 0:e.sendMessage(t,s)})}_sendTimeoutNotice(s){return I(this,void 0,void 0,function*(){var i;this._core.ssoLog.debug("_sendTimeoutNotice",Cr+"._sendTimeoutNotice params:"+JSON.stringify(s));let{isInviter:n,inviteID:o}=s,{signaling:a,signalingData:u,signalingExtensionOptions:e}=Lr.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}=u;null!=(i=this._core)&&i.notificationCenter.emitOuterEvent(null==(i=this._core)?void 0:i.SignalingEvent.INVITATION_TIMEOUT,{name:null==(i=this._core)?void 0:i.SignalingEvent.INVITATION_TIMEOUT,data:{data:e,groupID:t,inviteID:o,inviteeList:s,inviter:r,isSelfTimeout:!0,message:a}}),n?v.removeSignaling(o):v.updateSignaling(u)}})}_validateInviteId(e,t){if(!v.hasSignaling(t))throw new this._core.helper.ChatError({functionName:e,code:8010})}_validateProcessStatus(e){if(this._isProcessingSignaling)throw new this._core.helper.ChatError({functionName:e,message:"processing other signaling operations"})}_validateBeforeInvite(e){var e=e["userID"],t=this._core.common.getCurrentUserID();if(e===t)throw new this._core.helper.ChatError({functionName:"invite",message:`cannot invite yourself, currentUserId:${t}, inviteeId:`+e})}_validateBeforeAccept(t){var s="accept";this._validateInviteId(s,t),this._validateProcessStatus(s);let r=this._core.common.getCurrentUserID(),e=v.getSignaling(t)["inviteeList"];if(!e.includes(r)){let e=`userID:${r} not in inviteeList. inviteID:`+t;throw new this._core.helper.ChatError({functionName:s,message:e})}}_validateBeforeCancel(e){var t="cancel",s=(this._validateInviteId(t,e),this._validateProcessStatus(t),this._core.common.getCurrentUserID()),r=v.getSignaling(e)["inviter"];if(r!==s){let e=`unmatched inviter:${r} and my userID:`+s;throw new this._core.helper.ChatError({functionName:t,message:e})}}_validateBeforeReject(t){var s="reject";this._validateInviteId(s,t),this._validateProcessStatus(s);let r=this._core.common.getCurrentUserID(),e=v.getSignaling(t)["inviteeList"];if(!e.includes(r)){let e=`userID:${r} not in inviteeList. inviteID:`+t;throw new this._core.helper.ChatError({functionName:s,message:e})}}_validateBeforeModifyInvitation(e){this._validateInviteId("modifyInvitation",e)}_dispose(){var e;this._reset(),null!=(e=this._core)&&e.notificationCenter.unSubscribeInnerEvent(this._core.InnerEvent.DESTROY,this._dispose,this),null!=(e=this._core)&&e.notificationCenter.unSubscribeInnerEvent(this._core.InnerEvent.LOGOUT,this._reset,this)}_reset(){this._isProcessingSignaling=!1}},br=new class{constructor(){this._actionProcessor=new Map([[1,this._onNewInvitationReceived.bind(this)],[4,this._onInviteeRejected.bind(this)],[3,this._onInviteeAccepted.bind(this)],[2,this._onInvitationCancelled.bind(this)],[5,this._onInvitationTimeout.bind(this)]])}init(e){(this._core=e).notificationCenter.subscribeOuterEvent(e.OuterEvent.MESSAGE_RECEIVED,this._handleMessageReceived,this),e.notificationCenter.subscribeOuterEvent(e.OuterEvent.MESSAGE_MODIFIED,this._handleMessageModified,this),e.notificationCenter.subscribeInnerEvent(e.InnerEvent.DESTROY,this._dispose,this)}handleActionSignaling(e){e.forEach(e=>{var t,s=yr(e);s&&null!=(t=this._actionProcessor.get(s.actionType))&&t(s,e)})}_handleMessageReceived(e){v.getSignalingListenStatus()&&0!==(e=Mr(e.data)).length&&this.handleActionSignaling(e)}_handleMessageModified(e){v.getSignalingListenStatus()&&0<(e=Mr(e.data)).length&&e.forEach(e=>{var t=yr(e);t&&this._onInvitationModified(t,e)})}_onNewInvitationReceived(t,s){Cr;var{inviteID:r,inviteeList:i,groupID:n}=t,o=this._core.common.getCurrentUserID();if(this._core.ssoLog.debug("_onNewInvitationReceived",`signaling._onNewInvitationReceived signalingData:${JSON.stringify(t)}}`),!n||i.includes(o)){let e=t["timeout"];var n=Date.now()/1e3-s.time,o=(0<e&&0<n&&e>n&&(e-=n),v.getSignaling(r));o!==t&&(o||v.saveSignaling(r,Object.assign(Object.assign({},t),{signaling:s})),0<e&&(null!=(n=this._core)&&n.helper.taskScheduler.addOnceTask({id:Sr+"-"+r,intervalMs:1e3*e,callback:Nr.handleInvitationExpiryTimer.bind(Nr,r)})),this._emitEvent({name:null==(o=this._core)?void 0:o.SignalingEvent.NEW_INVITATION_RECEIVED,data:Object.assign(Object.assign({},this._generateBaseEmitData(t)),{inviteeList:i})}))}}_onInviteeRejected(e){Cr;var{inviteID:t,inviter:s,groupID:r,inviteeList:i}=e,n=v.hasSignaling(t);this._core.ssoLog.debug("_onInviteeRejected",`signaling._onInviteeRejected inviteID:${t} hasInviteID:${n} inviter:${s} groupID:`+r),n&&(v.updateSignaling(e),this._emitEvent({name:null==(t=this._core)?void 0:t.SignalingEvent.INVITEE_REJECTED,data:Object.assign(Object.assign({},this._generateBaseEmitData(e)),{invitee:i[0]})}))}_onInviteeAccepted(e){Cr;var{inviteID:t,inviter:s,groupID:r,inviteeList:i}=e,n=v.hasSignaling(t);this._core.ssoLog.debug("_onInviteeAccepted",`signaling._onInviteeAccepted inviteID:${t} hasInviteID:${n} inviter:${s} groupID:`+r),n&&(v.updateSignaling(e),this._emitEvent({name:null==(t=this._core)?void 0:t.SignalingEvent.INVITEE_ACCEPTED,data:Object.assign(Object.assign({},this._generateBaseEmitData(e)),{invitee:i[0]})}))}_onInvitationCancelled(e){Cr;var{inviteID:t,inviter:s,groupID:r}=e,i=v.hasSignaling(t);this._core.ssoLog.debug("_onInvitationCancelled",`signaling._onInvitationCancelled inviteID:${t} hasInviteID:${i} inviter:${s} groupID:`+r),i&&(v.removeSignaling(t),this._emitEvent({name:null==(s=this._core)?void 0:s.SignalingEvent.INVITATION_CANCELLED,data:this._generateBaseEmitData(e)}))}_onInvitationTimeout(e){Cr;var{inviteID:t,inviteeList:s}=e,r=v.hasSignaling(t);this._core.ssoLog.debug("_onInvitationTimeout",`signaling._onInvitationTimeout inviteID:${t} hasInviteID:${r} data:`+e.data),r&&(v.updateSignaling(e),this._emitEvent({name:null==(t=this._core)?void 0:t.SignalingEvent.INVITATION_TIMEOUT,data:Object.assign(Object.assign({},this._generateBaseEmitData(e)),{inviteeList:s,isSelfTimeout:!1})}))}_onInvitationModified(e,t){Cr;var{inviteID:s,data:r}=e,i=v.hasSignaling(s);this._core.ssoLog.debug("_onInvitationModified",`signaling._onInvitationModified inviteID:${s} data:`+r),i&&(v.saveSignaling(s,Object.assign(Object.assign({},e),{signaling:t})),this._emitEvent({name:null==(i=this._core)?void 0:i.SignalingEvent.INVITATION_MODIFIED,data:{inviteID:s,data:r}}))}_emitEvent(e){var t;null!=(t=this._core)&&t.notificationCenter.emitOuterEvent(e.name,e)}_generateBaseEmitData(e){var{inviteID:e,inviter:t,groupID:s,data:r}=e;return{inviteID:e,inviter:t,groupID:s,data:r||""}}_dispose(){var e;null!=(e=this._core)&&e.notificationCenter.unSubscribeOuterEvent(this._core.OuterEvent.MESSAGE_RECEIVED,this._handleMessageReceived,this),null!=(e=this._core)&&e.notificationCenter.unSubscribeOuterEvent(this._core.OuterEvent.MESSAGE_MODIFIED,this._handleMessageModified,this),null!=(e=this._core)&&e.notificationCenter.unSubscribeOuterEvent(this._core.InnerEvent.DESTROY,this._dispose,this)}},Gr=new class{constructor(){this._offlineSignalingMap=new Map}init(e){var{notificationCenter:e,helper:t,constants:{InnerEvent:s,WORKFLOW_STEP:r,WORKFLOW_NAME:i}}=this._core=e;e.subscribeInnerEvent(s.DESTROY,this._dispose,this),e.subscribeInnerEvent(s.LOGOUT,this._reset,this),t.registerWorkflowStep(i.SYNC_SERVER_INFO_AFTER_LOGIN,r.SIGNALING_MESSAGE_RECOVER,this._handleC2COfflineMessage,this)}_handleC2COfflineMessage(e){var{result:{unreadMessageMap:e}={}}=e||{};if(0!==(null==e?void 0:e.size)&&v.getSignalingListenStatus()){e=Mr([...e.values()]);if(0!==e.length&&(e.forEach(e=>{this._handleC2CActionType(e)}),0<this._offlineSignalingMap.size)){let e=this._sortOfflineSignalingByTime();br.handleActionSignaling(e)}}}_handleC2CActionType(e){var t,s=yr(e);s&&(t=s["actionType"],1===t?this._saveValidOfflineInvite(s,e):this._removeOfflineInvite(s))}_saveValidOfflineInvite(e,t){var{inviteID:s,inviteeList:r=[],timeout:i=0}=e,n=this._core.common.getCurrentUserID();r.includes(n)&&(r=Date.now()/1e3-t.time,0<i&&i<r&&0!==i||this._offlineSignalingMap.set(s,Object.assign(Object.assign({},e),{signalingList:[t]})))}_removeOfflineInvite(e){var{inviteID:e=""}=e;this._offlineSignalingMap.has(e)&&this._offlineSignalingMap.delete(e)}_sortOfflineSignalingByTime(){let t=[];return this._offlineSignalingMap.forEach(e=>{t=[...t,...e.signalingList]}),t.sort((e,t)=>e.time-t.time)}_dispose(){var e;this._reset(),null!=(e=this._core)&&e.notificationCenter.unSubscribeInnerEvent(this._core.InnerEvent.LOGOUT,this._reset,this),null!=(e=this._core)&&e.notificationCenter.unSubscribeInnerEvent(this._core.InnerEvent.DESTROY,this._dispose,this)}_reset(){this._offlineSignalingMap.clear()}};let Pr={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}}},wr={invite:!0,cancel:!0,accept:!0,reject:!0,modifyInvitation:!0},Ur=new class{constructor(){this.name="Signaling"}install(e){Nr.init(e),br.init(e),Lr.init(e),v.init(e),Gr.init(e),e.helper.registerValidateConfig({auth:wr,params:Pr})}},E=new class{init(e){this.core=e}},kr=((b=Or=Or||{}).MSG_TEXT="TIMTextElem",b.MSG_CUSTOM="TIMCustomElem",b.MSG_LOCATION="TIMLocationElem",b.MSG_FACE="TIMFaceElem",(N=Dr=Dr||{})[N.FORWARD=0]="FORWARD",N[N.BACKWARD=1]="BACKWARD",{ZH_CN:"zh (cmn-Hans-CN)",EN_US:"en-US",YUE_HK:"yue-Hant-HK",JA_JP:"ja-JP",ZH_PY:"zh-PY"}),Fr="16k_zh-PY",qr={[kr.ZH_CN]:"16k_zh",[kr.EN_US]:"16k_en",[kr.YUE_HK]:"16k_yue",[kr.JA_JP]:"16k_ja",[kr.ZH_PY]:Fr},xr=/\.(wav|pcm|ogg-opus|speex|silk|mp3|m4a|aac|amr)/,Vr={READ:0,UNREAD:1},Br=((ba=Rr=Rr||{}).IN="in",ba.OUT="out","C2C"),jr="GROUP";function Kr(n){return I(this,void 0,void 0,function*(){var e,s=E.core["appStore"],{messageList:t,conversationID:r}=n,s=s.conversationStore.getConversationMap();let i=null==(e=s.get(r))?void 0:e.peerReadTime;if(!i){let e=r.replace(Br,""),t=yield function(t){return I(this,void 0,void 0,function*(){var e={To_Account:t};return E.core.common.buildAndSendPacket({servcmd:"openim.get_peer_read_time",data:e})})}([e]);if(t){let e=t["ReadTime"];i=null==e?void 0:e[0],s.has(r)&&(s.get(r).peerReadTime=i)}}t.forEach(e=>{e.time<=i&&!e.isPeerRead&&"out"===e.flow&&(e.isPeerRead=!0)})})}function Wr(a){return I(this,void 0,void 0,function*(){var e;let{message:s,user:t,appStore:r,constants:{OuterConstant:i}}=E.core,n=r.conversationStore.getConversationMap();if(n.has(a)){let s=null==(e=n.get(a))?void 0:e.userProfile;if(s&&a.startsWith(i.CONV_C2C)){let{avatar:e,nick:t}=s;E.core.message.messageDataHandler.updateNickAndAvatarOfSentMessage({conversationID:a,latestAvatar:e,latestNick:t,isSentByMe:!1})}}var o=((yield t.userProfile.getMyProfile())||{})["data"];if(o){let{avatar:e,nick:t}=o;s.messageDataHandler.updateNickAndAvatarOfSentMessage({conversationID:a,latestAvatar:e,latestNick:t,isSentByMe:!0})}})}function Hr(e){let t,s=E.core["message"],{conversationID:r,messageID:i}=e;return t=(t=s.messageDataHandler.getLocalMessageList(r).find(e=>e.ID===i))||s.messageDataHandler.getSparseMessageList(r).find(e=>e.ID===i)}function Yr(e){return e.map(e=>{var{from:t,to:s,cloudCustomData:r,avatar:i,nick:n,ID:o,clientSequence:a,clientTime:u,messageRandom:l,messageSequence:c,time:d}=e;return{ClientSeq:a,CloudCustomData:r,From_Account:t,From_AccountHeadurl:i,From_AccountNick:n,Id:o,MsgBody:JSON.parse(JSON.stringify(e.transformElementsToServerFormat())),MsgClientTime:u,MsgRandom:l,Random:l,MsgSeq:c,MsgTimeStamp:d,ReceiverId:s,SenderId:t,To_Account:s}})}function $r(e){var{From_Account:t,From_AccountHeadurl:s,From_AccountNick:r,GroupId:i,MsgClientTime:n,ClientSeq:o,To_Account:a,MsgTimeStamp:u,TinyId:l,MsgRandom:c,MsgSeq:d}=e;return{from:t,avatar:s,nick:r,clientTime:n,time:u,tinyID:l,random:c,sequence:d,to:a,groupID:i,clientSequence:o,_elements:null==(t=e.MsgBody)?void 0:t.map(e=>{var t=e["MsgType"];return E.core.message.messageFactory.getElementClass(t).parseServerPushElement(e)})}}var zr=new class{constructor(){this._reactionsMap=new Map}init(e){var{helper:e,notificationCenter:t,InnerEvent:{MESSAGE_PUSH:s},InnerEventSubType:{MESSAGE_REACTION_UPDATED:r,MESSAGE_REACTION_UPDATED_SYNC:i}}=this._core=e;e.registerApi({apiName:"addMessageReaction",context:this}),e.registerApi({apiName:"removeMessageReaction",context:this}),e.registerApi({apiName:"getMessageReactions",context:this}),e.registerApi({apiName:"getAllUserListOfMessageReaction",context:this}),t.subscribeInnerEvent(s,r,this._handleReactionUpdated,this),t.subscribeInnerEvent(s,i,this._handleReactionSync,this)}addMessageReaction(d,p){return I(this,void 0,void 0,function*(){let{OuterConstant:e,helper:s}=this._core;this._validateMessageReactionBusinessCapability();var{conversationID:r,ID:i,conversationType:t,from:n,to:o,clientSequence:a,random:u,time:l,sequence:c}=d,r=`conversationID:${r} messageID:${i} reactionID:`+p;try{return this._recordMessageReactedByMe(i,p),t===e.CONV_C2C?yield function(o,a){return I(this,void 0,void 0,function*(){var{from:e,to:t,clientSequence:s,random:r,time:i,reactionID:n}=o,t={From_Account:e,To_Account:t,MsgKey:s+`_${r}_`+i,Reaction:n,Add_Account:[null==(e=a.store.get("login"))?void 0:e.userId]};return E.core.common.buildAndSendPacket({servcmd:"openim_msg_ext_http_svc.reaction_add",data:t})})}({from:n,to:o,clientSequence:a,random:u,time:l,reactionID:p},this._core):t===e.CONV_GROUP&&(yield function(r,i){return I(this,void 0,void 0,function*(){var{to:e,reactionID:t,sequence:s}=r,s={GroupId:e,MsgSeq:s,Reaction:t,Add_Account:[null==(e=i.store.get("login"))?void 0:e.userId]};return E.core.common.buildAndSendPacket({servcmd:"openim_msg_ext_http_svc.group_reaction_add",data:s})})}({to:o,reactionID:p,sequence:c},this._core)),{code:0,successLog:{message:r}}}catch(e){this._removeMyReactionRecord(i,p);let t=(e||{})["errorCode"];throw new s.ChatError({functionName:"addMessageReaction",code:t,moreMessage:r})}})}removeMessageReaction(d,p){return I(this,void 0,void 0,function*(){var{OuterConstant:e,helper:s}=this._core,{conversationID:r,ID:t,conversationType:i,from:n,to:o,clientSequence:a,random:u,time:l,sequence:c}=(this._validateMessageReactionBusinessCapability(),d),r=`conversationID:${r} messageID:${t} reactionID:`+p;try{return this._removeMyReactionRecord(t,p),i===e.CONV_C2C?yield function(o,a){return I(this,void 0,void 0,function*(){var{from:e,to:t,clientSequence:s,random:r,time:i,reactionID:n}=o,t={From_Account:e,To_Account:t,MsgKey:s+`_${r}_`+i,Reaction:n,Del_Account:[null==(e=a.store.get("login"))?void 0:e.userId]};return E.core.common.buildAndSendPacket({servcmd:"openim_msg_ext_http_svc.reaction_del",data:t})})}({from:n,to:o,clientSequence:a,random:u,time:l,reactionID:p},this._core):i===e.CONV_GROUP&&(yield function(r,i){return I(this,void 0,void 0,function*(){var{to:e,reactionID:t,sequence:s}=r,s={GroupId:e,MsgSeq:s,Reaction:t,Del_Account:[null==(e=i.store.get("login"))?void 0:e.userId]};return E.core.common.buildAndSendPacket({servcmd:"openim_msg_ext_http_svc.group_reaction_del",data:s},i)})}({to:o,reactionID:p,sequence:c},this._core)),{code:0,successLog:{message:r}}}catch(e){let t=(e||{})["errorCode"];throw new s.ChatError({functionName:"removeMessageReaction",code:t,moreMessage:r})}})}getAllUserListOfMessageReaction(u){return I(this,void 0,void 0,function*(){this._validateMessageReactionBusinessCapability();let{message:e,reactionID:t,nextSeq:r=0}=u,s=100<u.count?100:u.count,i=e["conversationID"],{helper:n,constants:o}=this._core;try{var a;if(a=i.startsWith(o.OuterConstant.CONV_C2C)?yield function(u){return I(this,void 0,void 0,function*(){var{message:e,nextSeq:t,reactionID:s,count:r}=u,{from:e,to:i,clientSequence:n,random:o,time:a}=e,s={Reaction:s,NextSeq:t,Count:r,From_Account:e,To_Account:i,MsgKey:n+`_${o}_`+a};return E.core.common.buildAndSendPacket({servcmd:"openim_msg_ext_http_svc.reaction_iterate",data:s})})}({message:e,reactionID:t,nextSeq:r,count:s}):yield function(n){return I(this,void 0,void 0,function*(){var{message:e,nextSeq:t,reactionID:s,count:r}=n,{sequence:e,to:i}=e,s={Reaction:s,NextSeq:t,GroupId:i,Count:r,MsgSeq:e};return E.core.common.buildAndSendPacket({servcmd:"openim_msg_ext_http_svc.group_reaction_iterate",data:s})})}({message:e,reactionID:t,nextSeq:r,count:s})){let{Reaction_Account:e,NextSeq:t}=a,s=yield this._getUserProfileList(e);return{code:0,data:{nextSeq:t,isCompleted:0===r,userList:s}}}}catch(e){let t=(e||{})["errorCode"];throw new n.ChatError({functionName:"getAllUserListOfMessageReaction",code:t})}})}getMessageReactions(h){return I(this,void 0,void 0,function*(){var e=this._core["constants"],{messageList:t,maxUserCountPerReaction:s=10}=(this._validateMessageReactionBusinessCapability(),h),r=t[0];let i=null,n=new Map,{from:o,to:a,conversationType:u}=r,l=this._generateMessageKeyList(t,n),{Results:c=[]}=(u===e.OuterConstant.CONV_C2C?i=yield function(i){return I(this,void 0,void 0,function*(){var{from:e,to:t,messageKeyList:s,maxUserCountPerReaction:r}=i,e={From_Account:e,To_Account:t,MsgKeyList:s,Count:r};return E.core.common.buildAndSendPacket({servcmd:"openim_msg_ext_http_svc.reaction_multi_stat",data:e})})}({from:o,to:a,messageKeyList:l,maxUserCountPerReaction:s}):u===e.OuterConstant.CONV_GROUP&&(i=yield function(r){return I(this,void 0,void 0,function*(){var{groupId:e,messageSequenceList:t,maxUserCountPerReaction:s}=r,e={GroupId:e,MsgSeqList:t,Count:s};return E.core.common.buildAndSendPacket({servcmd:"openim_msg_ext_http_svc.group_reaction_multi_stat",data:e})})}({groupId:a,messageSequenceList:l,maxUserCountPerReaction:s})),i||{}),d=this._extractUserIDsFromReactionResults(c),p=yield this._getUserProfileMap(d);return{code:0,data:{resultList:c.map(e=>{var{ReactionList:e,MsgSeq:t,MsgKey:s}=e;return{messageID:this._generateMessageID({messageSequence:t,messageKey:s,messageIDMap:n}),reactionList:e.map(e=>{var{Reaction:e,Count:t,Reaction_Account:s,ReactedByMe:r}=e;return{reactionID:e,totalUserCount:t,partialUserList:this._generatePartialUserInfo({userIDList:s,userProfileMap:p}),reactedByMyself:1===r}})}})}}})}dispose(){this._reactionsMap.clear()}_extractUserIDsFromReactionResults(e){let t=[];return null!=e&&e.forEach(e=>{var{ReactionList:e=[]}=e;e.forEach(e=>{e.Reaction_Account&&t.push(...e.Reaction_Account)})}),t}_getUserProfileList(s){return I(this,void 0,void 0,function*(){var e;try{var t=yield null==(e=this._core.user.userProfile)?void 0:e.getUserProfile({userIDList:s});return t?t.data:[]}catch(e){return[]}})}_getUserProfileMap(e){return I(this,void 0,void 0,function*(){let r=new Map;return(yield this._getUserProfileList(e)).forEach(e=>{var{nick:e,avatar:t,userID:s}=e;r.set(s,{nick:e,avatar:t,userID:s})}),r})}_recordMessageReactedByMe(e,t){e=e+"-"+t;this._reactionsMap.has(e)?this._reactionsMap.get(e).reactedByMe=!0:this._reactionsMap.set(e,{reactedByMe:!0})}_removeMyReactionRecord(e,t){e=e+"-"+t;this._reactionsMap.has(e)&&(this._reactionsMap.get(e).reactedByMe=!1)}_recordMessageReactionInfo(e){var{messageID:e,reactionID:t,reactionInfo:s}=e,e=e+"-"+t,t=this._reactionsMap.get(e)||{};this._reactionsMap.set(e,Object.assign(Object.assign({},t),s))}_validateMessageReactionBusinessCapability(){var{helper:e,constants:t}=this._core;if(!e.checkBusinessCapabilityBits("MSG_REACTION"))throw new e.ChatError({functionName:"addMessageReaction",code:t.ERROR_CODE.NO_USE,replacement1:"addMessageReaction"})}_handleReactionUpdated(e){let t=e["MsgReactionNotifyList"],{notificationCenter:d,constants:p}=this._core;t.forEach(c=>I(this,void 0,void 0,function*(){let{C2CMsgInfo:e,GroupMsgInfo:t,MsgReactionSummary:s}=c,{TinyId:r,MsgClientTime:i,MsgRandom:n}=Object.assign(Object.assign({},e),t),o=r+`-${i}-`+n,a=this._extractUserIDsFromReactionResults([{ReactionList:s}]),u=yield this._getUserProfileMap(a),l=s.map(e=>{var{Reaction:t,Reaction_Account:s}=e,r=this._generatePartialUserInfo({userIDList:s,userProfileMap:u}),s=s?e.Count:0,e=(null==(e=this._reactionsMap.get(o+"-"+t))?void 0:e.reactedByMe)||!1;return this._recordMessageReactionInfo({messageID:o,reactionID:t,reactionInfo:{reactionID:t,totalUserCount:s,partialUserList:r}}),{reactionID:t,totalUserCount:s,partialUserList:r,reactedByMyself:e}});d.emitOuterEvent(p.OuterEvent.MESSAGE_REACTIONS_UPDATED,{name:p.OuterEvent.MESSAGE_REACTIONS_UPDATED,data:{messageID:o,reactionList:l}})}))}_handleReactionSync(e){var{notificationCenter:t,constants:s}=this._core,{C2CMsgInfo:e={},GroupMsgInfo:r={},Reaction:i,OperateType:n}=e.MsgReactionNotify,{TinyId:e="",MsgClientTime:r=0,MsgRandom:o=0}=Object.assign(Object.assign({},e),r),r=e+`-${r}-`+o,o=r+"-"+i;if(1===n?this._recordMessageReactedByMe(r,i):this._removeMyReactionRecord(r,i),null!=(e=this._reactionsMap.get(o))&&e.reactionID){let e=this._reactionsMap.get(o);e.reactedByMyself=1===n,t.emitOuterEvent(s.OuterEvent.MESSAGE_REACTIONS_UPDATED,{name:s.OuterEvent.MESSAGE_REACTIONS_UPDATED,data:{messageID:r,reactionList:[e]}})}}_generatePartialUserInfo({userIDList:e,userProfileMap:t}){let s=[];return null!=e&&e.forEach(e=>{t.has(e)&&s.push(t.get(e))}),s}_generateMessageID(e){var{messageSequence:e,messageKey:t,messageIDMap:s}=e;return t?s.get(t):s.get(e)}_generateMessageKeyList(e,i){var t=this._core["constants"],s=e[0]["conversationType"];let r=[];return s===t.OuterConstant.CONV_C2C?r=e.map(e=>{var{clientSequence:e,random:t,time:s,ID:r}=e,e=e+`_${t}_`+s;return i.set(e,r),e}):s===t.OuterConstant.CONV_GROUP&&(r=e.map(e=>{var{ID:e,sequence:t}=e;return i.set(t,e),t})),r}},Jr=new class{init(e){var{helper:e,InnerEvent:{MESSAGE_PUSH:t},InnerEventSubType:{C2C_MESSAGE_READ_RECEIPT:s,GROUP_MESSAGE_READ_RECEIPT:r},notificationCenter:i}=this._core=e;e.registerApi({apiName:"sendMessageReadReceipt",context:this}),e.registerApi({apiName:"getMessageReadReceiptList",context:this}),e.registerApi({apiName:"getGroupMessageReadMemberList",context:this}),i.subscribeInnerEvent(t,s,this._handleC2CMessageReadReceipt,this),i.subscribeInnerEvent(t,r,this._handleGroupMessageReadReceipt,this)}sendMessageReadReceipt(e){return I(this,void 0,void 0,function*(){let{common:r,constants:t}=this._core,s=this._filterValidMessageSendByOther(e);if(0===s.length)throw new r.ChatError({code:t.ERROR_CODE.READ_RECEIPT_MSG_LIST_EMPTY});try{let e=s[0]["conversationType"];return e===t.OuterConstant.CONV_C2C?yield function(r){return I(this,void 0,void 0,function*(){var{common:e,constants:t}=E.core,t=r[0].conversationID.replace(t.OuterConstant.CONV_C2C,""),s=r.map(e=>{var{from:e,to:t,sequence:s,random:r,time:i,clientTime:n}=e;return{From_Account:e,To_Account:t,MsgSeq:s,MsgRandom:r,MsgTime:i,MsgClientTime:n}});return e.buildAndSendPacket({servcmd:"openim.c2c_msg_read_receipt",data:{Peer_Account:t,C2CMsgInfo:s}})})}(s):yield function(s){return I(this,void 0,void 0,function*(){var{common:e,constants:t}=E.core,t={GroupId:s[0].conversationID.replace(t.OuterConstant.CONV_GROUP,""),MsgSeqList:s.map(e=>({MsgSeq:e.sequence}))};return e.buildAndSendPacket({servcmd:"group_open_http_svc.group_msg_receipt",data:t})})}(s),{code:0,data:{}}}catch(e){let{errorCode:t,errorInfo:s}=e;throw new r.ChatError({code:t,message:s})}})}getMessageReadReceiptList(i){return I(this,void 0,void 0,function*(){let{common:r,constants:t}=this._core;try{let e=i[0]["conversationType"];if(e===t.OuterConstant.CONV_GROUP){let s=this._filterValidMessageSendByMe(i);if(0<(null==s?void 0:s.length)){let e=yield function(s){return I(this,void 0,void 0,function*(){var{common:e,constants:t}=E.core,t={GroupId:s[0].conversationID.replace(t.OuterConstant.CONV_GROUP,""),MsgSeqList:s.map(e=>({MsgSeq:e.sequence}))};return e.buildAndSendPacket({servcmd:"group_open_http_svc.get_group_msg_receipt",data:t})})}(s),t=(e||{})["GroupMsgReceiptList"];this._updateGroupMessagesReadReceiptInfo({messageList:i,readReceiptList:t})}}return{code:0,data:{messageList:i}}}catch(e){let{errorCode:t,errorInfo:s}=e;throw new r.ChatError({code:t,message:s})}})}getGroupMessageReadMemberList(n){return I(this,void 0,void 0,function*(){let{constants:e,common:r}=this._core,{message:t,filter:o=Vr.READ,cursor:s=""}=n,{conversationID:i,sequence:a,ID:u}=t,l=i.replace(e.OuterConstant.CONV_GROUP,""),c=100<=n.count?100:n.count;try{let n=yield function(n){return I(this,void 0,void 0,function*(){var{sequence:e,groupID:t,filter:s,cursor:r,count:i}=n,e={MsgSeq:e,GroupId:t,Filter:s,Cursor:r,Num:i};return E.core.common.buildAndSendPacket({servcmd:"group_open_http_svc.get_group_msg_receipt_detail",data:e})})}({groupID:l,sequence:a,filter:o,cursor:s,count:c});if(n){let{Cursor:e,IsFinish:t,UnreadList:s,ReadList:r}=n,i={cursor:e,isCompleted:1===t,messageID:u,unreadUserIDList:[],readUserIDList:[]};return o===Vr.READ?i.readUserIDList=r.map(e=>e.Read_Account):o===Vr.UNREAD&&(i.unreadUserIDList=s.map(e=>e.Unread_Account)),{code:0,data:i}}}catch(e){let{errorCode:t,errorInfo:s}=e;throw new r.ChatError({code:t,message:s})}})}_handleC2CMessageReadReceipt(e){let i=[],{constants:t,helper:s}=this._core,{C2cMsgInfo:n,PeerReadTime:o,Peer_Account:a}=e;if(!s.isEmpty(n)){let r=""+t.OuterConstant.CONV_C2C+a;null!=n&&n.forEach(e=>{var{TinyId:e,MsgClientTime:t,MsgRandom:s}=e,e=e+`-${t}-`+s,t=Hr({conversationID:r,messageID:e});t&&!t.readReceiptInfo.isPeerRead&&(t.readReceiptInfo.isPeerRead=!0,t.readReceiptInfo.timestamp=o,i.push({userID:a,messageID:e,isPeerRead:!0,timestamp:o}))}),this._emitReadReceiptEventIfNeed(i)}}_updateGroupMessagesReadReceiptInfo(e){let{messageList:t,readReceiptList:s}=e,r=new Map;t.forEach(e=>{r.set(e.sequence,e)}),null!=s&&s.forEach(e=>{var t,s;0===e.Code&&({MsgSeq:e,ReadNum:t,UnreadNum:s}=e,e=r.get(e))&&(e.readReceiptInfo.readCount=t,e.readReceiptInfo.unreadCount=s)})}_handleGroupMessageReadReceipt(e){let a=[],s=this._core["constants"],t=e["GroupTips"];t.forEach(e=>{let{MsgBody:{GroupMsgReceiptList:t},GroupInfo:{GroupId:n}}=e,o=""+s.OuterConstant.CONV_GROUP+n;null!=t&&t.forEach(e=>{var{TinyId:e,MsgClientTime:t,MsgRandom:s,ReadNum:r,UnreadNum:i}=e,e=e+`-${t}-`+s,t=Hr({conversationID:o,messageID:e}),s={groupID:n,messageID:e,readCount:0,unreadCount:0};t&&("number"==typeof r&&(t.readReceiptInfo.readCount=r,s.readCount=r),"number"==typeof i&&(t.readReceiptInfo.unreadCount=i,s.unreadCount=i),a.push(s))})}),this._emitReadReceiptEventIfNeed(a)}_emitReadReceiptEventIfNeed(e){var{notificationCenter:t,OuterEvent:s}=this._core;0<e.length&&t.emitOuterEvent(s.MESSAGE_READ_RECEIPT_RECEIVED,{name:s.MESSAGE_READ_RECEIPT_RECEIVED,data:e})}_filterValidMessageSendByOther(e){return this._filterNeedReadReceiptMessages(e).filter(e=>{e=e.from;return e!==this._core.common.getCurrentUserID()})}_filterValidMessageSendByMe(e){let s=this._core.constants["OuterConstant"];return this._filterNeedReadReceiptMessages(e).filter(e=>{var{from:e,status:t}=e;return e===this._core.common.getCurrentUserID()&&t===s.MessageStatus.SUCCESS})}_filterNeedReadReceiptMessages(e){return e.filter(e=>!0===e.needReadReceipt)}dispose(){var{InnerEvent:{MESSAGE_PUSH:e},InnerEventSubType:{C2C_MESSAGE_READ_RECEIPT:t,GROUP_MESSAGE_READ_RECEIPT:s},notificationCenter:r}=this._core;r.unSubscribeInnerEvent(e,t,this._handleC2CMessageReadReceipt,this),r.unSubscribeInnerEvent(e,s,this._handleGroupMessageReadReceipt,this)}};function Qr(o,a,u){return I(this,void 0,void 0,function*(){var{buildAndSendPacket:e}=E.core["common"],{from:t,to:s,clientSequence:r,random:i,time:n}=o;return e({servcmd:"openim_msg_ext_http_svc.set_key_values",data:{From_Account:t,To_Account:s,MsgKey:r+`_${i}_`+n,OperateType:u,ExtensionList:a}})})}function Xr(r,i,n){return I(this,void 0,void 0,function*(){var{buildAndSendPacket:e}=E.core["common"],{to:t,sequence:s}=r;return e({servcmd:"openim_msg_ext_http_svc.group_set_key_values",data:{GroupId:t,MsgSeq:s,OperateType:n,ExtensionList:i}})})}var Zr=new class{constructor(){this._messageExtensionsMap=new Map,this._extensionsLatestSequenceMap=new Map,this._completedFetchExtensions=new Set}init(e){var{notificationCenter:e,helper:{registerApi:t},InnerEvent:{MESSAGE_PUSH:s,LOGOUT:r},InnerEventSubType:{MESSAGE_EXTENSIONS_UPDATED:i}}=this._core=e;t({apiName:"setMessageExtensions",context:this}),t({apiName:"getMessageExtensions",context:this}),t({apiName:"deleteMessageExtensions",context:this}),e.subscribeInnerEvent(s,i,this._handleMessageExtensionsNotify,this),e.subscribeInnerEvent(r,this.reset,this)}setMessageExtensions(c,d){return I(this,void 0,void 0,function*(){this._validateMessageExtensionBusinessCapability("setMessageExtensions");let{constants:{OuterConstant:e},ssoLog:t}=this._core,{ID:s,conversationID:r,sequence:i,time:n,conversationType:o}=c,a=d;20<d.length&&(a=d.slice(0,20),t.warn("setMessageExtensions","the length of extensions cannot exceed 20"));var u=this._generateServerExtensions(c,a),l=`convID:${r} messageID:${s} sequence:${i} time:${n} count:`+a.length;try{let r;if(o===e.CONV_C2C?r=yield Qr(c,u,1):o===e.CONV_GROUP&&(r=yield Xr(c,u,1)),r){let{resultList:e,successCount:t,failureCount:s}=this._handleModifyMessageExtensions(c,r);return{code:0,data:{extensions:e},successLog:{message:l+` successCount:${t} failCount:`+s}}}return{code:0,data:{extensions:[]}}}catch(e){let t=e["errorCode"];throw new this._core.helper.ChatError({functionName:"setMessageExtensions",code:t,moreMessage:l})}})}getMessageExtensions(o){return I(this,void 0,void 0,function*(){let{isUndefined:s}=this._core["utils"],{conversationID:e,ID:r,sequence:t,time:i}=(this._validateMessageExtensionBusinessCapability("getMessageExtensions"),o),n=`convID:${e} messageID:${r} sequence:${t} time:`+i;try{let e,t=(this._completedFetchExtensions.has(r)&&(e=this._extensionsLatestSequenceMap.get(r)),yield this._fetchMessageExtensions(o,e));return s(e)&&1<t.length&&this._completedFetchExtensions.add(r),{code:0,data:{extensions:t},successLog:{message:n}}}catch(e){let{errorCode:t,errorInfo:s=""}=e||{};throw new this._core.common.ChatError({code:t,message:s,moreMessage:n})}})}deleteMessageExtensions(d,p){return I(this,void 0,void 0,function*(){this._validateMessageExtensionBusinessCapability("deleteMessageExtensions");let{utils:{isEmpty:e},constants:{OuterConstant:t}}=this._core,{conversationType:s,conversationID:r,sequence:i,ID:n,time:o}=d,a=3,u=[];e(p)||(a=2,null==p)||p.forEach(e=>{u.push({key:e,value:"",seq:0})});var l=`convID:${r} messageID:${n} sequence:${i} time:${o} operateType:`+a,c=this._generateServerExtensions(d,u);try{let r;if(s===t.CONV_C2C?r=yield Qr(d,c,a):s===t.CONV_GROUP&&(r=yield Xr(d,c,a)),r){let{resultList:e,successCount:t,failureCount:s}=this._handleModifyMessageExtensions(d,r);return{code:0,data:{extensions:e},successLog:{message:l+`successCount:${t} failCount:`+s}}}return{code:0,data:{extensions:[]}}}catch(e){let t=e["errorCode"];throw new this._core.helper.ChatError({functionName:"deleteMessageExtensions",code:t,moreMessage:l})}})}reset(){this._messageExtensionsMap.clear(),this._extensionsLatestSequenceMap.clear(),this._completedFetchExtensions.clear()}dispose(){this.reset();var{notificationCenter:e,InnerEvent:{MESSAGE_PUSH:t,LOGOUT:s},InnerEventSubType:{MESSAGE_EXTENSIONS_UPDATED:r}}=this._core;e.unSubscribeInnerEvent(t,r,this._handleMessageExtensionsNotify,this),e.subscribeInnerEvent(s,this.reset,this)}_handleModifyMessageExtensions(e,t){let s=e["ID"],r=t["Seq"],i=t.ExtensionList||[],n=[],o=0,a=0,u=[];return i.forEach(e=>{var{ErrorCode:e,Extension:t}=e,{Key:t,Value:s,Seq:r}=t;n.push({code:e,key:t,value:s}),0===e?o++:a++,u.push({key:t,value:s,seq:r})}),this._extensionsLatestSequenceMap.set(s,r),0<u.length&&this._updateLocalExtensions(e.ID,u),{resultList:n,successCount:o,failureCount:a}}_updateLocalExtensions(e,t){this._messageExtensionsMap.has(e)||this._messageExtensionsMap.set(e,new Map);let r=this._messageExtensionsMap.get(e);null!=t&&t.forEach(e=>{var{key:e,seq:t,value:s=""}=e;null!=r&&r.set(e,{value:s,seq:t})})}_fetchMessageExtensions(u,s){return I(this,void 0,void 0,function*(){let{constants:{OuterConstant:e},utils:{isEmpty:o}}=this._core;try{let n;var{conversationType:t,ID:a}=u;if(t===e.CONV_C2C?n=yield function(e,t){var s=E.core["common"]["buildAndSendPacket"],{from:e,to:r,clientSequence:i,random:n,time:o}=e;return s({servcmd:"openim_msg_ext_http_svc.get_key_values",data:{From_Account:e,To_Account:r,MsgKey:i+`_${n}_`+o,StartSeq:t}})}(u,s):t===e.CONV_GROUP&&(n=yield function(e,t){var s=E.core["common"]["buildAndSendPacket"],{to:e,sequence:r}=e;return s({servcmd:"openim_msg_ext_http_svc.group_get_key_values",data:{GroupId:e,MsgSeq:r,StartSeq:t}})}(u,s)),n){let{LatestSeq:e,ClearSeq:t,CompleteFlag:s}=n,r=(n.ExtensionList||[]).map(e=>({key:e.Key,value:e.Value,seq:e.Seq}));if(this._updateLocalExtensions(a,r),this._clearLocationExtensions(a,t),this._extensionsLatestSequenceMap.set(a,e),1!==s){let e=r[r.length-1].seq+1;return this._fetchMessageExtensions(u,e)}let i=[];if(this._messageExtensionsMap.has(a)){let e=this._messageExtensionsMap.get(a);null!=e&&e.forEach((e,t)=>{e=e.value;o(e)||i.push({key:t,value:e})})}return i}}catch(e){throw e}})}_clearLocationExtensions(e,r){if(!(r<=0)&&this._messageExtensionsMap.has(e)){let s=this._messageExtensionsMap.get(e);null!=s&&s.forEach((e,t)=>{e.seq<=r&&s.delete(t)})}}_generateServerExtensions(e,t){var s=e["ID"];if(this._messageExtensionsMap.has(s)){let r=this._messageExtensionsMap.get(s);return t.map(e=>{var{key:e,value:t}=e;let s=0;return{Key:e,Value:t,Seq:s=null!=r&&r.has(e)?null==(t=r.get(e))?void 0:t.seq:s}})}return t.map(e=>({Key:e.key,Value:e.value,Seq:0}))}_validateMessageExtensionBusinessCapability(e){var{helper:t,constants:s}=this._core;if(!t.checkBusinessCapabilityBits("MSG_EXT"))throw new t.ChatError({functionName:e,code:s.ERROR_CODE.NO_USE,replacement1:e})}_handleMessageExtensionsNotify(e){var{SetKVInfo:e,DeleteKVInfo:t,ClearKVInfo:s,MsgOptType:r,TinyId:i,MsgLastSeq:n,ExtensionC2cMsgInfo:o,ExtensionGroupMsgInfo:a}=(null==e?void 0:e.MsgExtensionNotify)||{},{MsgClientTime:o,MsgRandom:a}=o||a||{},i=i+`-${o}-`+a;this._extensionsLatestSequenceMap.set(i,n),1===r?this._handleMessageExtensionsUpdated({messageID:i,updateMessageExtensionsInfo:e}):2===r?this._handleMessageExtensionsDeleted({messageID:i,deleteMessageExtensionsInfo:t}):3===r&&this._handleMessageExtensionsCleared({messageID:i,clearMessageExtensionsInfo:s})}_handleMessageExtensionsUpdated(e){let{notificationCenter:t,OuterEvent:s}=this._core,{messageID:r,updateMessageExtensionsInfo:i=[]}=e,n=[];i.forEach(e=>{var{MsgKeyValue:e=[]}=e,e=e.map(e=>(n.push({key:e.Key,value:e.Value}),{key:e.Key,value:e.Value,seq:e.Seq}));this._updateLocalExtensions(r,e)}),t.emitOuterEvent(s.MESSAGE_EXTENSIONS_UPDATED,{name:s.MESSAGE_EXTENSIONS_UPDATED,data:{messageID:r,extensions:n}})}_handleMessageExtensionsDeleted(e){let{notificationCenter:t,OuterEvent:s}=this._core,{messageID:r,deleteMessageExtensionsInfo:i=[]}=e,n=[];i.forEach(e=>{var{MsgKeyValue:e=[]}=e,e=e.map(e=>(n.push(e.Key),{key:e.Key,seq:e.Seq}));this._updateLocalExtensions(r,e)}),t.emitOuterEvent(s.MESSAGE_EXTENSIONS_DELETED,{name:s.MESSAGE_EXTENSIONS_DELETED,data:{messageID:r,keyList:n}})}_handleMessageExtensionsCleared(e){let{notificationCenter:t,OuterEvent:{MESSAGE_EXTENSIONS_DELETED:s},utils:{isEmpty:r}}=this._core,{messageID:i,clearMessageExtensionsInfo:n=[]}=e,o=[];n.forEach(e=>{let s=e["ClearMsgSeq"];this._messageExtensionsMap.has(i)&&(this._messageExtensionsMap.get(i)||[]).forEach((e,t)=>{e.seq<=s&&!r(e.value)&&o.push(t)}),this._clearLocationExtensions(i,s)}),t.emitOuterEvent(s,{name:s,data:{messageID:i,keyList:o}})}};let ei={key:"message",required:!0,rules:["object"],allowEmpty:!1,customValidator:e=>{var{OuterConstant:t}=E.core["constants"];return e.status!==t.MessageStatus.SUCCESS?"message is not success":!0===e.isSupportExtension||"message is not support extension"}},ti={setMessageExtensions:[ei,{key:"extensions",required:!0,rules:["array"],allowEmpty:!1}],getMessageExtensions:[ei],deleteMessageExtensions:[ei]},si=Object.assign(Object.assign(Object.assign(Object.assign({deleteMessage:[{required:!0,rules:["array"],allowEmpty:!1}],revokeMessage:[{required:!0,rules:["object"],allowEmpty:!1}],resendMessage:[{key:"message",required:!0,rules:["object"],allowEmpty:!1},{key:"options",required:!1,rules:["object"],allowEmpty:!1}],getMessageList:{conversationID:{required:!0,rules:["string"],allowEmpty:!1},nextReqMessageID:{required:!1,rules:["string"],allowEmpty:!0},count:{required:!1,rules:["number"],allowEmpty:!0}},getMessageListHopping:{conversationID:{required:!0,rules:["string"],allowEmpty:!1},sequence:{required:!1,rules:["number"],allowEmpty:!0},direction:{required:!1,rules:["number"],allowEmpty:!0},count:{required:!1,rules:["number"],allowEmpty:!0}},createTextAtMessage:{to:{required:!0,rules:["string"],allowEmpty:!1},conversationType:{required:!0,rules:["string"],allowEmpty:!1,customValidator:e=>"GROUP"===e||"conversationType should be GROUP."},payload:{required:!0,rules:["object"],allowEmpty:!1,customValidator:e=>{var t="string"==typeof(null==e?void 0:e.text)&&("string"!=typeof e.text||0!==(null==(t=null==e?void 0:e.text)?void 0:t.length))||"payload.text is invalid.";return!0!==t?t:!(null!=e&&e.atUserList&&!Array.isArray(e.atUserList))||"atUserList should be an array or undefind."}}},findMessage:[{required:!0,rules:["string"],allowEmpty:!1}],translateText:{sourceTextList:{required:!0,rules:["array"],allowEmpty:!1},sourceLanguage:{required:!0,rules:["string"],allowEmpty:!1},targetLanguage:{required:!0,rules:["string"],allowEmpty:!1}},createForwardMessage:{to:{required:!0,rules:["string"],allowEmpty:!1},conversationType:{required:!0,rules:["string"],allowEmpty:!1,customValidator:e=>!(!e.startsWith("C2C")&&!e.startsWith("GROUP"))||"conversationType is invalid."},payload:{required:!0,rules:["object"],allowEmpty:!1}},createLocationMessage:{to:{required:!0,rules:["string"],allowEmpty:!1},conversationType:{required:!0,rules:["string"],allowEmpty:!1},payload:{required:!0,rules:["object"],allowEmpty:!1,customValidator:e=>{var{isString:t,isNumber:s}=E.core["utils"];return t(null==e?void 0:e.description)?s(null==e?void 0:e.longitude)?!!s(null==e?void 0:e.latitude)||"payload.latitude must be a number.":"payload.longitude must be a number.":"payload.description must be a string."}}}},{addMessageReaction:[{key:"message",required:!0,rules:["object"],allowEmpty:!1},{key:"reactionID",required:!0,rules:["string"],allowEmpty:!1}],removeMessageReaction:[{key:"message",required:!0,rules:["object"],allowEmpty:!1},{key:"reactionID",required:!0,rules:["string"],allowEmpty:!1}],getMessageReactions:{messageList:{required:!0,rules:["array"],allowEmpty:!1},maxUserCountPerReaction:{required:!1,rules:["number"],allowEmpty:!0,customValidator:e=>"number"!=typeof e?"maxUserCountPerReaction is invalid.":!(e<0||10<e)||"maxUserCountPerReaction should between [0, 10]."}},getAllUserListOfMessageReaction:{message:{required:!0,rules:["object"],allowEmpty:!1,customValidator:e=>"success"===e.status||"message is invalid."},reactionID:{required:!0,rules:["string"],allowEmpty:!1},nextSeq:{required:!1,rules:["number"],allowEmpty:!0},count:{required:!1,rules:["number"],allowEmpty:!0}}}),{sendMessageReadReceipt:[{required:!0,rules:["array"],allowEmpty:!1}],getMessageReadReceiptList:[{required:!0,rules:["array"],allowEmpty:!1}],getGroupMessageReadMemberList:{message:{required:!0,rules:["object"],allowEmpty:!1},filter:{required:!1,rules:["number"],allowEmpty:!0},count:{required:!1,rules:["number"],allowEmpty:!0},cursor:{required:!1,rules:["string"],allowEmpty:!0}}}),ti),{pinGroupMessage:{groupID:{required:!0,rules:["string"],allowEmpty:!1},message:{required:!0,rules:["object"],allowEmpty:!1},isPinned:{required:!0,rules:["boolean"],allowEmpty:!1}},getPinnedGroupMessageList:[{key:"groupID",required:!0,rules:["string"],allowEmpty:!1}]}),ri=Object.assign(Object.assign(Object.assign(Object.assign({deleteMessage:!0,revokeMessage:!0,resendMessage:!0,getMessageList:!0,getMessageListHopping:!0,createTextAtMessage:!0,findMessage:!0,translateText:!0,createForwardMessage:!0,createLocationMessage:!0},{addMessageReaction:!0,removeMessageReaction:!0,getMessageReactions:!0,getAllUserListOfMessageReaction:!0}),{sendMessageReadReceipt:!0,getMessageReadReceiptList:!0,getGroupMessageReadMemberList:!0}),{setMessageExtensions:!0,getMessageExtensions:!0,deleteMessageExtensions:!0}),{pinGroupMessage:!0,getPinnedGroupMessageList:!0});class ii{constructor(e){this._core=e}deleteMessage(s){return I(this,void 0,void 0,function*(){var{to:e,messageIdentifiers:t}=s,e={From_Account:this._core.common.getCurrentUserID(),To_Account:e,MsgKeyList:t};return this._core.common.buildAndSendPacket({servcmd:"openim.delete_c2c_msg_ramble",data:e})})}revokeMessage(n){return I(this,void 0,void 0,function*(){var{to:e,from:t,sequence:s,time:r,random:i}=n;return this._core.common.buildAndSendPacket({servcmd:"openim.msgwithdraw",data:{MsgInfo:{From_Account:t,To_Account:e,MsgSeq:s,MsgRandom:i,MsgTimeStamp:r}}})})}}class ni{constructor(e){this._core=e}deleteMessage(s){return I(this,void 0,void 0,function*(){var{to:e,messageIdentifiers:t}=s,e={GroupId:e,Deleter_Account:this._core.common.getCurrentUserID(),Seqs:t};return this._core.common.buildAndSendPacket({servcmd:"group_open_http_svc.delete_group_ramble_msg_by_seq",data:e})})}revokeMessage(s){return I(this,void 0,void 0,function*(){var{to:e,sequence:t}=s;return this._core.common.buildAndSendPacket({servcmd:"group_open_http_svc.group_msg_recall",data:{GroupId:e,MsgSeqList:[{MsgSeq:t}]}})})}}class oi{constructor(e){this._core=e}generateRevokeMessage(e){var{conversationID:e,sequence:t,random:s,tinyID:r,clientTime:i,revokeReason:n,revoker:o}=e;let a={};var u=this._core.message["messageDataHandler"];return(a=u.revokeMessage({conversationID:e,sequence:t,random:s,revoker:o}))||(a={conversationID:e,sequence:t},r&&i&&s&&(a.ID=r+`-${i}-`+s)),a.revoker=o,a.revokeReason=n,a.revokerInfo={userID:o,nick:"",avatar:""},a}updateRevokerInfo(t){return I(this,void 0,void 0,function*(){var e=t.map(e=>e.revoker);try{let s=yield this._fetchUserInfos(e);s&&t.forEach(e=>{var t=e["revoker"];s[t]&&(e.revokerInfo.nick=s[t].nick||"",e.revokerInfo.avatar=s[t].avatar||"",e.revokerInfo.userID=t)})}catch(e){console.debug(e)}})}_fetchUserInfos(t){return I(this,void 0,void 0,function*(){var e=yield null==(e=this._core.user.userProfile)?void 0:e.getUserProfile({userIDList:t});return null!=e&&e.data?null==(e=e.data)?void 0:e.reduce((e,{userID:t,nick:s,avatar:r})=>(e[t]={nick:s||"",avatar:r||""},e),{}):null})}}var ai=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 ii(e),this._messageHelper=new oi(e);e=e.helper;e.registerApi({apiName:"deleteMessage",context:this}),e.registerApi({apiName:"revokeMessage",context:this}),e.registerApi({apiName:"resendMessage",context:this}),e.registerApi({apiName:"findMessage",context:this})}deleteMessage(t){return I(this,void 0,void 0,function*(){let u=[],l=[],{conversationID:c,conversationType:d}=t[0],e=c.replace(d,"");if("@TIM#SYSTEM"===d)throw new this._core.helper.ChatError({code:2116});if(t.forEach(e=>{var{conversationID:t,conversationType:s,status:r,_onlineOnlyFlag:i,sequence:n,random:o,time:a}=e||{};if("success"===r&&t===c&&s===d){if(!i){let e="C2C"===s?n+`_${o}_`+a:String(n);u.push(e)}l.push(e)}}),0===u.length)return this._handleDeleteMessageSuccess(l),{code:0,data:{messageList:l}};30<u.length&&(u=u.slice(0,30),l=l.slice(0,30));try{return"C2C"===d?yield this._c2cMessageAction.deleteMessage({to:e,messageIdentifiers:u}):yield this._groupMessageAction.deleteMessage({to:e,messageIdentifiers:u}),this._handleDeleteMessageSuccess(l),{code:0,data:{messageList:l}}}catch(e){let t=e["errorCode"];throw new this._core.helper.ChatError({functionName:"deleteMessage",code:t})}})}revokeMessage(l){return I(this,void 0,void 0,function*(){var s;this._core.ssoLog.createSSOLogData({method:"revokeMessage"});let{conversationType:e,isRevoked:t,ID:r,type:i,from:n,to:o}=l;var a,u=`type:${i} from:${n} to:${o} ID:`+r;if("@TIM#SYSTEM"===e)throw new this._core.helper.ChatError({message:"system message cannot be revoked"});if(t)throw new this._core.helper.ChatError({message:"message has been revoked",moreMessage:u});try{if(a="C2C"===e?yield this._c2cMessageAction.revokeMessage(l):yield this._groupMessageAction.revokeMessage(l)){let e=a["RecallRetList"],t=(null==(s=null==e?void 0:e[0])?void 0:s.RetCode)||0;if(0!==t)throw new this._core.helper.ChatError({code:t,moreMessage:u});return yield this._handleRevokeMessageSuccess(l),{code:0,data:{message:l},successLog:{message:u}}}}catch(e){let t=e["errorCode"];throw new this._core.helper.ChatError({functionName:"revokeMessage",code:t,moreMessage:u})}})}resendMessage(t,s){return I(this,void 0,void 0,function*(){var e;return t.isResend=!0,t.status="unSend",null==(e=null==(e=this._core)?void 0:e.apiMap)?void 0:e.sendMessage(t,s)})}findMessage(e){return this._core.message.messageDataHandler.findMessage(e)}_handleDeleteMessageSuccess(i){if(0!==i.length){let{message:{messageDataHandler:s},common:{isTopic:e},notificationCenter:t,InnerEvent:r}=this._core;i.forEach(t=>{t.isDeleted=!0;var e=s.getLocalMessageList(t.conversationID);null!=e&&e.forEach(e=>{e.ID===t.ID&&(e.isDeleted=!0)})});var{conversationID:i=""}=i[0];e(i)?t.emitInnerEvent(r.TOPIC_MESSAGE_DELETED,i):t.emitInnerEvent(r.MESSAGE_DELETED,i)}}_handleRevokeMessageSuccess(i){return I(this,void 0,void 0,function*(){var e=null==(e=this._core.store.get("login"))?void 0:e.userId,{conversationID:t,sequence:s,random:r}=i;this._core.message.messageDataHandler.revokeMessage({conversationID:t,sequence:s,random:r,revoker:e}),yield this._messageHelper.updateRevokerInfo([i])})}};class ui{static parseServerPushElement(e){var{MsgContent:e={}}=e,{Index:e,Data:t}=e;return new ui({index:e,data:t})}constructor(e){this.type=Or.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 li{static parseServerPushElement(e){var{MsgContent:e={}}=e,{Desc:e,Longitude:t,Latitude:s}=e;return new li({description:e,longitude:t,latitude:s})}constructor(e){this.type=Or.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 ci=new class{init(e){(this._core=e).message.messageFactory.registerElementClass(Or.MSG_FACE,ui),e.message.messageFactory.registerElementClass(Or.MSG_LOCATION,li),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 ui({index:t,data:s}),s=this._core.common.getCurrentUserID(),(e=this._core.message.messageFactory.createMessage(Object.assign(Object.assign({},e),{from:s}))).setElement(t),e):null}createTextAtMessage(e){let r=((null==e?void 0:e.payload)||{})["atUserList"],i=this._core.apiMap.createTextMessage(e),n=this._core["OuterConstant"];if(!i)return null;if(Array.isArray(r)){let t=[],s=[];r.forEach(e=>{e!==n.MSG_AT_ALL?(t.push({GroupAtAllFlag:0,GroupAt_Account:e}),s.push(e)):(t.push({GroupAtAllFlag:1}),s.push(n.MSG_AT_ALL))}),i._groupAtInfoList=t,i.atUserList=s}return i}createForwardMessage(e){var{helper:t,OuterConstant:s}=this._core,{to:e,conversationType:r,priority:i,payload:n,needReadReceipt:o,receiverList:a,cloudCustomData:u="",isSupportExtension:l=!1}=e;if(!Array.isArray(n._elements))throw new t.ChatError({functionName:"createForwardMessage",code:2454});if(n.type===s.MSG_GRP_TIP)throw new t.ChatError({functionName:"createForwardMessage",code:2453});s=this._core.common.getCurrentUserID(),t=this._core.message.messageFactory.createMessage({to:e,from:s,conversationType:r,isPlaceMessage:0,priority:i,payload:n,needReadReceipt:o,isSupportExtension:l,cloudCustomData:u,receiverList:a});return t.setRelayFlag(!0),t.setElement(n._elements[0]),t}createLocationMessage(e){var t,s,r;return e?({description:t,longitude:s,latitude:r}=(null==e?void 0:e.payload)||{},t=new li({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 di=class{init(e){this._messageHelper=new oi(e);var{notificationCenter:e,InnerEvent:{MESSAGE_PUSH:t},InnerEventSubType:{C2C_REVOKED_MESSAGE:s},helper:{registerWorkflowStep:r},constants:{WORKFLOW_NAME:i,WORKFLOW_STEP:n}}=this._core=e;e.subscribeInnerEvent(t,s,this._handleC2CNotifyMessage,this),r(i.SYNC_SERVER_INFO_AFTER_RE_ONLINE,n.HANDLE_C2C_REVOKED_MESSAGE_FROM_SYNC_UNREAD,this._handleC2CRevokeMessagesFromUnreadMessageSync,this)}_handleC2CNotifyMessage(e){e=e.C2cNotifyMsgArray;null!=e&&e.forEach(e=>{Object.keys(e).includes("WithdrawC2cMsgNotify")&&this._handleC2CRevokeMessage(e)})}_handleC2CRevokeMessage(t){return I(this,void 0,void 0,function*(){try{var{C2cWithdrawInfoArray:e}=t["WithdrawC2cMsgNotify"];yield this._parseAndEmitC2CRevokedMessages(e)}catch(e){console.debug(e)}})}_parseAndEmitC2CRevokedMessages(s){return I(this,void 0,void 0,function*(){let a=[],{notificationCenter:e,OuterEvent:t,common:{getCurrentUserID:u}}=this._core;s.forEach(e=>{var{MsgRand:t,MsgSeq:s,To_Account:r,From_Account:i,RevokerInfo:{Revoker_Account:n,Revoke_Reason:o}}=e,r=u()===i?"C2C"+r:"C2C"+i,e=(null==(i=null==e?void 0:e.RevokerInfo)?void 0:i.Reason)||o,i=this._messageHelper.generateRevokeMessage({conversationID:r,sequence:s,random:t,revoker:n,revokeReason:e});a.push(i)}),0<a.length&&(yield this._messageHelper.updateRevokerInfo(a),e.emitOuterEvent(t.MESSAGE_REVOKED,{name:t.MESSAGE_REVOKED,data:a}))})}_handleC2CRevokeMessagesFromUnreadMessageSync(t){return I(this,void 0,void 0,function*(){var e=t.result["revokedMessageList"];yield this._parseAndEmitC2CRevokedMessages(e)})}dispose(){var{notificationCenter:e,InnerEvent:{MESSAGE_PUSH:t},InnerEventSubType:{C2C_REVOKED_MESSAGE:s}}=this._core;e.unSubscribeInnerEvent(t,s,this._handleC2CNotifyMessage,this)}},pi=class{init(e){this._messageHelper=new oi(e);var{notificationCenter:e,InnerEvent:{MESSAGE_PUSH:t},InnerEventSubType:{GROUP_MESSAGE_REVOKED:s}}=this._core=e;e.subscribeInnerEvent(t,s,this._handleGroupNotifyMessage,this)}_handleGroupNotifyMessage(e){e=e.GroupTips;null!=e&&e.forEach(e=>{var t;Array.isArray(null==(t=null==e?void 0:e.MsgBody)?void 0:t.GroupWithdrawInfoArray)&&this._handleGroupRevokeMessage(e)})}_handleGroupRevokeMessage(n){return I(this,void 0,void 0,function*(){try{let{RevokerInfo:u,MsgBody:{GroupWithdrawInfoArray:e},GroupInfo:l}=n,c=[],d=[],{notificationCenter:t,OuterEvent:s,utils:{isEmpty:r},common:{isCommunity:i}}=this._core,p=!1;l&&(p=i({groupID:l.GroupId})||!r(l.TopicId)),e.forEach(e=>{var{Random:e,MsgSeq:t,GroupId:s,MsgClientTime:r,TinyId:i,TopicId:n,RevokerInfo:{Revoker_Account:o=(null==u?void 0:u.Revoker_Account)||"",Reason:a=(null==u?void 0:u.Reason)||""}}=e,n=this._messageHelper.generateRevokeMessage({conversationID:n?"GROUP"+n:"GROUP"+s,sequence:t,random:e,tinyID:i,clientTime:r,revoker:o,revokeReason:a});(p?(n.revokerInfo.nick=l.From_AccountNick,n.revokerInfo.avatar=l.From_AccountHeadurl,c):d).push(n)}),0<d.length&&(yield this._messageHelper.updateRevokerInfo(d),c.push(...d)),0!==c.length&&t.emitOuterEvent(s.MESSAGE_REVOKED,{name:s.MESSAGE_REVOKED,data:c})}catch(e){console.debug(e)}})}dispose(){var{notificationCenter:e,InnerEvent:{MESSAGE_PUSH:t},InnerEventSubType:{GROUP_MESSAGE_REVOKED:s}}=this._core;e.unSubscribeInnerEvent(t,s,this._handleGroupNotifyMessage,this)}};var hi=new class{constructor(){this._c2cMessageReceiver=new di,this._groupMessageReceiver=new pi}init(e){this._c2cMessageReceiver.init(e),this._groupMessageReceiver.init(e)}dispose(){this._c2cMessageReceiver.dispose(),this._groupMessageReceiver.dispose()}};class gi{constructor(e){var t=(this._core=e)["constants"];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){let{recoverRevokeNoticeGroupIDList:t=[]}=e.result,r=this._filterValidGroupIDList(t);0!==r.length&&(e=Math.min(Math.ceil(r.length/10),5),Promise.all(Array.from({length:e},(e,t)=>{var t=10*t,s=Math.min(10+t,r.length);return this._fetchGroupRevokeNotice(r.slice(t,s))})).catch(e=>console.error(e)))}_fetchGroupRevokeNotice(s){return I(this,void 0,void 0,function*(){var e;try{var t=yield function(n){return I(this,void 0,void 0,function*(){let{appStore:e,constants:{OuterConstant:s},common:r}=E.core,i=e.groupStore.getGroupMap(),t={NotifyReqList:n.map(e=>{var t=i.get(e);return{NotifyType:1,Limit:20,Type:r.isCommunity({type:t.type,groupID:e})?s.GRP_COMMUNITY:void 0,GroupId:e,BeginTime:(null==t?void 0:t._lastRevokedTime)||0,EndTime:1e3*E.core.common.timeManager.getServerTimeMs()}})||[]};return r.buildAndSendPacket({servcmd:"group_open_http_svc.batch_get_group_notify",data:t})})}(s);if(t){let s=[];null!=(e=null==t?void 0:t.NotifyRspList)&&e.forEach(e=>{var{GroupId:e,NotifyMsgList:t}=e,e=this._parseServerRevokeMessageList({groupID:e,serverRevokeMessageList:t});s.push(...e)}),0!==s.length&&(yield this._emitMessageRevokedEvent(s))}}catch(e){console.error(e)}})}_parseServerRevokeMessageList(e){let{serverRevokeMessageList:t,groupID:o}=e,a=[];return null!=t&&t.forEach(e=>{var{ClientTime:e,MsgSeq:t,Random:s,RevokerInfo:{Revoker_Account:r="",Reason:i=""}}=e,n="GROUP"+o,n=this._messageHelper.generateRevokeMessage({conversationID:n,sequence:t,random:s,clientTime:e,revoker:r,revokeReason:i});a.push(n)}),a}_filterValidGroupIDList(e){let{OuterConstant:t}=this._core["constants"],s=this._core.appStore.groupStore.getGroupMap();return(null==e?void 0:e.filter(e=>{return!(!s.has(e)||(null==(e=s.get(e))?void 0:e.type)===t.GRP_AVCHATROOM||null!=e&&e.isSupportTopic)}))||[]}_emitMessageRevokedEvent(s){return I(this,void 0,void 0,function*(){var{notificationCenter:e,OuterEvent:t}=this._core;yield this._messageHelper.updateRevokerInfo(s),e.emitOuterEvent(t.MESSAGE_REVOKED,{name:t.MESSAGE_REVOKED,data:s})})}}class _i{constructor(e){this._historyMessageListFetchAnchors=new Map,this._core=e,this._messageHelper=new oi(e)}getRoamingMessagesByAnchor(g){return I(this,void 0,void 0,function*(){var i;try{var{conversationID:n,count:e,messageID:r,time:o,direction:a}=g;let t=o,s="";if(!o){let e=r?this._core.message.messageDataHandler.findMessage(r):null;if(t=(null==e?void 0:e.time)||0,r&&this._historyMessageListFetchAnchors.has(n)){let e=this._historyMessageListFetchAnchors.get(n);t=e.lastMessageTime,s=e.messageKey}}var u=n.replace(Br,""),l=yield function(n){return I(this,void 0,void 0,function*(){var{peerAccount:e,count:t,lastMessageTime:s,messageKey:r,direction:i}=n,e={Peer_Account:e,MaxCnt:t,WithRecalledMsg:1,LastMsgTime:s,MsgKey:r,GetDirection:i};return E.core.common.buildAndSendPacket({servcmd:"openim.getroammsg",data:e})})}({count:e,lastMessageTime:t,messageKey:s,peerAccount:u,direction:a});if(l){let{MsgList:t=[],Complete:e,MsgKey:s,LastMsgTime:r}=l;this._historyMessageListFetchAnchors.set(n,{messageKey:s,lastMessageTime:r});var c=[];for(let e=0;e<t.length;e++){var d=t[e],p=this._parseMessage(d);c.push(p)}var h=this._core.message.messageHelper.filterValidMessages(c);return{messageList:h,nextReqMessageIDFromServer:null==(i=h[0])?void 0:i.ID,lastMessageTime:r,hasNoMoreHistoryMessage:1===e}}}catch(e){throw new this._core.helper.ChatError({code:null==e?void 0:e.code})}})}clearHistoryMessageListFetchAnchors(e){this._historyMessageListFetchAnchors.delete(e)}reset(){this._historyMessageListFetchAnchors.clear()}_parseMessage(e){Br;var e=this._core.message.messageHelper.parseServerPushMessage(e),t=this._core.message.messageFactory.createMessage(Object.assign(Object.assign({},e),{conversationType:"C2C",flow:"in"}));return t.setElement(e.elements),t}}var mi=new class{constructor(){this._clearedConversations=new Set,this._fetchedCompleteConversations=new Set}init(e){this._core=e,this._groupMessageHistory=new gi(e),this._c2cMessageHistory=new _i(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 I(this,void 0,void 0,function*(){try{var{conversationID:t,nextReqMessageID:s}=e;if("@TIM#SYSTEM"===t)return{code:0,data:{messageList:[],isCompleted:!1,nextMessageSeq:""}};var r=this._getAvailableLocalMessagesCount({conversationID:t,nextReqMessageID:s});if(this._needFetchHistoryMessageList({conversationID:t,availableLocalMessagesCount:r,targetCount:20})){let e=null;if(t.startsWith(jr)?e=yield this._groupMessageHistory.getRoamingMessagesByAnchor({conversationID:t,sequence:Number(s),count:20,direction:Dr.FORWARD}):t.startsWith(Br)&&(e=yield this._c2cMessageHistory.getRoamingMessagesByAnchor({conversationID:t,messageID:s,count:20,direction:Dr.FORWARD})),e){var{nextReqMessageIDFromServer:i,hasNoMoreHistoryMessage:n,messageList:o}=e,a=this._core.message.messageDataHandler.prependLocalMessageList({messageList:o,conversationID:t}),u=t,{appStore:l,message:c,OuterConstant:d}=E.core,l=l.conversationStore.getConversation(u),p=c.messageDataHandler.getLocalMessageList(u);if(l&&0!==p.length&&u!==d.CONV_SYSTEM){var h=[];for(let e=0;e<p.length;e++)"in"!==p[e].flow?"out"!==p[e].flow||p[e].isRead||p[e].setIsRead(!0):h.push(p[e]);let t=0;if(l.type===d.CONV_C2C){let e=h.slice(-l.unreadCount).filter(e=>e.isRevoked).length;t=h.length-l.unreadCount-e}else t=h.length-l.unreadCount;for(let e=0;e<t&&!h[e].isRead;e++)h[e].setIsRead(!0)}yield Wr(t),t.startsWith(Br)&&(yield Kr({messageList:o,conversationID:t}));var g=this._core.message.messageDataHandler.getLocalMessageList(t).slice(0,a.length+r),_=g.filter(e=>e.isRevoked),m=(yield this._messageHelper.updateRevokerInfo(_),n&&this._fetchedCompleteConversations.add(t),{nextReqMessageID:n?"":String(i),messageList:g,isCompleted:n}),v=g.map(e=>e.sequence);return{code:0,data:m,successLog:{message:`conversationID: ${t} nextReqMessageID: ${s} availableLocalMessagesCount: ${r} sequenceList: `+JSON.stringify(v)}}}return{code:0,data:{messageList:[],isCompleted:!1,nextReqMessageID:""}}}return{code:0,data:yield this._getMessageListFromMemory({conversationID:t,nextReqMessageID:s,count:20}),successLog:{message:`conversationID: ${t} nextReqMessageID: ${s} availableLocalMessagesCount: ${r}}`}}}catch(e){throw new this._core.helper.ChatError({code:null==e?void 0:e.code})}})}getMessageListHopping(r){return I(this,void 0,void 0,function*(){var n,o;let{conversationID:e,sequence:a,time:t,direction:u=Dr.FORWARD}=r,l=this._core.helper["isEmpty"];if(![Dr.BACKWARD,Dr.FORWARD].includes(u))throw new this._core.helper.ChatError({message:"direction must be 0 or 1"});let{count:s=20}=r,c=(s=20<s?20:s,null);if(e.startsWith(jr)){if(c=yield this._groupMessageHistory.getRoamingMessagesByAnchor({conversationID:e,sequence:a,count:s,direction:u})){let{nextReqMessageIDFromServer:t,hasNoMoreHistoryMessage:s,messageList:r,invisibleSequenceList:i}=c;if(this._core.message.messageDataHandler.storeSparseMessageList(r),u===Dr.FORWARD){let e=s&&t<1;return{code:0,data:{messageList:r,isCompleted:e,nextMessageSeq:e?"":t}}}if(u!==Dr.BACKWARD)return{code:0,data:c};{if(l(r)&&l(i))return{code:0,data:{messageList:[],isCompleted:!0,nextMessageSeq:""}};let e=(null==(n=null==r?void 0:r[r.length-1])?void 0:n.sequence)||0,t=(null==(o=null==i?void 0:i[i.length-1])?void 0:o.sequence)||0;return{code:0,data:{messageList:r.filter(e=>e.sequence>=a),isCompleted:!s,nextMessageSeq:s?Math.max(e,t)+1:""}}}}}else if(e.startsWith(Br)&&(c=yield this._c2cMessageHistory.getRoamingMessagesByAnchor({conversationID:e,count:s+1,time:t,direction:u}))){let{messageList:e,lastMessageTime:t,hasNoMoreHistoryMessage:s}=c;return s||(u===Dr.FORWARD?e.shift():e.pop()),this._core.message.messageDataHandler.storeSparseMessageList(e),{code:0,data:{messageList:e,isCompleted:s,nextMessageTime:s?"":t}}}})}clearHistoryMessage(d){return I(this,void 0,void 0,function*(){let t,{appStore:e,common:{ChatError:s,getCurrentUserID:r},OuterConstant:{CONV_C2C:i,CONV_GROUP:n},message:o,apiMap:a}=this._core,u=e.conversationStore.getConversation(d);if(!u)throw new s({code:2500});var l={fromAccount:r()},c=u["type"];c===i?(l.type=1,l.toAccount=d.replace(i,"")):c===n&&(l.type=2,l.toGroupID=d.replace(n,""));try{yield null==(t=null==a?void 0:a.setMessageRead)?void 0:t.call(a,{conversationID:d});let e=yield function(i){return I(this,void 0,void 0,function*(){var{fromAccount:e,type:t,toAccount:s,toGroupID:r}=i,e={From_Account:e,Type:t,To_Account:s,ToGroupid:r};return E.core.common.buildAndSendPacket({servcmd:"recentcontact.clear_msg",data:e})})}(l);return e&&(o.messageDataHandler.deleteConversationMessageList(d),this._clearedConversations.add(d),this._fetchedCompleteConversations.delete(d),this._c2cMessageHistory.clearHistoryMessageListFetchAnchors(d),this._updateConversationLastMessage(d)),{code:0,data:{conversationID:d},successLog:{message:"convID:"+d}}}catch(t){let e=t["errorCode"];throw new this._core.helper.ChatError({functionName:"clearHistoryMessage",code:e,moreMessage:"convID:"+d})}})}_updateConversationLastMessage(e){var t=this._core["appStore"];t.conversationStore.updateConversation(e,{lastMessage:this._generateLastMessage()},{needSort:!0})}_getAvailableLocalMessagesCount({conversationID:e,nextReqMessageID:t}){var s=this._core.message.messageDataHandler.getLocalMessageList(e),r=s["length"];if(!t)return r;let i=-1;return null!=e&&e.startsWith(Br)?i=s.findIndex(e=>e.ID===t):null!=e&&e.startsWith(jr)&&(i=s.findIndex(e=>t.includes("-")?e.ID===t:String(e.sequence)===t)),-1===i?0:i}_needFetchHistoryMessageList({conversationID:e,availableLocalMessagesCount:t,targetCount:s}){return!!this._clearedConversations.has(e)||t<s&&!this._fetchedCompleteConversations.has(e)}_getMessageListFromMemory(e){return I(this,arguments,void 0,function*({conversationID:t,nextReqMessageID:s,count:e}){var r=this._core.message.messageDataHandler.getLocalMessageList(t),i=r.length;let n=i,o={isCompleted:!1,nextReqMessageID:"",messageList:[]},a=0,u=i;return s?(u=r.findIndex(e=>t.startsWith(Br)?e.ID===s:String(e.sequence)===s),a=u>e?u-e:0,n=u):a=e<i?i-e:0,o.nextReqMessageID=0===a?"":this._generateNextReqMessageID({conversationID:t,targetIndex:a}),o.messageList=r.slice(a,u),o.isCompleted=n<=e,t.startsWith(Br)&&(yield Wr(t),yield Kr({messageList:o.messageList,conversationID:t})),o})}_generateNextReqMessageID({conversationID:e,targetIndex:t}){var s=this._core.message.messageDataHandler.getLocalMessageList(e);return e.startsWith("C2C")?s[t].ID:String(s[t].sequence)}_generateLastMessage(){return{lastTime:0,lastSequence:0,fromAccount:"",messageForShow:"",payload:null,type:"",isRevoked:!1,cloudCustomData:"",onlineOnlyFlag:!1,nick:"",nameCard:"",version:0,isPeerRead:!1,revoker:null}}reset(){this._clearedConversations.clear(),this._fetchedCompleteConversations.clear(),this._c2cMessageHistory.reset()}dispose(){this.reset()}},vi=new class{constructor(){this._core=null}init(e){e=(this._core=e).helper;e.registerApi({apiName:"translateText",context:this})}translateText(i){return I(this,void 0,void 0,function*(){try{var{sourceLanguage:t,sourceTextList:s,targetLanguage:e}=i,r=yield function(n,o){return I(this,void 0,void 0,function*(){var{sourceTextList:s,sourceLanguage:e,targetLanguage:t}=n,{store:r,common:i}=o,t={SourceText:s,Source:e,Target:t,FromAccount:null==(s=r.get("login"))?void 0:s.tinyID,SDKAppID:null==(e=r.get("instance"))?void 0:e.sdkAppId},s=yield i.buildAndSendPacket({servcmd:"im_open_translate.ws_batch_trans_text",data:t});if(s){let{CmdErrorCode:e,TargetText:t}=s;return{cmdErrorCode:e,translatedTextList:t}}})}({sourceLanguage:t,sourceTextList:s,targetLanguage:e},this._core);if(r){let{cmdErrorCode:{ErrorCode:e,ErrorInfo:t},translatedTextList:s}=r;if(0===e)return{code:0,data:{translatedTextList:s}};throw{errorCode:e,errorInfo:t,message:t}}}catch(e){var{errorCode:t,errorInfo:s}=e||{};throw new this._core.helper.ChatError({functionName:"translateText",code:t,message:s})}})}},fi=new class{init(e){(this._core=e).helper.registerApi({apiName:"convertVoiceToText",context:this})}convertVoiceToText(n){return I(this,void 0,void 0,function*(){var e,{message:t,language:s=kr.ZH_PY}=n;let r=(t.payload||{})["url"];var i=null==(i=this._core.store.get("login"))?void 0:i.userID,i=(t.from===i&&"out"===t.flow&&(r=t.payload.remoteAudioUrl),this._validateVoiceFormat(r),(null==(e=xr.exec(r))?void 0:e[1])||"mp3"),t=qr[s]||Fr;try{let s=yield function(e){var{store:t,common:s}=E.core,{url:e,format:r,serverLanguageType:i}=e,i={BytesUrl:e,BytesEngServiceType:i,BytesVoiceFormat:r,Uint32Sdkappid:null==(e=t.get("instance"))?void 0:e.sdkAppId,Uint64SourceType:0};return s.buildAndSendPacket({servcmd:"im_open_speech.ws_sentence_recognition",data:i})}({url:r,format:i,serverLanguageType:t});if(s){let{CmdErrorCode:e,BytesResult:t}=s;if(0===e.ErrorCode)return{code:0,data:{result:t}};throw{code:e.ErrorCode,message:e.ErrorInfo}}}catch(e){let{code:t,message:s}=e||{};throw new this._core.common.ChatError({functionName:"convertVoiceToText",code:t,message:s})}})}_validateVoiceFormat(e){if(!xr.test(e))throw new this._core.common.ChatError({code:2119})}};class Ii{constructor(e){var{constants:t,common:s,utils:r}=E.core,{CONV_C2C:t,CONV_GROUP:i}=t.OuterConstant,{ID:e,tinyID:n,from:o,to:a,clientTime:s=s.timeManager.getServerTimeSeconds()||0,random:u,sequence:l,cloudCustomData:c="",nick:d="",avatar:p="",clientSequence:h,conversationType:g,groupID:_,_elements:m,time:v}=e,n=(this.ID=e||n+`-${s}-`+u,this.messageRandom=u,this.from=o,this.messageSender=o,this.time=v,this.messageSequence=l,this.clientSequence=h||l,this.clientTime=s,this.cloudCustomData=c,this.messageReceiver=a,this.avatar=p,this.nick=d,r.deepCopyWithMethods(m));n.forEach(e=>{e.payload=e.content,delete e.content}),this.messageBody=n,e?g.startsWith(t)?this.receiverUserID=a:g.startsWith(i)&&(this.receiverGroupID=a):_?(this.receiverGroupID=_,this.messageReceiver=_):a&&(this.receiverUserID=a,this.messageReceiver=a)}transformElementsToServerFormat(){return this.messageBody?Array.isArray(this.messageBody)?this.messageBody.map(e=>e.transformToServerFormat({isMergerMessage:!0})):this.messageBody.transformToServerFormat({isMergerMessage:!0}):null}}class Ei{static parseServerPushElement(e){var e=e["MsgContent"],{MsgList:e=[],CompatibleText:t,AbstractList:s,Title:r,PbMsgKey:i,JsonMsgKey:n}=e||{},e=e.map(e=>$r(e));return new Ei({messageList:e,title:r,abstractList:s,compatibleText:t,pbDownloadKey:i,downloadKey:n})}constructor(e){this.type=E.core.constants.OuterConstant.MSG_MERGER;let{messageList:t,title:s,abstractList:r,compatibleText:i,pbDownloadKey:n="",downloadKey:o="",version:a=0,layersOverLimit:u=!1}=e,l=[];t.forEach(e=>{e&&(e=new Ii(e),l.push(e))}),this.content={messageList:l,title:s,abstractList:r,compatibleText:i,version:a,downloadKey:o,pbDownloadKey:n,layersOverLimit:u}}validateBeforeSend(){var e=E.core.helper["isEmpty"];return e(this.content.messageList)?{isValid:!1,error:{message:"content is invalid"}}:{isValid:!0}}transformToServerFormat(e){var{isMergerMessage:e=!1}=e||{},{abstractList:e,compatibleText:t,downloadKey:s,layersOverLimit:r,pbDownloadKey:i,title:n,version:o,messageList:a}=e?this.payload:this.content;return{MsgType:this.type,MsgContent:{AbstractList:e,CompatibleText:t,JsonMsgKey:s,LayersOverLimit:r,PbMsgKey:i,Title:n,Version:o,MsgList:Yr(a)}}}}var Ci=new class{init(e){let{message:t,helper:s,constants:{OuterConstant:r}}=this._core=e;t.messageFactory.registerElementClass(r.MSG_MERGER,Ei),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 Ei(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,u){return I(this,void 0,void 0,function*(){var e,t,s;try{var n=function(t){let e="utf-8";E.core.helper.IN_BROWSER&&document&&(e=document.charset.toLowerCase());let s,r=0,i;if(i=t.length,"utf-8"===e||"utf8"===e)for(let e=0;e<i;e++)(s=t.codePointAt(e))<=127?r+=1:s<=2047?r+=2:s<=65535?r+=3:(r+=4,e++);else if("utf-16"===e||"utf16"===e)for(let e=0;e<i;e++)(s=t.codePointAt(e))<=65535?r+=2:(r+=4,e++);else r=t.replace(/[^\x00-\xff]/g,"aa").length;return r}(JSON.stringify(a));let r=a,i=null;if(11264<n){r=this._core.utils.deepCopyWithMethods(a);try{let{JsonMsgKey:e,PbMsgKey:t}=yield function(t){return I(this,void 0,void 0,function*(){var e=t["payload"]["messageList"],e={MsgList:Yr(e)};return E.core.common.buildAndSendPacket({servcmd:"im_long_msg.save_relay_json_msg",data:e})})}(r),s=r["payload"];i=new Ei(Object.assign(Object.assign({},s),{messageList:[],downloadKey:e,pbDownloadKey:t})),r.setElement(i)}catch(e){console.error(e)}}var{message:o}=(yield null==(s=null==(t=null==(e=this._core)?void 0:e.message)?void 0:t.messageSender)?void 0:s.sendMessage(r,u))["data"];return i&&o.setElement(a._elements),{code:0,data:{message:o}}}catch(e){let t=e["errorCode"];throw new this._core.helper.ChatError({code:t})}})}downloadMergerMessage(o){return I(this,void 0,void 0,function*(){let r=this._core["ssoLog"],e=o.payload,{downloadKey:i,pbDownload:t,type:s}=e,n=f(e,["downloadKey","pbDownload","type","messageList"]);try{let e=yield function(e){return I(this,void 0,void 0,function*(){return E.core.common.buildAndSendPacket({servcmd:"im_long_msg.get_relay_json_msg",data:{JsonMsgKey:e}})})}(i),t=(e||{})["MsgList"],s=null==t?void 0:t.map(e=>{e=$r(e);return new Ii(e)});return"function"==typeof o.isOnlineMessage?o.setElement({type:o.type,content:Object.assign({messageList:s},n)}):(o.payload.messageList=s,o.payload.downloadKey="",o.payload.pbDownloadKey=""),r.info("downloadMergerMessage"," success downloadKey:"+i),o}catch(e){let t=e["errorCode"];throw new this._core.helper.ChatError({functionName:"downloadMergerMessage",code:t,moreMessage:i})}})}},Si=new class{init(e){this._core=e,this._core.helper.registerExperimentalAPI("sendComboMessage",this)}sendComboMessage(a){return I(this,void 0,void 0,function*(){let{appStore:t,message:e,common:{getCurrentUserID:s},utils:{isArray:r}}=this._core,{GroupId:i,To_Account:n}=a,o=(a.From_Account=a.From_Account||s(),null);if(i){o=this._generateGroupMessage(Object.assign(Object.assign({},a),{ToGroupId:i}));let e=t.userStore.getUserProfile(s());o.level=(null==e?void 0:e.level)||0,r(n)&&0<n.length&&(o._receiverList=n)}else n&&(o=this._generateC2CMessage(a));return e.messageSender.sendMessage(o,a)})}_generateC2CMessage(e){var{message:t,OuterConstant:{CONV_C2C:s}}=this._core,e=t.messageHelper.parseServerPushMessage(e),t=t.messageFactory.createMessage(Object.assign(Object.assign({},e),{conversationType:s,flow:Rr.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:Rr.OUT})),s=e["elements"];return t.setElement(s),t}},Mi=new class{init(e){var{helper:e,notificationCenter:t,InnerEvent:{MESSAGE_PUSH:s},InnerEventSubType:{GROUP_MESSAGE_PINNED:r}}=this._core=e;t.subscribeInnerEvent(s,r,this._handleGroupMessagePinned,this),e.registerApi({apiName:"pinGroupMessage",context:this}),e.registerApi({apiName:"getPinnedGroupMessageList",context:this})}pinGroupMessage(o){return I(this,void 0,void 0,function*(){let{ssoLog:e,common:{isTopic:t},OuterConstant:{},helper:{ChatError:r}}=this._core;var{groupID:s,message:i,isPinned:n}=o,i=i["sequence"];try{return yield function(o){return I(this,void 0,void 0,function*(){var{buildAndSendPacket:e,getCurrentUserID:t}=E.core["common"],{groupID:s,sequence:r,isPinned:i}=o,t=t(),n=i?"group_open_http_svc.pin_message":"group_open_http_svc.unpin_message",s={GroupId:s,MsgSeq:r};return i?s.Pinner_Account=t:s.UnPinner_Account=t,e({servcmd:n,data:s})})}({groupID:s,sequence:i,isPinned:n}),{code:0,data:{}}}catch(e){let{errorCode:t,errorInfo:s}=e||{};throw new r({code:t,message:s})}})}getPinnedGroupMessageList(r){return I(this,void 0,void 0,function*(){let e=[];try{var t,s=yield function(s){return I(this,void 0,void 0,function*(){var e=s["groupID"],{buildAndSendPacket:t}=E.core["common"];return t({servcmd:"group_open_http_svc.get_pinned_messages",data:{GroupId:e}})})}({groupID:r});return s&&({PinnedMsgList:t=[]}=s,e=yield this._updatePinnedMessageInfo({serverPinnedMessageList:t,groupID:r})),{code:0,data:{messageList:e}}}catch(e){throw e}})}_handleGroupMessagePinned(e){let{message:{messageHelper:l,messageFactory:c},notificationCenter:d,OuterEvent:p,OuterConstant:h}=this._core;e.GroupTips.forEach(e=>{var{ToGroupId:e,MsgBody:{PinnedMsg:t,OpType:s,MsgOperatorMemberExtraInfo:r,SdkGroupMessageId:n}}=e,{UserId:r,NickName:i="",ImageUrl:o=""}=r;let a=null,u=!1;if(16===s){u=!0;let e=l.parseServerGroupMessage(t);(a=c.createMessage(Object.assign(Object.assign({},e),{conversationType:h.CONV_GROUP,flow:"in"}))).setElement(e.elements),a.pinnerInfo={userID:r,nick:i,avatar:o}}else if(17===s){let{ClientTime:e,Random:t,SenderTinyId:s,ServerTime:r,MsgSeq:i}=n;a={ID:`${s}-${e}-`+t,sequence:i,random:t,time:r,clientTime:e}}a&&d.emitOuterEvent(p.PINNED_GROUP_MESSAGE_UPDATED,{name:p.PINNED_GROUP_MESSAGE_UPDATED,data:{groupID:e,message:a,isPinned:u,operatorInfo:{userID:r,nick:i,avatar:o}}})})}_findMessageBySequence(e,t){var{messageDataHandler:s}=this._core["message"];return[...s.getLocalMessageList(e),...s.getSparseMessageList(e)].find(e=>e.sequence===t)}_updatePinnedMessageInfo(e){return I(this,arguments,void 0,function*({serverPinnedMessageList:n,groupID:e}){let{OuterConstant:{CONV_GROUP:t},utils:{isEmpty:s}}=this._core,o=[],a=[],u=[],l=new Map,c=""+t+e;for(let i=0;i<n.length;i++){let e=n[i],{Pinner_Account:t,MsgSeq:s}=e,r=this._findMessageBySequence(c,s);a.push(t),l.set(s,t),r?o.push(r):u.push(s)}let r=yield this._fetchPinnedMessageInfo({conversationID:c,messageSequenceList:u,pinnerIDList:a});if(r){let{pinnerInfoMap:s,messageList:e}=r;return o.push(...e),o.forEach(e=>{var t=e["sequence"],t=l.get(t),t=s[t]||{userID:t,nick:"",avatar:""};e.pinnerInfo=t}),o.sort((e,t)=>e.sequence-t.sequence),o}return[]})}_fetchPinnedMessageInfo(n){return I(this,void 0,void 0,function*(){var{message:{},user:{userProfile:e},utils:{isArray:t}}=this._core,{conversationID:s,messageSequenceList:i,pinnerIDList:r}=n,s=yield Promise.all([this._fetchMessageBySequence({conversationID:s,messageSequenceList:i}),null==e?void 0:e.getUserProfile({userIDList:r})]);if(t(s)){let r={};return((null==(i=s[1])?void 0:i.data)||[]).forEach(e=>{var{userID:e,nick:t="",avatar:s=""}=e;r[e]={userID:e,nick:t,avatar:s}}),{messageList:(null==(e=s[0])?void 0:e.messageList)||[],pinnerInfoMap:r}}})}_fetchMessageBySequence(i){return I(this,void 0,void 0,function*(){var{utils:{isEmpty:e},message:{messageHistory:t}}=this._core,{conversationID:s,messageSequenceList:r}=i;return e(r)?[]:t.getGroupRoamingMessagesByAnchor({conversationID:s,messageSequenceList:r,getType:3})})}},yi=new class{constructor(){this.name="MessageEnhancer"}install(e){this._core=e,E.init(e),ai.init(e),ci.init(e),hi.init(e),mi.init(e),zr.init(e),vi.init(e),fi.init(e),Jr.init(e),Ci.init(e),Zr.init(e),Si.init(e),Mi.init(e),e.helper.registerValidateConfig({auth:ri,params:si}),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),hi.dispose(),mi.dispose(),Jr.dispose(),Zr.dispose()}_reset(){mi.reset()}},Ti=new class{constructor(){this._name="WebRequest"}init(e){this._core=e}request(g,_){return I(this,void 0,void 0,function*(){let e,t=(null==(e=this._core)?void 0:e.utils).isEmpty,{downloadUrl:s="",method:r="PUT",url:i,qs:n,headers:o={},resources:a,dataType:u="text",uploadByIP:l,uploadIP:c}=g,d=i;if(n){let e=this._queryString(n);e&&(d+=(d.includes("?")?"&":"?")+e)}let p=new XMLHttpRequest;p.open(r.toUpperCase(),d,!0),p.responseType=u;var h=Object.assign({},o);if(l&&c&&(h.host=c),!t(h))for(let e in h)h.hasOwnProperty(e)&&!["content-length","user-agent","origin","host"].includes(e.toLowerCase())&&p.setRequestHeader(e,h[e]);return p.onload=()=>{var e=this._getResponseBody(p,s,l&&c),e=this._buildResponse(p,e);if(200===p.status)_(null,e);else{if(c&&!d.includes(c))return g.url=this._domainName2IP(d,c),g.uploadByIP=!0,this.request(g,_);_({code:p.status,message:JSON.stringify(p.responseText)},e)}},p.onerror=()=>{var e=this._getResponseBody(p,s,l&&c),e=this._buildResponse(p,e),t={code:p.status,message:0===p.status?"CORS blocked or network error":JSON.stringify(p.responseText)};_(t,e)},g.onProgress&&p.upload&&(p.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})}),p.send(a),p})}_buildResponse(e,t){let s={};return e.getAllResponseHeaders().trim().split("\n").forEach(e=>{var t;e&&([e,t]=e.split(":").map(e=>e.trim()),s[e.toLowerCase()]=t)}),{statusCode:e.status,statusMessage:e.statusText,headers:s,data:t}}_getResponseBody(e,t,s){return 200===e.status&&t?{location:t,uploadIP:s}:{response:e.responseText,uploadIP:s}}_queryString(s,r="&",i="="){var{isEmpty:e,isPlainObject:t}=null==(e=this._core)?void 0:e.utils;return e(s)?"":t(s)?Object.keys(s).map(e=>{let t=encodeURIComponent(e)+i;return Array.isArray(s[e])?s[e].map(e=>t+encodeURIComponent(e)).join(r):t+encodeURIComponent(s[e])}).filter(Boolean).join(r):void 0}_domainName2IP(e,t){return e.replace(/^http(s)?:\/\/(.*?)\//,`https://${t}/`)}};let Ai=["unknown","image","video","audio","log"];var Oi,Di=new class{init(e){this._core=e}request(s,r){let e,{MINI_APP_NAMESPACE:i,IN_ALIPAY_MINI_APP:n,IN_UNI_IOS_APP:o}=null==(e=this._core)?void 0:e.utils,{resources:a="",headers:u={},url:l,downloadUrl:c=""}=s,d=l,p=null;var h=c?c.match(/^(https?:\/\/[^/]+\/)([^/]*\/?)(.*)$/):null;if(h){var h=decodeURIComponent(h[3]),h=h.includes("?")?h.split("?")[0]:h||"",h={key:s.fileKey||h,success_action_status:200,"Content-Type":""},g={};if(o){let[e,t]=l.split("?sign=");t&&(d=e+"?sign="+encodeURIComponent(t),g.sign=decodeURIComponent(t),g.signature=decodeURIComponent(t))}let t={url:d,header:u,name:"file",filePath:a,formData:Object.assign(Object.assign({},h),g),timeout:s.timeout||3e5};if(n){let e=f(t,["name"]);t=Object.assign(Object.assign({},e),{fileName:"file",fileType:s.fileType?Ai[s.fileType]:"image"})}return(p=i.uploadFile(Object.assign(Object.assign({},t),{success:e=>{this._handleResponse({response:e,downloadUrl:c,callback:r})},fail:e=>{this._handleResponse({response:e,downloadUrl:c,callback:r})}}))).onProgressUpdate&&p.onProgressUpdate(e=>{s.onProgress&&s.onProgress({total:e.totalBytesExpectedToSend||0,loaded:e.totalBytesSent||0,percent:e.progress?Math.floor(e.progress)/100:0})}),p}console.warn("message Invalid download URL format")}_handleResponse(e){var{downloadUrl:e,response:t,callback:s}=e,r={};if(t.header)for(let e in t.header)t.header.hasOwnProperty(e)&&(r[e.toLowerCase()]=t.header[e]);var i=+t.statusCode;200==i?s(null,{statusCode:i,headers:r,data:Object.assign(Object.assign({},t.data),{location:e})}):s({code:i,message:JSON.stringify(t.data)},{statusCode:i,headers:r,data:void 0})}};function Ri(e){return"file"===Object.prototype.toString.call(e).match(/^\[object (.*)\]$/)[1].toLowerCase()}function Li(e){e=e||99999999;return Math.round(Math.random()*e)}function Ni(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 bi(e){return Array.from({length:8},()=>Math.floor(65536*(1+Math.random())).toString(16).substring(1)).join("")+"-"+e}function Gi(e,t){return Math.round(Number(e)*10**t)/10**t}function Pi(e){return e<1024?e+"B":e<1048576?Math.floor(e/1024)+"KB":Math.floor(e/1048576)+"MB"}function wi(e){return e<=1048576?Gi(e/1024,1)+"KB/s":Gi(e/1048576,1)+"MB/s"}let Ui="TIMImageElem",ki="TIMSoundElem",Fi="TIMFileElem",qi="TIMVideoFileElem",xi="RichMediaMessagePlugin",Vi=["rich.my-imcloud.com","imrich.qcloud.com"],Bi=((n=Oi=Oi||{}).UNSENT="unSend",n.SUCCESS="success",n.FAIL="fail",{wechat:/^(wxfile:\/\/tmp_|http:\/\/temp\/|cloud:\/\/temp-)/,alipay:/^(https:\/\/resource\/|alipayfile:\/\/tmp\/)/,baidu:/^(http:\/\/tmp\/|swanfile:\/\/tmp_)/,bytedance:/^(ttfile:\/\/tmp_|\/(var|tmp)\/|tttemp:\/\/)/,qq:/^(qqfile:\/\/tmp_|http:\/\/qtemp\/)/});var C=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(Bi).some(e=>e.test(t))}extractFileFromInput(e){var{isArray:t}=this._core["utils"];return Ri(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 I(this,void 0,void 0,function*(){var{IN_MINI_APP:e,IN_BROWSER:t}=(null==(e=this._core)?void 0:e.utils)||{};return this._shouldSkipProbing()?{width:0,height:0}:t?this._probeImageDimensionsWeb(s):e?this._probeImageDimensionsMiniApp(s):void 0})}isSimpleCos(){var e=((null==(e=this._core)?void 0:e.store.get("cloudConfig"))||{})["simple_cos"];return"0"!==e}getFileDNList(){let e,t=Vi;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=Vi}return t}getPlatform(){var e;return null==(e=this._core)?void 0:e.utils.platform}generateUUID(e,t){let s,r=`${this.getSDKAppID()}-${this.getCurrentUserID()}-`+(null==(s=this._core)?void 0:s.utils.randomString());return t?r+"."+t:(e=(t=e.name||e.value||e.url||e.tempFilePath)&&t.slice(t.lastIndexOf(".")+1),r=e?r+"."+e:r)}processResourceUrl(e){if(!e)return"";let t=e;var s=this.getFileDownloadProxy(),r=this.getAuthKey(),i=this.getFileDNList(),e=(s&&(e.startsWith("http://")?t=e.replace(/^http:\/\/[^/]+/,s):e.startsWith("https://")&&(t=e.replace(/^https:\/\/[^/]+/,s))),r&&-1===t.indexOf("authKey=")&&function(e,t){let s=!1;if(e){var e=e.match(/:\/\/([0-9]?\.)?(.[^/:]+)/),r=e&&e[2]||"";if(r.includes("rich-dev"))return!0;for(let e=0;e<t.length;e++)if(r.endsWith(t[e])){s=!0;break}}return s}(t,i));return t=e?-1<t.indexOf("?")?t+"&authKey="+r:t+"?authKey="+r:t}getCurrentUserID(){var e;return null==(e=null==(e=this._core)?void 0:e.store.get("login"))?void 0:e.userId}getSDKAppID(){var e;return null==(e=null==(e=this._core)?void 0:e.store.get("instance"))?void 0:e.sdkAppId}getFileDownloadProxy(){var e;return(null==(e=null==(e=this._core)?void 0:e.store.get("instance"))?void 0:e.fileDownloadProxy)||""}getFileUploadProxy(){var e;return(null==(e=null==(e=this._core)?void 0:e.store.get("instance"))?void 0:e.fileUploadProxy)||""}getAuthKey(){var e;return(null==(e=null==(e=this._core)?void 0:e.store.get("login"))?void 0:e.authKey)||""}isPrivateNetWork(){var e;return null==(e=null==(e=this._core)?void 0:e.store.get("instance"))?void 0:e.proxyServer}getPlatformFlags(){var{IN_BROWSER:e,IN_MINI_APP:t,IN_RN_APP:s,IN_UNI_NATIVE_APP:r}=null==(e=this._core)?void 0:e.utils;return{IN_BROWSER:e,IN_MINI_APP:t,IN_RN_APP:s,IN_UNI_NATIVE_APP:r}}isEmpty(e){var t=(null==(t=this._core)?void 0:t.utils)["isEmpty"];return t(e)}_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})}},ji=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?Di:Ti,null!=(t=this.httpRequest)&&t.init(e)}uploadToCOS(l){return I(this,void 0,void 0,function*(){let r=xi+" uploadToCOS",{ssoLog:i,utils:{safeStringify:e}}=this._core,n=l["file"];this.uploadFileType=l.uploadFileType,i.debug("uploadToCOS",r+" options:"+e(l));try{let e=Date.now(),t=yield this._createCosOptions(l),s=yield this._uploadFile(t);this._handleUploadError(s,l);var o=this._createUploadResult(n,s),a=Date.now()-e,u=`size:${Pi(n.size)} time:${a}ms speed:`+wi(1e3*n.size/a);return i.debug("uploadToCOS",r+` ok. name:${n.name} `+u),{uploadOptions:t,response:o}}catch(e){throw console.warn(r+" failed, error:",e),e}})}_handleUploadError(e,t){var s=(null==(s=this._core)?void 0:s.helper)["ChatError"];if(403===e.statusCode)throw Ni(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:Ni(Date.now(),!1),uploadSpeed:wi(1e3*e.size/Ni(Date.now(),!1))}}_createCosOptions(p){return I(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 i=yield this._fetchCosSignatureUrl({fileType:this.uploadFileType,fileName:e,uploadMethod:s,duration:this.duration,userID:p.message.from,conversationType:r}),{uploadUrl:n,downloadUrl:o,requestSnapshotUrl:a,thumbUrl:u,largeUrl:l,fileKey:c}=i,d=!C.isPrivateNetWork()&&i.uploadIP;return{url:this._getRawOrUploadProxyUrl(n),fileType:this.uploadFileType,fileName:e,resources:t,downloadUrl:o,requestSnapshotUrl:a,thumbUrl:u,largeUrl:l,fileKey:c,uploadIP:d||"",onProgress:e=>this._handleUploadProgress(e,p)}}catch(e){throw console.error("Failed to create COS pre-signed URL options:",e),e}})}_prepareUploadParams(e){var{ssoLog:t,utils:{safeStringify:s}}=this._core,t=(t.debug("_prepareUploadParams"," prepareUploadParams:"+s(e)),e)["file"],{IN_MINI_APP:s,IN_RN_APP:r}=C.getPlatformFlags(),s=s||r,r=s&&e.message.type!==Fi,e=t["name"],e=e.slice(e.lastIndexOf(".")),e=""+Li(999999)+e;return{fileName:bi(r?t.name:e),resources:s?t.url:t,uploadMethod:s?1:0}}_handleUploadProgress(e,t){if("function"==typeof t.onProgress)try{t.onProgress(e.percent)}catch(e){throw console.warn("Upload progress callback error:",e),e}}_fetchCosSignatureUrl(e){return I(this,void 0,void 0,function*(){var{ssoLog:t,utils:{safeStringify:s}}=this._core,r=C.isSimpleCos(),i=this._prepareCosRequestData(e),n=r?"im_cos_msg.simple_sig":"im_cos_msg.pre_sig";try{let e=yield function(i,n,o){return I(this,void 0,void 0,function*(){try{var{helper:e,channel:t}=o,s=e.generateCosSpecifiedData({servcmd:i,data:n}),r=s.head.seq+i;return yield t.sendPacket(s,{requestId:r})}catch(e){throw console.warn("getCosSig error:",e),e}})}(n,i,this._core);this.fetchCosTryCount=0;var o=this._processResponse(e);return t.debug("_fetchCosSignatureUrl",` ok. isSimpleCos:${r} data:`+s(o)),o||{}}catch(t){if(this.fetchCosTryCount<1)return this.fetchCosTryCount++,this._fetchCosSignatureUrl(e);throw this.fetchCosTryCount=0,t}})}_processResponse(e){var t;let s=C.isSimpleCos(),u=s?null==(t=null==e?void 0:e.rpt_pre_sig)?void 0:t[0]:e;if(!u)return{};if(s){let{str_final_ip:e,rpt_pre_sig:t,uint32_file_id:s,uint32_exist_flag:r,str_download_url:i,str_upload_url:n,str_snapshot_url:o,str_file_key:a}=u;return{uploadIP:e,preSig:t,fileID:s,existFlag:r,downloadUrl:i,uploadUrl:n,requestSnapshotUrl:o,fileKey:a}}let{upload_url:r,download_url:i,snapshot_url:n,thumb_url:o,large_url:a,file_key:l}=u;return{uploadUrl:r,downloadUrl:i,requestSnapshotUrl:n,thumbUrl:o,largeUrl:a,fileKey:l}}_prepareCosRequestData(e){return C.isSimpleCos()?{uint32_upload_method:e.uploadMethod,uint32_platform:C.getPlatform(),uint32_sdkappid:C.getSDKAppID(),str_user_id:e.userID,uint32_scene:e.conversationType,rpt_upload_object:[{uint32_file_id:1,uint32_file_type:e.fileType,str_file_name:e.fileName}]}:{file_type:e.fileType,file_name:e.fileName,upload_method:e.uploadMethod,Duration:e.duration}}_uploadFile(i){return I(this,void 0,void 0,function*(){return new Promise((s,r)=>{this.httpRequest.request(i,(e,t)=>{e&&this.uploadFileTryCount<this.maxRetries&&this.shouldRetry(e)?(this.uploadFileTryCount++,this._uploadFile(i).then(s).catch(r)):(this.uploadFileTryCount=0,e?r(e):s(t))})})})}shouldRetry(e){return!(!e||5!==Math.floor(e.statusCode/100)&&(!this.isTimeRelatedError(e)||!this._isClockOutOfSync(e)||(this._syncSystemClock(e),0)))}isTimeRelatedError(e){var t,s;try{var r=null==(t=e.error)?void 0:t.Code,i=null==(s=e.error)?void 0:s.Message;return"RequestTimeTooSkewed"===r||"AccessDenied"===r&&"Request has expired"===i}catch(e){return!1}}_isClockOutOfSync(e){var t,e=(null==(t=e.headers)?void 0:t.date)||(null==(t=e.headers)?void 0:t.Date)||(null==(t=e.error)?void 0:t.ServerTime);return!!e&&(t=Date.now(),e=Date.parse(e),3e4<=Math.abs(t+this.systemClockOffset-e))}_syncSystemClock(e){var t,s=(null==(t=e.headers)?void 0:t.date)||(null==(t=e.headers)?void 0:t.Date)||(null==(t=e.error)?void 0:t.ServerTime);if(s){let e=Date.now(),t=Date.parse(s);this.systemClockOffset=t-e}}_getRawOrUploadProxyUrl(e){var t=C.getFileUploadProxy();let s=e;return s=t?e.replace(/^https:\/\/[^/]+/,t):s}_isC2CConversation(e){return"C2C"===e.slice(0,3)}};let Ki=["jpg","jpeg","gif","png","bmp","image","webp"],Wi={JPG:1,JPEG:1,GIF:2,PNG:3,BMP:4,UNKNOWN:255};class Hi{constructor(e,t){this.instanceID=Li(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=C.addAuthToUrl(e.imageUrl||e.url||""),this.url=C.addAuthToUrl(e.url||t)}setSizeType(e){this.sizeType=e}setType(e){this.type=e}setImageUrl(e){e&&(this.imageUrl=C.addAuthToUrl(e))}getImageUrl(){return this.imageUrl}}function Yi(e){var{originUrl:t,originWidth:e,originHeight:s,min:r=198}=e,i=parseInt(e)||0,s=parseInt(s)||0,n={url:void 0,width:0,height:0};if((i<=s?i:s)<=r)n.url=t,n.width=i,n.height=s;else{s<=i?(n.width=Math.ceil(i*r/s),n.height=r):(n.width=r,n.height=Math.ceil(s*r/i));let e=t&&-1<t.indexOf("?")?t+"&":t+"?";n.url=198===r?e+"imageView2/3/w/198/h/198":e+"imageView2/3/w/720/h/720"}return void 0===t?f(n,["url"]):n}class $i{constructor(e){this._imageMemoryURL="",this._percent=0,this.type=Ui;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:i}=t,n=r.map(e=>({size:e.Size,type:e.Type,width:e.Width,height:e.Height,url:e.URL}));return new $i({imageFormat:s,imageInfoArray:n,uuid:i})}createImageDataAsURL(e){let t="";var{IN_MINI_APP:s,IN_RN_APP:r,IN_BROWSER:i}=C.getPlatformFlags();return t=e&&((s||r)&&(t=e.url),i)?window.URL.createObjectURL(e):t}initImageInfoArray(t=[]){var s={type:0,size:0,width:0,height:0,url:""};for(let e=0;e<3;e++){var r=t[e]||Object.assign({},s),r=new Hi(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=Wi[e.toUpperCase()]||Wi.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],Yi({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:C.removeAuthToUrl(e.imageUrl)}))}}var zi=new class{constructor(){this._messageOptionsMap=new Map}init(e){var{notificationCenter:e,helper:t,InnerEvent:s,message:r}=this._core=e;t.registerApi({apiName:"createImageMessage",context:this}),null!=(t=null==r?void 0:r.messageFactory)&&t.registerElementClass(Ui,$i),e.subscribeInnerEvent(s.DESTROY,this._dispose,this)}createImageMessage(e){var t,s,r;try{var i=null==(t=this._core.store.get("login"))?void 0:t.userId,n=null==(r=null==(s=this._core)?void 0:s.message.messageFactory)?void 0:r.createMessage(Object.assign(Object.assign({},e),{from:i})),o=this._processImage(e),a=(e.payload.file=o,{imageFormat:Wi.UNKNOWN,uuid:C.generateUUID(o),file:o,imageInfoArray:[]}),u=new $i(a);return n.setElement(u),this._messageOptionsMap.set(n.clientSequence,e),n}catch(e){throw e}}upload(r){return I(this,void 0,void 0,function*(){var e=r.getElements()[0],t=this._messageOptionsMap.get(r.clientSequence).payload["file"],t=(this._validateBeforeUploadImage(t),yield this._performImageUpload(e,r,t)),s=this._generateImageInfo(t);return e.updateImageFormat(null==t?void 0:t.fileType),e.updateImageInfoArray(s),r})}_performImageUpload(r,i,s){return I(this,void 0,void 0,function*(){var e=i["to"],{uploadOptions:e,response:t}=yield ji.uploadToCOS({uploadFileType:1,file:s,to:e,message:i,onProgress:e=>{var t,s;r.updatePercent(e),null!=(s=null==(t=this._messageOptionsMap.get(i.clientSequence))?void 0:t.onProgress)&&s.call(t,e)}});return this._parseResponse(e,t)})}_generateImageInfo(e){var{location:e,fileSize:t,width:s,height:r,smallImageUrl:i,smallImageWidth:n,smallImageHeight:o,largeImageUrl:a,largeImageWidth:u,largeImageHeight:l,imageInfoArray:c}=e,e=C.addAuthToUrl(e),d={size:t,url:e,width:s,height:r};return 0<(null==c?void 0:c.length)?this._processImageInfoArray(c,t):i&&a?[Object.assign({},d),{largeImageUrl:a,largeImageWidth:u,largeImageHeight:l},{smallImageUrl:i,smallImageWidth:n,smallImageHeight:o}]:[Object.assign({},d),this._generateThumbInfo(e,s,r,720),this._generateThumbInfo(e,s,r,198)]}_generateThumbInfo(e,t,s,r){return Yi({originUrl:e,originWidth:t,originHeight:s,min:r})}_processImageInfoArray(e,t){let s,r,i;for(var n of e)1===n.type?(r=n,r.size=t):2===n.type?(i=n,i.size=t):(s=n,s.size=t);return[Object.assign({},s),Object.assign({},i),Object.assign({},r)]}_parseResponse(r,i){return I(this,void 0,void 0,function*(){try{var{thumbUrl:e,largeUrl:t,downloadUrl:s}=r;if(e&&t&&(yield this._getImageInfoByUrl(e,i,"thumb"),yield this._getImageInfoByUrl(t,i,"large")),C.isSimpleCos()&&!C.isPrivateNetWork()&&(yield this._getImageInfoArray(s,i),null!=i)&&i.uploadIP){let e=this._extractDomainFromUrl(s);e&&(yield this._getDownloadIP(e,i))}return i}catch(e){throw e}})}_extractDomainFromUrl(t){var e;try{let e=t.match(/:\/\/([^\/]+)/);return e?e[1]:null}catch(t){return null!=(e=this._core)&&e.ssoLog.warn("_extractDomainFromUrl","Failed to extract domain from URL:"+t.message),null}}_getImageInfoByUrl(r,i,n){return I(this,void 0,void 0,function*(){var t;try{let e=C.addAuthToUrl(r),{width:t=0,height:s=0}=yield C.probeImageWidthHeight(e);i.width=t,i.height=s,"thumb"===n?(i.smallImageUrl=r,i.smallImageWidth=t,i.smallImageHeight=s):(i.largeImageUrl=r,i.largeImageWidth=t,i.largeImageHeight=s)}catch(e){null!=(t=this._core)&&t.ssoLog.warn("_getImageInfoByUrl",`Failed to get ${n} image info:`+e.message)}})}_validateBeforeUploadImage(e){var t=(null==(t=this._core)?void 0:t.helper)["ChatError"];if(!e)throw new t({code:2251});this._checkImageType(e),this._checkImageSize(e)}_processImage(e){var t;try{var s=(null==(t=this._core)?void 0:t.utils)["IN_MINI_APP"],r=e.payload["file"];return s?this._processMiniAppImageFile(r):this._processWebImageFile(r)}catch(e){throw e}}_processMiniAppImageFile(e){Ri(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=C.extractFileFromInput(e);if(e)return e;throw new t({message:"Invalid file. Pass either `e.target` (from file input) or a File object"})}_getDownloadIP(r,i){return I(this,void 0,void 0,function*(){var e=xi+" getDownloadIP domainName: "+r;try{var t,s=yield function(o,a){return I(this,void 0,void 0,function*(){try{var{helper:e,channel:t}=a,s="im_cos_msg.get_final_ip",r={str_domain:o},i=e.generateProtocolData({servcmd:s,data:r}),n=i.head.seq+s;return yield t.sendPacket(i,{requestId:n})}catch(e){throw console.warn("getFinalIP error:",e),e}})}(r,this._core);s&&s.str_final_ip&&(console.log(e+" ok. downloadIP:"+s),(t=i.location.split("/"))[0]=s.str_final_ip,i.location=t.join("/"))}catch(e){console.warn(e)}})}_getImageInfoArray(t,s){return I(this,void 0,void 0,function*(){try{var e=yield function(o,a){return I(this,void 0,void 0,function*(){try{var{helper:e,channel:t}=a,s="im_cos_msg.get_imageinfo",r={str_image_url:o},i=e.generateProtocolData({servcmd:s,data:r}),n=i.head.seq+s;return yield t.sendPacket(i,{requestId:n})}catch(e){throw console.warn("getImageInfo error:",e),e}})}(t,this._core);return s.imageInfoArray=this._processImageInfoResponse(e),s}catch(e){throw s.imageInfoArray=void 0,e}})}_processImageInfoResponse(e){return e?(e=e["rpt_msg_image_info"],e.map(e=>({type:e.uint32_image_type,url:e.str_url,width:e.uint32_width,height:e.uint32_height,imageFormat:e.str_image_format}))):[]}_checkImageType(e){var{utils:t,helper:s}=this._core;let r="";if(t.IN_MINI_APP&&(r=e.url.slice(e.url.lastIndexOf(".")+1)),t.IN_BROWSER&&(r=e.name.slice(e.name.lastIndexOf(".")+1)),Ki.indexOf(r.toLowerCase())<0)throw new s.ChatError({code:2252})}_checkImageSize(e){var{utils:t,helper:s}=this._core,r=0;if(t.IN_MINI_APP,0===(r=e.size))throw new s.ChatError({code:2108});if(20971520<=r)throw new s.ChatError({message:"File size exceeds limit: "+Pi(20971520)})}_reset(){this._messageOptionsMap.clear()}_dispose(){this._reset();var{notificationCenter:e,InnerEvent:t}=this._core;e.unSubscribeInnerEvent(t.DESTROY,this._dispose,this)}};let Ji=104857600;function Qi(e,t){let r=e.split("."),i=t.split("."),n=Math.max(r.length,i.length);for(;r.length<n;)r.push("0");for(;i.length<n;)i.push("0");for(let s=0;s<n;s++){let e=parseInt(r[s]),t=parseInt(i[s]);if(e>t)return 1;if(e<t)return-1}return 0}let Xi=new class{init(e){this.core=e}};class Zi{constructor(e){this.type=Fi,this.uploadProgress=0;var t=this._getFileInfo(e);this.content={downloadFlag:2,fileUrl:C.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:i}=e;return new Zi({downloadFlag:e,url:t,fileName:s,fileSize:r,uuid:i})}updatePercent(e){this.uploadProgress=Math.min(e,1)}updateFileUrl(e){this.content.fileUrl=e}validateBeforeSend(){var e=""!==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:i}=e?this.payload:this.content;return{MsgType:this.type,MsgContent:{Download_Flag:t,Url:C.removeAuthToUrl(s),FileName:r,FileSize:i,UUID:e}}}_getFileInfo(e){var t=Xi.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=Li(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 en=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(Fi,Zi),e.subscribeInnerEvent(s.DESTROY,this._dispose,this)}createFileMessage(e){var t,s,r;try{this._checkVersion();var i=this._processFile(e.payload.file),n=(e.payload.file=i,null==(t=this._core.store.get("login"))?void 0:t.userId),o=null==(r=null==(s=this._core)?void 0:s.message.messageFactory)?void 0:r.createMessage(Object.assign(Object.assign({},e),{from:n})),a={uuid:C.generateUUID(i),file:i},u=new Zi(a);return o.setElement(u),this._messageOptionsMap.set(o.clientSequence,e),o}catch(e){throw e}}upload(s){return I(this,void 0,void 0,function*(){var e=this._messageOptionsMap.get(s.clientSequence).payload["file"],t=(this._validateBeforeUploadFile(e),s.getElements()[0]),e=yield this._performFileUpload(t,s,e),e=C.addAuthToUrl(null==e?void 0:e.location);return t.updateFileUrl(e),s})}_validateBeforeUploadFile(e){var t=(null==(t=this._core)?void 0:t.helper)["ChatError"];if(!e)throw new t({code:2401});if(e.size>Ji)throw new t({message:"File size exceeds limit: "+Pi(Ji)});if(0===e.size)throw new t({code:2108})}_performFileUpload(r,i,t){return I(this,void 0,void 0,function*(){var e=i["to"],e=(yield ji.uploadToCOS({uploadFileType:255,file:t,to:e,message:i,onProgress:e=>{var t,s;r.updatePercent(e),null!=(s=null==(t=this._messageOptionsMap.get(i.clientSequence))?void 0:t.onProgress)&&s.call(t,e)}}))["response"];return e})}_processFile(t){var{IN_BROWSER:e,IN_RN_APP:s,IN_WX_MINI_APP:r,IN_QQ_MINI_APP:i,IN_UNI_NATIVE_APP:n}=null==(e=this._core)?void 0:e.utils,o=(null==(o=this._core)?void 0:o.helper)["ChatError"];if(e||n){let e=C.extractFileFromInput(t);if(e)return e;throw new o({message:"Invalid file. Pass either `e.target` (from file input) or a File object"})}if(r||i){let e=t["tempFiles"];return Object.assign(Object.assign({},e[0]),{url:e[0].path})}return s?Object.assign(Object.assign({},t),{url:t.uri}):t}_checkVersion(){var{MINI_APP_NAMESPACE:t,IN_MINI_APP:e,IN_WX_MINI_APP:s,IN_QQ_MINI_APP:r,IN_UNI_NATIVE_APP:i}=null==(e=this._core)?void 0:e.utils,n=(null==(n=this._core)?void 0:n.helper)["ChatError"];if(e){if(!(s||r||i))throw new n({message:"Unsupported mini app environment"});let e=t.getSystemInfoSync().SDKVersion;if(s&&Qi(e,"2.5.0")<0)throw new n({message:"WXChooseMessageFile requires SDK version 2.5.0 or higher"});if(r&&Qi(e,"1.18.0")<0)throw new n({message:"QQChooseMessageFile requires SDK version 1.18.0 or higher"})}}_reset(){this._messageOptionsMap.clear()}_dispose(){this._reset();var{notificationCenter:e,InnerEvent:t}=this._core;e.unSubscribeInnerEvent(t.DESTROY,this._dispose,this)}};let tn=["mp4","quicktime","mov"],sn=104857600;class rn{constructor(e){this.type=qi,this.uploadProgress=0;var t="number"==typeof(null==e?void 0:e.videoSecond)?null==e?void 0:e.videoSecond:0;this.content={remoteVideoUrl:C.addAuthToUrl(e.remoteVideoUrl||e.videoUrl||""),videoFormat:e.videoFormat,videoSecond:parseInt(null==t?void 0:t.toString(),10),videoSize:e.videoSize,videoUrl:C.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:C.addAuthToUrl(e.thumbUrl),snapshotUrl:C.addAuthToUrl(e.thumbUrl)}}static parseServerPushElement(e){var e=e["MsgContent"],{VideoUrl:e,VideoFormat:t,VideoSecond:s,VideoSize:r,VideoDownloadFlag:i,VideoUUID:n,ThumbUUID:o,ThumbFormat:a,ThumbWidth:u,SnapshotWidth:l,ThumbHeight:c,SnapshotHeight:d,ThumbSize:p,SnapshotSize:h,ThumbDownloadFlag:g,ThumbUrl:_,SnapshotUrl:m}=e;return new rn({videoUrl:e,videoFormat:t,videoSecond:s,videoSize:r,videoDownloadFlag:i,videoUUID:n,thumbUUID:o,thumbFormat:a,thumbWidth:u,snapshotWidth:l,thumbHeight:c,snapshotHeight:d,thumbSize:p,snapshotSize:h,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;C.isEmpty(e)||(this.content.thumbUrl=this.content.snapshotUrl=e),C.isEmpty(t)||(this.content.thumbWidth=this.content.snapshotWidth=Number(t)),C.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:i,videoUUID:n,thumbUUID:o,thumbFormat:a,thumbWidth:u,snapshotWidth:l,thumbHeight:c,snapshotHeight:d,thumbSize:p,snapshotSize:h,thumbDownloadFlag:g,thumbUrl:_,snapshotUrl:m}=e?this.payload:this.content;return{MsgType:this.type,MsgContent:{VideoUrl:C.removeAuthToUrl(e),VideoFormat:t,VideoSecond:s,VideoSize:r,VideoDownloadFlag:i,VideoUUID:n,ThumbUUID:o,ThumbFormat:a,ThumbWidth:u,SnapshotWidth:l,ThumbHeight:c,SnapshotHeight:d,ThumbSize:p,SnapshotSize:h,ThumbDownloadFlag:g,ThumbUrl:C.removeAuthToUrl(_),SnapshotUrl:C.removeAuthToUrl(m)}}}}var nn=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(qi,rn),e.subscribeInnerEvent(s.DESTROY,this._dispose,this)}createVideoMessage(e){var t,s,r;try{var i=this._processVideo(e),n=(e.payload.file=i,null==(t=this._core.store.get("login"))?void 0:t.userId),o=null==(r=null==(s=this._core)?void 0:s.message.messageFactory)?void 0:r.createMessage(Object.assign(Object.assign({},e),{from:n})),a={videoFormat:i.videoFile.type,videoSecond:Gi(i.videoFile.second,0),videoSize:i.videoFile.size,remoteVideoUrl:"",videoUrl:i.videoFile.url,videoUUID:C.generateUUID(i.videoFile),thumbUUID:C.generateUUID(i.videoFile,"jpg"),thumbWidth:i.width||200,thumbHeight:i.height||200,thumbUrl:i.thumbUrl,thumbSize:i.thumbSize,thumbFormat:"jpg"},u=new rn(a);return o.setElement(u),this._messageOptionsMap.set(o.clientSequence,e),o}catch(e){throw e}}upload(r){return I(this,void 0,void 0,function*(){var e=r.getElements()[0],t=this._messageOptionsMap.get(r.clientSequence).payload["file"],t=(this._validateBeforeUploadVideo(t),yield this._performVideoUpload(e,r,t)),{location:t,snapshotInfo:s}=t,t=C.addAuthToUrl(t);return e.updateVideoUrl(t),C.isEmpty(s)||e.updateSnapshotInfo(s),r})}_validateBeforeUploadVideo(e){var t=(null==(t=this._core)?void 0:t.helper)["ChatError"];if(e.videoFile.size>sn)throw new t({message:"File size exceeds limit: "+Pi(sn)});if(0===e.videoFile.size)throw new t({code:2108});if(-1===tn.indexOf(e.videoFile.type))throw new t({code:2352})}_performVideoUpload(r,i,s){return I(this,void 0,void 0,function*(){var e=i["to"],{response:e,uploadOptions:t}=yield ji.uploadToCOS({uploadFileType:2,file:s,to:e,message:i,onProgress:e=>{var t,s;r.updatePercent(e),null!=(s=null==(t=this._messageOptionsMap.get(i.clientSequence))?void 0:t.onProgress)&&s.call(t,e)}});return{snapshotInfo:yield this._getSnapshotInfoByUrl(t.requestSnapshotUrl),location:e.location}})}_processVideo(e){var r,i;try{var n=(null==(r=this._core)?void 0:r.helper)["ChatError"],{IN_MINI_APP:o,IN_BROWSER:a}=null==(i=this._core)?void 0:i.utils;let t=e.payload["file"],s={};if(o&&(s=this._processMiniVideoFile(t),t.name=s.name,t.url=s.url,t.type=s.type),a){let e=C.extractFileFromInput(t);if(!e)throw new n({message:"Invalid file. Pass either `e.target` (from file input) or a File object"});t=e,s=this._processWebVideoFile(t)}return t.videoFile=s,t.thumbUrl="",t.thumbSize=0,t}catch(e){throw console.warn(xi+" _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(Ri(e))throw new r({message:"FileUnsupportedInMiniApp"});let i=(e=Array.isArray(e.tempFiles)?e.tempFiles[0]:e).tempFilePath.slice(e.tempFilePath.lastIndexOf(".")+1).toLowerCase();return s&&(i=e.fileType||i),{url:e.tempFilePath,name:e.tempFilePath.slice(e.tempFilePath.lastIndexOf("/")+1),size:e.size||1,second:e.duration||0,type:i}}_processWebVideoFile(e){var{name:t,size:s=1,duration:r=0,type:i}=e,i=i.split("/")[1];return{url:window.URL.createObjectURL(e),name:t,size:s,second:r,type:i}}_getSnapshotInfoByUrl(n){return I(this,void 0,void 0,function*(){var e=this._core["ssoLog"];try{e.debug("_getSnapshotInfoByUrl",xi+" _getSnapshotInfoByUrl url:"+n);var t,s,r,i=((yield function(n,o){return I(this,void 0,void 0,function*(){try{var e="im_cos_msg.video_cover",{helper:t,channel:s}=o,r=t.generateCosSpecifiedData({servcmd:e,data:n}),i=r.head.seq+e;return yield s.sendPacket(r,{requestId:i})}catch(e){throw console.warn("getSnapshotInfo error:",e),e}})}({version:1,platform:C.getPlatform(),cover_name:bi(Li(99999)),snapshot_url:n},this._core))||{})["download_url"];return(e.debug("_getSnapshotInfoByUrl",xi+" _getSnapshotInfoByUrl OK snapshotUrl:"+i),C.isEmpty(i))?{}:(t=C.addAuthToUrl(i),{width:s=0,height:r=0}=yield C.probeImageWidthHeight(t),{snapshotUrl:t,snapshotWidth:s,snapshotHeight:r})}catch(e){throw e}})}_reset(){this._messageOptionsMap.clear()}_dispose(){this._reset();var{notificationCenter:e,InnerEvent:t}=this._core;e.unSubscribeInnerEvent(t.DESTROY,this._dispose,this)}};class on{constructor(e){this.uploadProgress=0,this.type=ki,this.content={downloadFlag:2,second:e.second,size:e.size,url:C.addAuthToUrl(e.url),remoteAudioUrl:C.addAuthToUrl(e.url||""),uuid:e.uuid}}static parseServerPushElement(e){var e=e["MsgContent"],{Url:e,Download_Flag:t,Second:s,Size:r,UUID:i}=e;return new on({url:e,downloadFlag:t,second:s,size:r,uuid:i})}updatePercent(e){this.uploadProgress=Math.min(e,1)}updateAudioUrl(e){this.content.remoteAudioUrl=e}validateBeforeSend(){var e=""!==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:i}=e?this.payload:this.content;return{MsgType:this.type,MsgContent:{Url:C.removeAuthToUrl(s),Download_Flag:t,Second:i,Size:r,UUID:e}}}}var an,un,ln,cn=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(ki,on),e.subscribeInnerEvent(s.DESTROY,this._dispose,this)}createAudioMessage(e){var t,s,r;try{var i=e.payload["file"],i=this._processAudioFile(e.payload.file),n=(e.payload.file=i,null==(t=this._core.store.get("login"))?void 0:t.userId),o=null==(r=null==(s=this._core)?void 0:s.message.messageFactory)?void 0:r.createMessage(Object.assign(Object.assign({},e),{from:n})),a={second:Math.floor((i.duration||i.second)/1e3),size:i.fileSize||i.size||1,url:i.tempFilePath||i.uri||i.url,uuid:C.generateUUID(i)},u=new on(a);return o.setElement(u),this._messageOptionsMap.set(o.clientSequence,e),o}catch(e){throw new this._core.helper.ChatError({code:null==e?void 0:e.code})}}upload(s){return I(this,void 0,void 0,function*(){var{ssoLog:e,utils:{safeStringify:t}}=this._core,e=(e.debug("upload",xi+" uploadAudio message:"+t(s)),this._messageOptionsMap.get(s.clientSequence).payload)["file"],t=(this._validateBeforeUploadAudio(e),s.getElements()[0]),e=yield this._performAudioUpload(t,s,e),e=C.addAuthToUrl(null==e?void 0:e.location);return t.updateAudioUrl(e),s})}_validateBeforeUploadAudio(e){var t=(null==(t=this._core)?void 0:t.helper)["ChatError"];if(!e)throw new t({code:2300});if(20971520<e.size)throw new t({message:"File size exceeds limit: "+Pi(20971520)});if(0===e.size)throw new t({code:2108})}_performAudioUpload(r,i,t){return I(this,void 0,void 0,function*(){var e=i["to"],e=(yield ji.uploadToCOS({uploadFileType:3,file:t,to:e,message:i,onProgress:e=>{var t,s;r.updatePercent(e),null!=(s=null==(t=this._messageOptionsMap.get(i.clientSequence))?void 0:t.onProgress)&&s.call(t,e)}}))["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 dn={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}},pn={createImageMessage:dn,createAudioMessage:dn,createVideoMessage:dn,createFileMessage:dn},hn={createImageMessage:!0,createAudioMessage:!0,createVideoMessage:!0,createFileMessage:!0},gn={TIMImageElem:zi,TIMFileElem:en,TIMVideoFileElem:nn,TIMSoundElem:cn},_n=new class{constructor(){this.name="RichMediaMessage"}install(e){let{OuterConstant:{MSG_AUDIO:t,MSG_FILE:s,MSG_IMAGE:r,MSG_VIDEO:i}}=(this._core=e)["constants"];Xi.init(e),zi.init(e),en.init(e),nn.init(e),cn.init(e),ji.init(e),C.init(e),e.helper.registerApi({apiName:"sendMessage",context:this,matcher:e=>[t,s,r,i].includes(e[0].type)}),e.helper.registerValidateConfig({auth:hn,params:pn})}sendMessage(r,i){return I(this,void 0,void 0,function*(){var e,t,s;try{return yield this._upload(r),yield null==(s=null==(t=null==(e=this._core)?void 0:e.message)?void 0:t.messageSender)?void 0:s.sendMessage(r,i)}catch(e){let t=e["errorCode"];throw new this._core.helper.ChatError({functionName:"sendMessage",code:t})}})}_upload(s){return I(this,void 0,void 0,function*(){let{ssoLog:t,utils:{safeStringify:e}}=this._core;if(t.debug("_upload"," uploadFile message:"+e(s)),!0!==s._relayFlag)try{let e=gn[s.type];e&&(yield e.upload(s),t.info("_upload"," type:"+s.type))}catch(t){throw s.status=Oi.FAIL,t instanceof Error&&(t.data={message:s}),this._core.message.messageDataHandler.storeConversationMessage(s),t}})}},M=new class{init(e){this.core=e}},mn=e=>{var{OuterConstant:t,utils:{isString:s}}=M["core"];return s(e)&&e.slice(0,3)===t.CONV_C2C},vn=e=>{var{OuterConstant:t,utils:{isString:s}}=M["core"];return s(e)&&e.slice(0,5)===t.CONV_GROUP},fn=e=>{var{OuterConstant:t,utils:{isString:s}}=M["core"];return s(e)&&e===t.CONV_SYSTEM},In=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:M.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 En(e){var t=M.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 Cn(e,t){var s=M.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 Sn{constructor(e){this.conversationID=e.conversationID||"",this.unreadCount=e.unreadCount||0,this.type=e.type||"",this.lastMessage=In(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}}=M["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}}=M["core"],{nextUnreadCount:e,isFromGetConversations:r,isUnreadC2CMessage:i}=e;s(e)||(this.subType!==t.GRP_AVCHATROOM?r&&this.type===t.CONV_GROUP||i&&this.type===t.CONV_C2C?this.unreadCount=e:this.unreadCount+=e:this.unreadCount=0)}updateLastMessage(e){this.lastMessage=In(e)}reduceUnreadCount(){return 1<=this.unreadCount&&(--this.unreadCount,!0)}isLastMessageRevoked(e){var t=M["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}}=M["core"];t(e,this.groupAtInfoList)}clearGroupAtInfoList(){this.groupAtInfoList.length=0}getProfileCompleted(){return this._isInfoCompleted}setProfileCompleted(){this._isInfoCompleted=!0}}(b=an=an||{})[b.OFF=0]="OFF",b[b.ON=1]="ON",un=un||{},un[un.ONLY_CONVERSATIONID=1]="ONLY_CONVERSATIONID",(N=ln=ln||{})[N.CONV_NOT_FOUND=2500]="CONV_NOT_FOUND",N[N.USER_OR_GRP_NOT_FOUND=2501]="USER_OR_GRP_NOT_FOUND",N[N.CONV_UN_RECORDED_TYPE=2502]="CONV_UN_RECORDED_TYPE";var y=new class{constructor(){this._name="ConversationDataHandler",this._totalUnreadCount=0,this._groupAtTipsList=[]}init(e){var{helper:t,notificationCenter:s,appStore:{conversationStore:r},constants:{WORKFLOW_NAME:i,WORKFLOW_STEP:n},InnerEvent:{SYNC_CONVERSATION_LIST:o,MESSAGE_PUSH:a,NEW_MESSAGE:u,MESSAGE_DELETED:l,MESSAGE_REVOKED:c,MESSAGE_MODIFIED:d,CONVERSATION_UPDATED:p,LOGOUT:h,DESTROY:g}}=this._core=e,r=(this._conversationStore=r,t.registerWorkflowStep(i.SYNC_SERVER_INFO_AFTER_LOGIN,n.CONVERSATION_UPDATE_AFTER_UNREAD_SYNC_FINISHED,this._handleUnreadSyncFinished,this),t.registerWorkflowStep(i.SYNC_SERVER_INFO_AFTER_LOGIN,n.CONVERSATION_UPDATE_AFTER_GROUP_LIST_SYNC_FINISHED,this._handleGroupListSyncFinished,this),t.registerWorkflowStep(i.RECEIVE_C2C_NEW_MESSAGE,n.CREATE_OR_UPDATE_CONVERSATION_BY_RECEIVE_NEW_MESSAGE,this._handleNewMessage,this),t.registerWorkflowStep(i.RECEIVE_C2C_NEW_MESSAGE,n.CONVERSATION_UPDATE_AFTER_UNREAD_SYNC_FINISHED,this._handleUnreadSyncFinished,this),t.registerWorkflowStep(i.RECEIVE_GROUP_NEW_MESSAGE,n.CREATE_OR_UPDATE_CONVERSATION_BY_RECEIVE_NEW_MESSAGE,this._handleNewMessage,this),t.registerWorkflowStep(i.SYNC_SERVER_INFO_AFTER_RE_ONLINE,n.CONVERSATION_UPDATE_AFTER_UNREAD_SYNC_FINISHED,this._handleUnreadSyncFinished,this),t.registerWorkflowStep(i.RECEIVE_GROUP_TIPS_NOTIFICATION,n.CREATE_OR_UPDATE_CONVERSATION_BY_RECEIVE_NEW_MESSAGE,this._handleNewMessage,this),s)["InnerEventSubType"]["GROUP_AT_TIPS"];s.subscribeInnerEvent(o,this._handleConversationSynced,this),s.subscribeInnerEvent(u,this._handleNewMessage,this),s.subscribeInnerEvent(a,r,this._handleNewGroupAtTips,this),s.subscribeInnerEvent(l,this._handleMessageDeleted,this),s.subscribeInnerEvent(c,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),e.ssoLog.debug(this._name+".init")}_handleConversationSynced(e){this.updateLocalConversationList({conversationUpdateFieldList:e.conversationUpdateFieldList||[],isFromGetConversations:!0,updateUnreadCount:!0}),this.emitConversationListUpdate()}_handleUnreadSyncFinished(e){let{WORKFLOW_STEP:t}=this._core["constants"],{conversationUpdateFieldList:s=[],groupTipList:r=[],isUnreadC2CMessage:i}=e.result[t.UNREAD_MESSAGE_SYNC]||{},n=!1;s.forEach(e=>{var{conversationID:e,unreadCount:t}=e,e=this.getLocalConversation(e);e&&e.unreadCount!==t&&(e.updateUnreadCount({nextUnreadCount:t,isUnreadC2CMessage:i}),n=!0)}),n&&this.emitConversationListUpdate(),this._handleGroupAtTipsSynced(r)}_handleGroupAtTipsSynced(t){var s;for(let e=0;e<t.length;e++)if(12===t[e].Event){if(null!=(s=t[e].GroupTips[0].MsgBody)&&s.TopicId)continue;this._handleNewGroupAtTips(t[e])}}_handleGroupListSyncFinished(e){let r,{WORKFLOW_STEP:t}=this._core.constants,i=e.result[t.GROUP_LIST_SYNC]||[],{CONV_GROUP:n}=this._core.OuterConstant,o=!1;for(let s=0;s<i.length;s++){let e=i[s],t=""+n+e.groupID;var a;this.hasLocalConversation(t)&&((a=this.getLocalConversation(t)).groupProfile=JSON.parse(JSON.stringify(e)),a.lastMessage.lastSequence<e.nextMessageSeq&&(a.lastMessage.lastSequence=e.nextMessageSeq-1),a.subType||(a.subType=e.type),0<(null==(r=e._groupAtInfoList)?void 0:r.length)&&this._handleNewGroupAtTips({GroupTips:e._groupAtInfoList}),o=!0)}o&&this.emitConversationListUpdate()}_handleNewMessage(e){var t,{conversationUpdateFieldList:e=[],isInstantMessage:s=!0,isUnreadC2CMessage:r=!1,updateUnreadCount:i=!0}=e.result||{};0===e.length||({isTopic:t}=this._core["common"],t(e[0].conversationID))||(this.updateLocalConversationList({conversationUpdateFieldList:e,isInstantMessage:s,isUnreadC2CMessage:r,isFromGetConversations:!1,updateUnreadCount:i}),0<e.filter(e=>this._isConversationNeedShow(e.conversationID)).length&&this.emitConversationListUpdate())}_handleNewGroupAtTips(e){var{GroupTips:e=[]}=e;e.forEach(e=>{var{GroupAtTips:t,MsgBody:s,MsgRandom:r,ClientSeq:i}=e;let n={};t?n=this._convertGroupAtTipsKey(t):s?n=Object.assign({},this._convertGroupAtTipsKey(s)):e.groupAtType&&(n=Object.assign({},e)),n.__random=r,n.__sequence=i,this._groupAtTipsList.push(n)}),console.log(this._name+"._handleNewGroupAtTips groupAtTipsList: "+JSON.stringify(this._groupAtTipsList)),this._updateGroupAtInfoList()}_convertGroupAtTipsKey(e){var{From_Account:e,GroupId:t,MsgSeq:s,GroupAtType:r}=e;return{from:e,groupID:t,sequence:s,groupAtType:r}}_updateGroupAtInfoList(){if(0!==this._groupAtTipsList.length){let{common:e,OuterConstant:r}=this._core,i=e.getCurrentUserID(),n=!1;this._groupAtTipsList.forEach(t=>{var{groupID:s,from:e}=t;if(e!==i){let e=this.getLocalConversation(""+r.CONV_GROUP+s);e&&(e.updateGroupAtInfoList(t),n=!0)}}),n&&this.emitConversationListUpdate(),this._groupAtTipsList.length=0}}_handleMessageDeleted(t){console.log(this._name+"._handleMessageDeleted, conversationID:",t);var s,{message:{messageDataHandler:r},OuterConstant:i}=this._core,n=(null==r?void 0:r.getLocalMessageList(t))||[];let o={};for(let e=(n.length||0)-1;0<=e;e--)if(!n[e].isDeleted){o=n[e];break}r=this.getLocalConversation(t);if(r){let e=!1;r.lastMessage.lastSequence===o.sequence&&r.lastMessage.lastTime===o.time||(null!=(s=null==(s=this._core)?void 0:s.helper)&&s.isEmpty(o)&&(o=void 0),r.updateLastMessage(o),e=!0),t.startsWith(i.CONV_C2C)&&this.updateUnreadCount(t),e&&(this.emitConversationListUpdate(),console.log(this._name+`._handleMessageDeleted. update conversationID:${t} with lastMessage:`,r.lastMessage))}}_handleMessageRevoked(e){let{messageList:r=[],updateUnreadCount:i=!0}=e;if(console.log(this._name+"._handleMessageRevoked messageList:"+r.length),0!==r.length){let t=null,s=!1;r.forEach(e=>{(t=this.getLocalConversation(e.conversationID))&&(i&&t.reduceUnreadCount()&&(s=!0),t.isLastMessageRevoked({sequence:e.sequence,time:e.time}))&&(t.setLastMessageRevoked(!0),t.setLastMessageRevoker(e.revoker),s=!0)}),s&&this.emitConversationListUpdate()}}_handleMessageModified(e){console.log(this._name+"._handleMessageModified",JSON.stringify(e));var{conversationID:t,messageList:s}=e,e=this.getLocalConversation(t),{utils:{isEmpty:r},common:{getMessagePreviewText:i}}=this._core;if(!r(e)){r=e["lastMessage"];if(r){let e=(null==s?void 0:s[0])||{};r.lastTime===e.time&&r.lastSequence===e.sequence&&r.version!==e.version&&(r.type=e.type,r.payload=e.payload,r.messageForShow=i(e.type,e.payload),r.cloudCustomData=e.cloudCustomData,r.version=e.version,this.emitConversationListUpdate(),console.log(this._name+` conversationID:${t} lastMessage updated`))}}}_handleConversationUpdated(e){this.emitConversationListUpdate(null==e?void 0:e.needSort)}updateLocalConversationList(e){var t=e["isFromGetConversations"],e=this._getTmpConversationListMapping(e)["newConversationList"];this._sortConversationList(),t||this._updateNewConversationProfile(e),this._core.ssoLog.debug("updateLocalConversationList"," newConversationList: "+e.length)}_getTmpConversationListMapping(e){let n=this._core["OuterConstant"],{conversationUpdateFieldList:o,isFromGetConversations:a,isInstantMessage:u,isUnreadC2CMessage:l=!1,updateUnreadCount:c}=e,d=[],t=null==o?void 0:o.length;for(let i=0;i<t;i++){let t=new Sn(o[i]),{conversationID:s,type:r}=t;if(!function(e){var t=M.core["OuterConstant"];let s;return"@TLS#ERROR"===(s=e.startsWith(t.CONV_C2C)?e.replace(t.CONV_C2C,""):s)||"@TLS#NOT_FOUND"===s}(s))if(this.hasLocalConversation(s)){let e=this.getLocalConversation(s);a?(this.setLocalConversation(s,t),r===n.CONV_C2C?t.unreadCount=(null==e?void 0:e.unreadCount)||0:r===n.CONV_GROUP&&(t.groupProfile=JSON.parse(JSON.stringify(null==e?void 0:e.groupProfile)))):(this._mergeConversationInfo({conversationID:s,tmpConversation:t,lastMessage:o[i].lastMessage,isFromGetConversations:a,isInstantMessage:u}),this._patchLastMessage({conversationID:s,lastMessage:o[i].lastMessage,isInstantMessage:u}),!0===c&&null!=e&&e.updateUnreadCount({nextUnreadCount:t.unreadCount,isFromGetConversations:a,isUnreadC2CMessage:l}))}else d.push(t),this.setLocalConversation(s,t)}return{newConversationList:d}}_mergeConversationInfo(e){var{conversationID:e,tmpConversation:t,lastMessage:s,isFromGetConversations:r,isInstantMessage:i}=e,e=this.getLocalConversation(e),n=["unreadCount","allowType","adminForbidType","payload"],{utils:{isUndefined:r,isEmpty:o},common:{deepMerge:a}}=(!1===i&&n.push("lastMessage"),r&&n.push("isPinned"),this._core);r(i)&&s&&null===(null==e?void 0:e.lastMessage.payload)&&(e.lastMessage.payload=s.payload),o(null==e?void 0:e.lastMessage.revoker)||(e.lastMessage.revoker=null),a(e,t,n,[null,void 0,"",0,NaN])}_patchLastMessage(e){let i=this._core["OuterConstant"],{conversationID:t,lastMessage:n,isInstantMessage:o}=e,a=this.getLocalConversation(t);if(a&&n){let{payload:e,nameCard:t,nick:s,cloudCustomData:r=""}=n;o&&(e&&(a.lastMessage.payload=e),a.type===i.CONV_GROUP)&&(a.lastMessage.nameCard=t,a.lastMessage.nick=s),a.lastMessage.cloudCustomData!==r&&(a.lastMessage.cloudCustomData=r)}}_sortConversationList(){let{isEmpty:t}=this._core["utils"],e=[...this._conversationStore.getConversationMap()],s=[],r=[],i=[],n=[];e.forEach(e=>{(!0===e[1].isPinned?t(e[1].lastMessage.lastTime)?r:s:t(e[1].lastMessage.lastTime)?n:i).push(e)});var o=s.sort((e,t)=>t[1].lastMessage.lastTime-e[1].lastMessage.lastTime).concat(r).concat(i.sort((e,t)=>t[1].lastMessage.lastTime-e[1].lastMessage.lastTime)).concat(n);this._updateConversationMapFromList(o)}_updateNewConversationProfile(e){if(0!==e.length){let s=[],r=[],{CONV_GROUP:i,CONV_C2C:n}=this._core["OuterConstant"];e.forEach(e=>{var{conversationID:t,type:e}=e;if(e===n){let e=t.replace(n,"");s.push(e)}else if(e===i){let e=t.replace(i,"");r.push(e)}}),0<s.length&&this._updateC2CConversation(s),0<r.length&&this._updateGroupConversation(r)}}_updateC2CConversation(e){let t,{OuterConstant:{CONV_C2C:i},appStore:{userStore:n},user:s}=this._core,o=!1;null!=(t=s.userProfile)&&t.getUserProfile({userIDList:e}).then(e=>{((null==e?void 0:e.data)||[]).forEach(t=>{var s=t["userID"],r=this.getLocalConversation(""+i+s);if(r){let e=(null==(s=n.getFriend(s))?void 0:s.remark)||"";r.remark=e,r.userProfile=t,o=!0}}),o&&this.emitConversationListUpdate()}).catch(e=>{})}_updateGroupConversation(e){let{OuterConstant:{CONV_GROUP:s},appStore:{groupStore:r}}=this._core,i=!1;e.forEach(e=>{var t=r.getGroup(e),e=this.getLocalConversation(""+s+e);t&&e&&(e.groupProfile=t,i=!0)}),i&&this.emitConversationListUpdate()}_isConversationNeedShow(e){var{OuterConstant:{CONV_GROUP:t,GRP_ROOM:s,GRP_LIVE:r},utils:{isUndefined:i}}=this._core,e=this.getLocalConversation(e);return!(!i(e)&&(i=e.type===t&&(null==(i=e.groupProfile)?void 0:i.type)===s,t=e.type===t&&(null==(s=e.groupProfile)?void 0:s.type)===r,i||t))}updateUnreadCount(e,t=!0){let s,r,i=!1;var n,o=this.getLocalConversation(e),a=null==(r=null==(s=this._core)?void 0:s.message.messageDataHandler)?void 0:r.getLocalMessageList(e);return o&&(n=o.unreadCount,a=null==a?void 0:a.filter(e=>!e.isRead&&!e._onlineOnlyFlag&&!e.isDeleted).length,console.log(this._name+`._updateUnreadCount conversationID:${e} currentUnreadCount:${n} newUnreadCount:`+a),n!==a)&&(o.unreadCount=a,(i=!0)===t)&&this.emitConversationListUpdate(),i}emitConversationListUpdate(e=!1){e&&this._sortConversationList();var e=this._core["OuterEvent"]["CONVERSATION_LIST_UPDATED"],t=this.getLocalConversationList();this._emitEvent({name:e,data:t}),this._emitTotalUnreadCountUpdate()}_emitTotalUnreadCountUpdate(){var e,t=this.getTotalUnreadMessageCount();this._totalUnreadCount!==t&&(this._core.ssoLog.debug("_emitTotalUnreadCountUpdate",` from ${this._totalUnreadCount} to `+t),this._totalUnreadCount=t,this._emitEvent({name:null==(e=this._core)?void 0:e.OuterEvent.TOTAL_UNREAD_MESSAGE_COUNT_UPDATED,data:t}))}_emitEvent(e){var t;null!=(t=this._core)&&t.notificationCenter.emitOuterEvent(e.name,e)}getTotalUnreadMessageCount(){let{OuterConstant:t,utils:{isEmpty:s}}=this._core,e=this.getLocalConversationList(),r=0;return e.forEach(e=>{e.type===t.CONV_SYSTEM||!s(e.messageRemindType)&&e.messageRemindType!==t.MSG_REMIND_ACPT_AND_NOTE||(r+=e.unreadCount)}),r}getLocalConversationList(){return[...this._conversationStore.getConversationMap().values()].filter(e=>this._isConversationNeedShow(e.conversationID))}hasLocalConversation(e){return this._conversationStore.getConversationMap().has(e)}getLocalConversation(e){return this._conversationStore.getConversationMap().get(e)}setLocalConversation(e,t){return this._conversationStore.getConversationMap().set(e,t)}deleteLocalConversation(e){this._conversationStore.getConversationMap().delete(e)}_updateConversationMapFromList(e){this._clearConversationMap();for(var[t,s]of e)this.setLocalConversation(t,s)}_clearConversationMap(){this._conversationStore.getConversationMap().clear()}patchMessageRemindType(e,t){let s=!1;e.forEach(e=>{e=this.getLocalConversation(e);(null==e?void 0:e.messageRemindType)!==t&&(e.messageRemindType=t,s=!0)}),console.log(this._name+`.patchMessageRemindType conversationIDList:${e} messageRemindType:${t} hasUpdated:`+s),s&&this.emitConversationListUpdate()}markMessageAsRead(e){let{messageDataHandler:t}=this._core["message"],{conversationID:s,lastReadTime:i=0,lastReadSequence:n=0}=e,o=null==t?void 0:t.getLocalMessageList(s);if(0!==o.length){let e=o["length"];for(let r=e-1;0<=r;r--){let e=o[r],t=i&&e.time>i,s=n&&e.sequence>n;if(!t&&!s){if("in"===e.flow&&e.isRead)break;e.setIsRead(!0)}}}}appendToPinnedConversation(e){var t=[...this._conversationStore.getConversationMap().entries()],s=t.findIndex(e=>!1===e[1].isPinned);t.splice(s,0,[e.conversationID,e]),this._updateConversationMapFromList(t),this.emitConversationListUpdate()}_reset(){this._clearConversationMap(),this._totalUnreadCount=0,this._groupAtTipsList=[]}_dispose(){var{notificationCenter:e,InnerEvent:{NEW_MESSAGE:t,MESSAGE_DELETED:s,MESSAGE_REVOKED:r,MESSAGE_MODIFIED:i,CONVERSATION_UPDATED:n,LOGOUT:o,DESTROY:a,SYNC_CONVERSATION_LIST:u}}=this._core,{GROUP_AT_TIPS:l}=e["InnerEventSubType"];e.unSubscribeInnerEvent(t,this._handleNewMessage,this),e.unSubscribeInnerEvent(t,l,this._handleNewGroupAtTips,this),e.unSubscribeInnerEvent(s,this._handleMessageDeleted,this),e.unSubscribeInnerEvent(r,this._handleMessageRevoked,this),e.unSubscribeInnerEvent(i,this._handleMessageModified,this),e.unSubscribeInnerEvent(n,this._handleConversationUpdated,this),e.unSubscribeInnerEvent(u,this._handleConversationSynced,this),e.unSubscribeInnerEvent(o,this._reset,this),e.unSubscribeInnerEvent(a,this._dispose,this)}},Mn=new class{constructor(){this._name="GetConversationList"}init(e){e=(this._core=e).helper;e.registerApi({apiName:"getConversationList",context:this})}getConversationList(e){return I(this,void 0,void 0,function*(){return{code:0,data:{conversationList:this._getConversationList(e),isSyncCompleted:this._core.conversation.syncConversationHandler.isSyncCompleted()}}})}_getConversationList(o){let{isUndefined:e,isArray:t,isPlainObject:s}=this._core["utils"];if(e(o))return y.getLocalConversationList();if(t(o))return 0===o.length?[]:y.getLocalConversationList().filter(e=>o.includes(e.conversationID));if(s(o)){let{type:t,markType:s,groupName:r,hasUnreadCount:i,hasGroupAtInfo:n}=o;return y.getLocalConversationList().filter(e=>this._filterType(e,t)&&this._filterMarkType(e,s)&&this._filterGroupName(e,r)&&this._filterUnreadCount(e,i)&&this._filterGroupAtInfo(e,n))}return[]}_filterType(e,t){var s=this._core["OuterConstant"];return t!==s.CONV_C2C&&t!==s.CONV_GROUP||e.type===t}_filterGroupName(e,t){var{isString:s}=this._core["utils"];return!s(t)||(""===t?0===e.conversationGroupList.length:e.conversationGroupList.includes(t))}_filterMarkType(e,t){var{isNumber:s}=this._core["utils"];return!s(t)||(0===t?0===e.markList.length:e.markList.includes(t))}_filterUnreadCount(e,t){let s=!0;return!0===t?s=1<=e.unreadCount:!1===t&&(s=0===e.unreadCount),s}_filterGroupAtInfo(e,t){let s=!0;return!0===t?s=1<=e.groupAtInfoList.length:!1===t&&(s=0===e.groupAtInfoList.length),s}},yn=new class{constructor(){this._name="GetC2CMessageRemindType"}init(e){this._core=e}get(r){return I(this,void 0,void 0,function*(){try{var e=this._core["common"],t=yield function(s,r){return I(this,void 0,void 0,function*(){var{toAccount:e,userIDList:t}=s;return r.common.buildAndSendPacket({servcmd:"openim.get_c2c_peer_mute_notifications",data:{To_Account:e,Peer_Account:t}})})}({toAccount:e.getCurrentUserID(),userIDList:r},this._core),{MuteNotificationsList:s=[]}=t||{};s.forEach(e=>{var{Peer_Account:e,MuteNotifications:t}=e,e=""+this._core.OuterConstant.CONV_C2C+e,t=En(t);y.patchMessageRemindType([e],t)})}catch(e){console.error(this._name+".get fail:",e)}})}},Tn=new class{constructor(){this._name="GetGroupMessageRemindType"}init(e){this._core=e}get(s){return I(this,void 0,void 0,function*(){if(0!==s.length)try{var e=yield function(s,r){return I(this,void 0,void 0,function*(){var{groupIDList:e,responseFilter:t}=s;return r.common.buildAndSendPacket({servcmd:"group_open_http_svc.get_group_self_member_info",data:{GroupIdList:e,ResponseFilter:t}})})}({groupIDList:s,responseFilter:{MemberInfoFilter:["MsgFlag"]}},this._core),{GroupInfo:t=[]}=e||{};t.forEach(e=>{var{GroupId:e,MemberList:t}=e,t=(null==(t=t[0])?void 0:t.MsgFlag)||"",e=""+this._core.OuterConstant.CONV_GROUP+e;y.patchMessageRemindType([e],t)})}catch(e){console.error(this._name+".get fail:",e)}})}},An=new class{constructor(){this._name="GetConversationProfile"}init(e){e=(this._core=e).helper;e.registerApi({apiName:"getConversationProfile",context:this})}getConversationProfile(l){return I(this,void 0,void 0,function*(){let{OuterConstant:{CONV_C2C:s,CONV_GROUP:r,GRP_AVCHATROOM:i},appStore:{groupStore:n},utils:{isEmpty:e}}=this._core,o={code:0,data:{}},a=y.getLocalConversation(l);if(fn(l))o.data.conversation=a;else{let t=!1;var u=mn(l)?s:r;if(e(a)&&(t=!0,a=new Sn({conversationID:l,type:u})),console.log(this._name+`.getConversationProfile conversationID:${l} isNewConversation:`+t),null==(o.data.conversation=a)||!a.getProfileCompleted()){if(u===s){let e=l.replace(s,"");yield this._handleC2CConversation(a,e),t&&(yield yn.get([e]))}if(u===r){let e=l.replace(r,"");if(!n.getGroup(e))return o;yield this._handleGroupConversation(a,e),t&&a.groupProfile.type!==i&&(yield Tn.get([e]))}}}return o})}_handleC2CConversation(o,a){return I(this,void 0,void 0,function*(){var{user:e,helper:t,utils:{isEmpty:s},appStore:{conversationStore:r,userStore:i}}=this._core,n=o["conversationID"],e=yield null==(e=e.userProfile)?void 0:e.getUserProfile({userIDList:[a]});if(0===(null==e?void 0:e.data.length))throw new t.ChatError({code:ln.USER_OR_GRP_NOT_FOUND});o.userProfile=null==e?void 0:e.data[0];e=null==(t=i.getFriend(a))?void 0:t.remark,s(e)||o.remark===e||(o.remark=e),o.setProfileCompleted(),i=y.hasLocalConversation(n);console.log(this._name+`._handleC2CConversation conversationID:${n} hasLocalConversation: `+i),i?r.updateConversation(n,o):y.appendToPinnedConversation(o)})}_handleGroupConversation(r,i){return I(this,void 0,void 0,function*(){var{apiMap:{getGroupProfile:e},appStore:{conversationStore:t}}=this._core,s=r["conversationID"],e=yield e({groupID:i}),e=(r.groupProfile=null==e?void 0:e.data.group,r.setProfileCompleted(),y.hasLocalConversation(s));console.log(this._name+`._handleGroupConversation conversationID:${s} hasLocalConversation: `+e),e?t.updateConversation(s,r):y.appendToPinnedConversation(r)})}},On=new class{init(e){e=e.helper;e.registerApi({apiName:"getTotalUnreadMessageCount",context:this})}getTotalUnreadMessageCount(){return y.getTotalUnreadMessageCount()}},Dn=new class{constructor(){this._serverGroupConversationLastReadSeqMap=new Map,this._name="SetMessageRead"}init(e){let{helper:t,common:{isTopic:s},notificationCenter:r,InnerEvent:{MESSAGE_PUSH:i},InnerEventSubType:{ALL_MESSAGE_READ:n}}=this._core=e;t.registerApi({apiName:"setMessageRead",context:this,matcher:e=>!s(e[0].conversationID)}),t.registerApi({apiName:"setAllMessageRead",context:this}),r.subscribeInnerEvent(i,n,this._handleAllMessageRead,this)}handleC2CMessageReadSync(e){let{helper:{isEmpty:s},OuterConstant:r}=this._core;e.forEach(e=>{var t=e["ReadC2cMsgNotify"];if(!s(t)){let{UinPairReadArray:e=[]}=t;e.forEach(e=>{var{From_Account:e,LastReadTime:t}=e,e=""+r.CONV_C2C+e;console.log(this._name+`.handleC2CMessageReadSync conversationID:${e} lastReadTime:`+t),y.markMessageAsRead({conversationID:e,lastReadTime:t}),y.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),y.markMessageAsRead({conversationID:e,lastReadSequence:t}),y.updateUnreadCount(e),this._clearGroupAtInfoList(e)})})}setMessageRead(u){return I(this,void 0,void 0,function*(){var e,t=this._core["OuterConstant"],s=u["conversationID"],r={code:0,data:{}},i=y.getLocalConversation(s);let n=this._name+`.setMessageRead conversationID:${s} unreadCount:`+((null==i?void 0:i.unreadCount)||0);if(r.successLog={message:n},!i)return r;var o=!(null!=(e=null==(o=this._core)?void 0:o.helper)&&e.isEmpty(i.groupAtInfoList));if(i.type===t.CONV_GROUP&&o&&this._deleteGroupAtTips(s),0===i.unreadCount)return r;var a=this._core["helper"]["ChatError"];try{if(i.type===t.CONV_C2C){let e=this._getLocalMessageMaxTime(i);yield this._setC2CMessageRead(s,e),n+="lastMessageTime:"+e}if(i.type===t.CONV_GROUP){let e=this._getLocalMessageMaxSequence(i);yield this._setGroupMessageRead(s,e),n+="lastMessageSequence:"+e}}catch(e){let{errorCode:t,errorInfo:s}=e;throw new a({functionName:"setMessageRead",code:t,message:s,moreMessage:n})}return i.type===t.CONV_SYSTEM&&(i.unreadCount=0),y.emitConversationListUpdate(),Object.assign(Object.assign({},r),{successLog:{message:n}})})}setAllMessageRead(){return I(this,arguments,void 0,function*(t={}){let{OuterConstant:{READ_ALL_MSG:e},ssoLog:s,utils:{safeStringify:i}}=this._core,n="scope:"+t.scope,r=(s.createSSOLogData({method:"setAllMessageRead"}),t.scope||(t.scope=e),t)["scope"],o=this._generateSetAllMessageReadRequestData(r);if(0===o.allC2CMessageReadStatus&&0===o.groupMessageReadInfoList.length)return{code:0};try{let r=yield function(s){return I(this,void 0,void 0,function*(){var{allC2CMessageReadStatus:e,groupMessageReadInfoList:t}=s,e={C2CReadAllMsg:e,GroupReadInfo:t};return M.core.common.buildAndSendPacket({servcmd:"openim.read_all_unread_msg",data:e})})}(o);if(r){let{GroupReadInfoArray:e,C2CReadAllMsg:t}=r,s=this._parseGroupReadInfo(e);0<this._updateAllConversationReadStatus({allC2CMessageReadStatus:t})&&y.emitConversationListUpdate(),n+="failureGroupInfoList:"+i(s)}return{code:0,successLog:{message:n}}}catch(t){let e=t["errorCode"];throw new this._core.helper.ChatError({functionName:"setAllMessageRead",code:e,moreMessage:n})}})}_handleAllMessageRead(e){var{GroupReadInfoArray:e,C2CReadAllMsg:t}=e;this._parseGroupReadInfo(e),0<this._updateAllConversationReadStatus({allC2CMessageReadStatus:t})&&y.emitConversationListUpdate()}_updateAllConversationReadStatus(e){let{OuterConstant:{CONV_C2C:r,CONV_GROUP:i},appStore:t}=this._core,n=t.conversationStore.getConversationMap(),o=e["allC2CMessageReadStatus"],a=0;for(let[s,t]of n)if(1<=t.unreadCount){if(1===o&&t.type===r){let e=this._getLocalMessageMaxTime(t);y.markMessageAsRead({conversationID:s,lastReadTime:e})}else if(t.type===i){let t=s.replace(i,"");if(this._serverGroupConversationLastReadSeqMap.has(t)){let e=this._serverGroupConversationLastReadSeqMap.get(t);y.markMessageAsRead({conversationID:s,lastReadSequence:e})}}y.updateUnreadCount(s,!1)&&(a+=1)}return a}_generateSetAllMessageReadRequestData(r){let{OuterConstant:{CONV_C2C:i,CONV_GROUP:n,READ_ALL_C2C_MSG:o},appStore:e}=this._core,a={allC2CMessageReadStatus:0,groupMessageReadInfoList:[]},t=e.conversationStore.getConversationMap();for(let[,s]of t){let{type:e,unreadCount:t}=s;if(this._shouldSetAllMessageRead({scope:r,type:e,unreadCount:t}))if(e===i&&0===a.allC2CMessageReadStatus){if(a.allC2CMessageReadStatus=1,r===o)break}else if(e===n){let e=this._getLocalMessageMaxSequence(s),t=s.groupProfile["groupID"];a.groupMessageReadInfoList.push({GroupId:t,MsgSeq:e})}}return a}_parseGroupReadInfo(e){let{isUndefined:i}=this._core["utils"],n=[];return null!=e&&e.forEach(e=>{var{GroupId:e,MsgSeq:t,RetCode:s,LastReadMsgSeq:r}=e;i(s)?this._serverGroupConversationLastReadSeqMap.set(e,r):(this._serverGroupConversationLastReadSeqMap.set(e,t),0!==s&&n.push(e+`-${t}-`+s))}),n}_deleteGroupAtTips(o){return I(this,void 0,void 0,function*(){console.log(this._name+"._deleteGroupAtTips conversationID:"+o);let e=y.getLocalConversation(o);if(e){var n=(null==e?void 0:e.groupAtInfoList)||[];if(0!==n.length)try{let{common:{getCurrentUserID:t,isCommunity:e},OuterConstant:{CONV_GROUP:s,CONV_AT_ALL:r}}=this._core,i=[...n];e({groupID:o.replace(s,"")})&&0===(i=n.filter(e=>!e.atTypeArray.includes(r))).length?this._clearGroupAtInfoList(o,!1):(yield function(t,s){return I(this,void 0,void 0,function*(){var e=t["messageListToDelete"];return s.common.buildAndSendPacket({servcmd:"openim.deletemsg",data:{DelMsgList:e}})})}({messageListToDelete:i.map(e=>({From_Account:e.from,To_Account:t(),MsgSeq:e.__sequence,MsgRandom:e.__random,GroupId:e.groupID}))},this._core),console.log(this._name+"._deleteGroupAtTips ok. count:"+n.length),this._clearGroupAtInfoList(o))}catch(e){console.error(this._name+"._deleteGroupAtTips fail:",e)}}})}_clearGroupAtInfoList(e,t=!0){var s=y.getLocalConversation(e);s&&(0<s.groupAtInfoList.length&&(s.clearGroupAtInfoList(),console.log(this._name+`._clearGroupAtInfoList conversationID:${e} needEmitConversationUpdate:`+t)),t)&&y.emitConversationListUpdate()}_getLocalMessageMaxTime(e){var t=e["conversationID"],t=this._core.message.messageDataHandler.getLocalMessageList(t),t=Math.max(...t.map(e=>e.time));let s=(null==(e=null==e?void 0:e.lastMessage)?void 0:e.lastTime)||0;return t>s&&(console.log(`${this._name}._getLocalMessageMaxTime update lastMessageTime from ${s} to `+t),s=t),s}_getLocalMessageMaxSequence(e){var t=e["conversationID"],t=this._core.message.messageDataHandler.getLocalMessageList(t),t=Math.max(...t.map(e=>e.sequence));let s=(null==(e=null==e?void 0:e.lastMessage)?void 0:e.lastSequence)||0;return t>s&&(console.log(`${this._name}._getLocalMessageMaxSequence update lastMessageSequence from ${s} to `+t),s=t),s}_setC2CMessageRead(e,t){return I(this,void 0,void 0,function*(){try{yield function(e,t){return I(this,void 0,void 0,function*(){return t.common.buildAndSendPacket({servcmd:"openim.msgreaded",data:e})})}({C2CMsgReaded:{Cookie:"",C2CMsgReadedItem:[{To_Account:e.replace("C2C",""),LastedMsgTime:t,Receipt:1}]}},this._core),console.log(this._name+"._setC2CMessageRead ok, lastReadTime:"+t),y.markMessageAsRead({conversationID:e,lastReadTime:t}),y.updateUnreadCount(e)}catch(e){throw console.warn(this._name+"._setC2CMessageRead fail:",e),e}})}_setGroupMessageRead(e,t){return I(this,void 0,void 0,function*(){try{yield function(s,r){return I(this,void 0,void 0,function*(){var{groupID:e,lastMessageSequence:t}=s;return r.common.buildAndSendPacket({servcmd:"group_open_http_svc.msg_read_report",data:{GroupId:e,MsgReadedSeq:t}})})}({groupID:e.replace("GROUP",""),lastMessageSequence:t},this._core),console.log(this._name+"._setGroupMessageRead ok, lastReadSequence:"+t),y.markMessageAsRead({conversationID:e,lastReadSequence:t}),y.updateUnreadCount(e)}catch(e){throw console.warn(this._name+"._setGroupMessageRead fail:",e),e}})}_shouldSetAllMessageRead(e){var{CONV_C2C:t,CONV_GROUP:s,READ_ALL_MSG:r,READ_ALL_C2C_MSG:i,READ_ALL_GROUP_MSG:n}=this._core["OuterConstant"],{type:e,scope:o,unreadCount:a}=e;return!(a<=0||(e!==t||![r,i].includes(o))&&(e!==s||![r,n].includes(o)))}},Rn=new class{constructor(){this._name="PinConversation"}init(e){e=(this._core=e).helper;e.registerApi({apiName:"pinConversation",context:this})}handleConversationPinned(e,o){var{isArray:t}=this._core["utils"];if(t(e)){let i=this._core["OuterConstant"],n=!1;e.forEach(e=>{var{Type:e,To_Account:t,GroupId:s}=e;let r;1===e?r=y.getLocalConversation(""+i.CONV_C2C+t):2===e&&(r=y.getLocalConversation(""+i.CONV_GROUP+s)),r&&(console.log(`${this._name}.handleConversationPinned conversationID:${r.conversationID} localPinned:${r.isPinned} remotePinned:`+o),o&&!r.isPinned&&(r.isPinned=!0,n=!0),!o)&&r.isPinned&&(r.isPinned=!1,n=!0)}),n&&y.emitConversationListUpdate(!0)}}pinConversation(e){return I(this,void 0,void 0,function*(){let{OuterConstant:s,common:r,helper:{ChatError:i}}=this._core,{conversationID:n,isPinned:o}=e,a={code:0,data:{conversationID:n}},u=y.getLocalConversation(n);if(u&&u.isPinned===o)return a;if(fn(n))return u&&(u.isPinned=o),y.emitConversationListUpdate(!0),a;var l=`conversationID:${n} isPinned:`+o;try{let e=null,t=(mn(n)?e={Type:1,To_Account:n.replace(s.CONV_C2C,"")}:vn(n)&&(e={Type:2,GroupId:n.replace(s.CONV_GROUP,"")}),yield function(r,i){return I(this,void 0,void 0,function*(){var{fromAccount:e,operationType:t,itemList:s}=r;return i.common.buildAndSendPacket({servcmd:"recentcontact.top",data:{From_Account:e,OperationType:t,RecentContactItem:s}})})}({fromAccount:r.getCurrentUserID(),operationType:!0===o?1:2,itemList:[e]},this._core));if(t){if(u)u.isPinned!==o&&(u.isPinned=o);else{let e=new Sn({conversationID:n,type:mn(n)?s.CONV_C2C:s.CONV_GROUP,isPinned:o});y.setLocalConversation(n,e)}y.emitConversationListUpdate(!0)}return Object.assign(Object.assign({},a),{successLog:{message:l}})}catch(e){let{errorCode:t,errorInfo:s}=e;throw new i({functionName:"pinConversation",code:t,message:s,moreMessage:l})}})}},Ln=new class{constructor(){this._name="DeleteConversation"}init(e){e=(this._core=e).helper;e.registerApi({apiName:"deleteConversation",context:this})}handleConversationDeleted(e){var{isArray:t}=this._core["utils"];if(t(e)){let r=this._core["OuterConstant"],i=[];e.forEach(e=>{var{Type:e,Peer_Account:t,GroupId:s}=e;1===e&&i.push(""+r.CONV_C2C+t),2===e&&i.push(""+r.CONV_GROUP+s)}),console.log(this._name+".handleConversationDeleted conversationIDList:"+i),this._deleteLocalConversationList(i)}}deleteConversation(t){return I(this,void 0,void 0,function*(){var e=this._core["utils"]["isString"];e(t)?yield this._deleteConversation({conversationIDList:[t],flag:un.ONLY_CONVERSATIONID}):(100<(e=Object.assign({},t)).conversationIDList.length&&(e.conversationIDList=e.conversationIDList.slice(0,100)),yield this._deleteConversation(e))})}_deleteConversation(e){return I(this,void 0,void 0,function*(){let{conversationIDList:s,clearHistoryMessage:r=!0,flag:i=0}=e,{ChatError:n}=this._core["helper"],o=`conversationIDList:${s} clearHistoryMessage:`+r;try{let e=yield Promise.all([this._deleteConversationFromLocal(s),this._deleteConversationFromServer(s,r)]),t=[...e[0],...e[1]];if(0===t.length)throw new this._core.helper.ChatError({code:ln.CONV_NOT_FOUND});return{code:0,data:i===un.ONLY_CONVERSATIONID?{conversationID:t[0]}:{conversationIDList:t},successLog:{message:o}}}catch(e){let{errorCode:t,errorInfo:s}=e;throw new n({code:t,message:s,moreMessage:o})}})}_deleteConversationFromLocal(e){let s=this._core["OuterConstant"];return e.filter(e=>{var t;return!!y.hasLocalConversation(e)&&((t=null==(t=y.getLocalConversation(e))?void 0:t.type)===s.CONV_GROUP&&!this._hasLocalGroup(e)||t===s.CONV_SYSTEM)&&(this._deleteLocalConversation(e),!0)})}_deleteConversationFromServer(t,n){return I(this,void 0,void 0,function*(){let{OuterConstant:r,common:e}=this._core,i={fromAccount:e.getCurrentUserID(),conversationList:[],clearHistoryMessage:n?1:0};if(t.forEach(e=>{var t,s;y.hasLocalConversation(e)&&(t=(null==(t=y.getLocalConversation(e))?void 0:t.type)||"",s=e.replace(t,""),t===r.CONV_C2C?i.conversationList.push({To_Account:s,Type:1}):t===r.CONV_GROUP&&this._hasLocalGroup(e)&&i.conversationList.push({ToGroupid:s,Type:2}))}),0!==i.conversationList.length){var s=yield function(r,i){return I(this,void 0,void 0,function*(){var{fromAccount:e,conversationList:t,clearHistoryMessage:s}=r;return i.common.buildAndSendPacket({servcmd:"recentcontact.batch_delete",data:{From_Account:e,ContactItem:t,ClearRamble:s}})})}(i,this._core);if(s){let{ResultItem:e=[]}=s,t=[];return 0<e.length&&e.forEach(e=>{0===e.ResultCode&&(e=1===e.Type?""+r.CONV_C2C+e.To_Account:""+r.CONV_GROUP+e.ToGroupid,t.push(e))}),this._deleteLocalConversationList(t),t}}return[]})}_deleteLocalConversationList(e){let t=!1;e.forEach(e=>{y.hasLocalConversation(e)&&(this._deleteLocalConversation(e,!1),t=!0)}),console.log(this._name+"._deleteLocalConversationList isUpdate:"+t),t&&y.emitConversationListUpdate()}_deleteLocalConversation(e,t=!0){var s=y.hasLocalConversation(e);console.log(this._name+`._deleteLocalConversation conversationID:${e} has:`+s),s&&(y.deleteLocalConversation(e),this._deleteConversationLocalMessage(e),t)&&y.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)}},Nn=new class{constructor(){this._name="SetConversationDraft"}init(e){e=(this._core=e).helper;e.registerApi({apiName:"setConversationDraft",context:this})}setConversationDraft(s){return I(this,void 0,void 0,function*(){var{conversationID:e,draftText:t}=s;if(console.log(this._name+` conversationID:${e} draftText:`+t),y.hasLocalConversation(e))return null!=(e=y.getLocalConversation(e))&&e.setDraftText(t),y.emitConversationListUpdate(),{code:0,data:{conversation:e}};throw new this._core.helper.ChatError({code:ln.CONV_NOT_FOUND})})}},bn=new class{constructor(){this._name="SetC2CMessageRemindType"}init(e){this._core=e}set(a,u){return I(this,void 0,void 0,function*(){30<a.length&&(console.warn(`${this._name}.set userIDList length:${a.length} exceeds limit 30`),a.splice(30));let e=function(){var{MSG_REMIND_ACPT_AND_NOTE:e,MSG_REMIND_DISCARD:t,MSG_REMIND_ACPT_NOT_NOTE:s}=M.core.OuterConstant;return{[e]:0,[t]:1,[s]:2}}()[u],t=yield function(s,r){return I(this,void 0,void 0,function*(){var{userIDList:e,receiveMessageOption:t}=s;return r.common.buildAndSendPacket({servcmd:"openim.set_c2c_peer_mute_notifications",data:{Peer_Account:e,Mute_Notifications:t}})})}({userIDList:a,receiveMessageOption:e},this._core),{ErrorList:s=[]}=t||{},r=[],i=(s.forEach(e=>{var{Peer_Account:e,ErrorCode:t}=e,t=(r.push({userID:e,code:t}),a.indexOf(e));-1<t&&a.splice(t,1)}),[]),n=[],o=this._core["OuterConstant"];return a.forEach(e=>{n.push(""+o.CONV_C2C+e),i.push({userID:e})}),y.patchMessageRemindType(n,u),{code:0,data:{successUserIDList:i,failureUserIDList:r}}})}},Gn=new class{constructor(){this._name="SetGroupMessageRemindType"}init(e){this._core=e}set(r,i){return I(this,void 0,void 0,function*(){let{common:{getCurrentUserID:e,isTopic:t},OuterConstant:s}=this._core;if(yield function(r,i){return I(this,void 0,void 0,function*(){var{groupID:e,userID:t,receiveMessageOption:s}=r;return i.common.buildAndSendPacket({servcmd:"group_open_http_svc.modify_group_member_info",data:{GroupId:e,Member_Account:t,MsgFlag:s}})})}({groupID:r,userID:e(),receiveMessageOption:i},this._core),!t(r)){let e=""+s.CONV_GROUP+r;y.patchMessageRemindType([e],i)}return{code:0,data:{groupID:r,messageRemindType:i}}})}},Pn=new class{constructor(){this._name="SetMessageRemindType"}init(e){e=(this._core=e).helper;e.registerApi({apiName:"setMessageRemindType",context:this})}handleC2CMessageRemindTypeSync(e){let{helper:{isEmpty:t},OuterConstant:n}=this._core;e.forEach(e=>{var i=e["MuteNotificationsSync"];if(!t(i)){let{To_Account:e,MuteNotifications:t}=i,s=e.map(e=>""+n.CONV_C2C+e),r=En(t);console.log(this._name+`.handleC2CMessageRemindTypeSync conversationIDList:${s} messageRemindType:`+r),y.patchMessageRemindType(s,r)}})}setMessageRemindType(o){return I(this,void 0,void 0,function*(){let s="setMessageRemindType",{groupID:e,userIDList:t,messageRemindType:r}=o,{helper:i,utils:{isUndefined:n}}=this._core;try{if(!n(e))return console.log(`${this._name}.${s} groupID:${e} messageRemindType:`+r),yield Gn.set(e,r);if(n(t))throw new i.ChatError({functionName:s,message:"userIDList or groupID is required"});return console.log(this._name+`.${s} userIDList:${t} messageRemindType:`+r),yield bn.set(t,r)}catch(e){let t=new i.ChatError({functionName:s,code:null==e?void 0:e.errorCode,message:null==e?void 0:e.errorInfo});throw console.error(this._name+`.${s} fail:`,t),t}})}},wn=new class{init(e){e.ssoLog.debug("ConversationAction.init"),this._core=e,Mn.init(e),An.init(e),On.init(e),Dn.init(e),Rn.init(e),Ln.init(e),Nn.init(e),Pn.init(e);var{notificationCenter:e,InnerEvent:{MESSAGE_PUSH:t,DESTROY:s}}=this._core,{CONV_MODIFIED:r,C2C_MESSAGE_READ_SYNC:i,GROUP_MESSAGE_READ_SYNC:n,C2C_REMIND_TYPE_SYNC:o}=e["InnerEventSubType"];e.subscribeInnerEvent(t,r,this._onConversationModified,this),e.subscribeInnerEvent(t,i,this._onC2CMessageReadSync,this),e.subscribeInnerEvent(t,o,this._onC2CMessageRemindTypeSync,this),e.subscribeInnerEvent(t,n,this._onGroupMessageReadSync,this),e.subscribeInnerEvent(s,this._dispose,this)}_onConversationModified(e){let{ConvModifyPushType:s}=this._core["constants"],{RecentContactMod:t=[]}=e;t.forEach(t=>{var e=t["PushType"];if(e===s.CONV_DELETED){let e=t.RecentContactDeleteItem["RecentContactList"];Ln.handleConversationDeleted(e)}if(e===s.CONV_PINED){let e=t.RecentContactTopItem["RecentContactList"];Rn.handleConversationPinned(e,!0)}if(e===s.CONV_UNPINED){let e=t.RecentContactTopItem["RecentContactList"];Rn.handleConversationPinned(e,!1)}})}_onC2CMessageReadSync(e){var{C2cNotifyMsgArray:e=[]}=e;Dn.handleC2CMessageReadSync(e)}_onC2CMessageRemindTypeSync(e){var{C2cNotifyMsgArray:e=[]}=e;Pn.handleC2CMessageRemindTypeSync(e)}_onGroupMessageReadSync(e){var{GroupTips:e=[]}=e;Dn.handleGroupMessageReadSync(e)}_dispose(){var{notificationCenter:e,InnerEvent:{MESSAGE_PUSH:t,DESTROY:s}}=this._core,{CONV_MODIFIED:r,C2C_MESSAGE_READ_SYNC:i,GROUP_MESSAGE_READ_SYNC:n,C2C_REMIND_TYPE_SYNC:o}=e["InnerEventSubType"];e.unSubscribeInnerEvent(t,r,this._onConversationModified,this),e.unSubscribeInnerEvent(t,i,this._onC2CMessageReadSync,this),e.unSubscribeInnerEvent(t,o,this._onC2CMessageRemindTypeSync,this),e.unSubscribeInnerEvent(t,n,this._onGroupMessageReadSync,this),e.unSubscribeInnerEvent(s,this._dispose,this)}},Un=new class{init(e){e=(this._core=e).helper;e.registerApi({apiName:"setAllReceiveMessageOpt",context:this})}setAllReceiveMessageOpt(o){return I(this,void 0,void 0,function*(){try{var{MSG_REMIND_ACPT_NOT_NOTE:e}=this._core["OuterConstant"],{messageRemindType:t=e,isRepeated:s=!0}=o,{startTime:r=0,endTime:i=0}=this._calcStartAndEndTime(o),n=yield function(n){return I(this,void 0,void 0,function*(){var e=M.core["common"],{startTime:t,endTime:s,isRepeated:r,messageRemindType:i}=n;return e.buildAndSendPacket({servcmd:"im_msg_db_logic.ws_set_do_not_disturb",data:{StartTime:t,EndTime:s,IsRepeated:r,Level:i}})})}({messageRemindType:this._getType(t),startTime:r,endTime:i,isRepeated:s?an.ON:an.OFF});return{code:0,data:{errorCode:n.ErrorCode,errorInfo:n.ErrorInfo}}}catch(e){Cn("setAllReceiveMessageOpt",e)}})}_calcStartAndEndTime(e){var{startHour:e=0,startMinute:t=0,startSecond:s=0,duration:r=0,isRepeated:i=!0}=e,n=new Date,n=new Date(n.getFullYear(),n.getMonth(),n.getDate(),e,t,s),e=Math.round(n.getTime()/1e3);let o=i&&86400<=r?e+86400:e+r;return{startTime:e,endTime:o}}_getType(e){var t=this._core["OuterConstant"];return{[t.MSG_REMIND_ACPT_AND_NOTE]:0,[t.MSG_REMIND_DISCARD]:1,[t.MSG_REMIND_ACPT_NOT_NOTE]:2}[e]}},kn=new class{init(e){var{helper:e,notificationCenter:t,InnerEvent:s}=this._core=e;e.registerApi({apiName:"getAllReceiveMessageOpt",context:this}),t.subscribeInnerEvent(s.MESSAGE_PUSH,t.InnerEventSubType.ALL_RECEIVE_MESSAGE_OPTION,this.onAllReceiveMsgOptionNotify,this)}onAllReceiveMsgOptionNotify(e){var e=this._handleResult(e),{notificationCenter:t,OuterEvent:{ALL_RECEIVE_MESSAGE_OPT_UPDATED:s}}=this._core;t.emitOuterEvent(s,{name:s,data:e})}getAllReceiveMessageOpt(){return I(this,void 0,void 0,function*(){try{var e=yield function(){return I(this,void 0,void 0,function*(){var e=M.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){Cn("getAllReceiveMessageOpt",e)}})}_handleResult(e){var t=this._core["OuterConstant"],{MSG_REMIND_ACPT_AND_NOTE:t,MSG_REMIND_DISCARD:s,MSG_REMIND_ACPT_NOT_NOTE:r}=t,{Level:e,StartTime:i,EndTime:n,IsRepeated:o}=e;return{messageRemindType:{0:t,1:s,2:r}[e]||t,startTime:i,endTime:n,isRepeated:o===an.ON}}},Fn=new class{init(e){e.ssoLog.debug("ReceiveMessageOptions.init"),this._core=e,bn.init(e),Gn.init(e),yn.init(e),Tn.init(e),Un.init(e),kn.init(e)}};let qn=e=>!mn(e)&&!vn(e)&&!fn(e),xn={getConversationProfile:[{key:"conversationID",required:!0,rules:["string"],allowEmpty:!1,customValidator:e=>!qn(e)||"conversationID is invalid."}],setMessageRead:{conversationID:{required:!0,rules:["string"],allowEmpty:!1,customValidator:e=>!qn(e)||"conversationID is invalid."}},pinConversation:{conversationID:{required:!0,rules:["string"],allowEmpty:!1,customValidator:e=>!qn(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}}=M["core"];if(!r(e)&&!s(e))return"options is String or Object.";if(r(e)&&qn(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(qn(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=>!(!mn(e)&&!vn(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}}},Vn={getConversationList:!0,getConversationProfile:!0,getTotalUnreadCount:!0,setMessageRead:!0,pinConversation:!0,deleteConversation:!0,setConversationDraft:!0,setMessageRemindType:!0,getAllReceiveMessageOpt:!0,setAllReceiveMessageOpt:!0},Bn=new class{constructor(){this.name="Conversation"}install(e){M.init(e),wn.init(e),Fn.init(e),y.init(e),e.helper.registerValidateConfig({auth:Vn,params:xn})}},jn=new class{init(e){this.core=e}},Kn="AVChatRoom",Wn="GRP_COUNTER",Hn=["Type","Name","Introduction","Notification","FaceUrl","Owner_Account","CreateTime","InfoSeq","LastInfoTime","LastMsgTime","MemberNum","MaxMemberNum","ApplyJoinOption","NextMsgSeq","ShutUpAllMember","InviteJoinOption","LastRecallTime"],Yn=["Type","Name","Introduction","Notification","FaceUrl","CreateTime","Owner_Account","LastInfoTime","LastMsgTime","NextMsgSeq","MemberNum","MaxMemberNum","ApplyJoinOption","InviteJoinOption"],$n=["Role","JoinTime","MsgFlag","MsgSeq"],zn=["Role","JoinTime","MsgSeq","MsgFlag","NameCard"],Jn="notStart",Qn="resolved",Xn="rejected",Zn=["Owner","Admin","Member"],eo=["Role","JoinTime","NameCard","ShutUpUntil","OnlineStatus"],to={from:!0,groupID:!0,groupName:!0,to:!0},so={from:!0,groupID:!0,groupName:!0,to:!0,type:!0},ro=e=>e===jn.core.OuterConstant.GRP_PUBLIC,io=e=>e===jn.core.OuterConstant.GRP_AVCHATROOM,no=(r,e)=>{var t=jn.core.utils["isArray"];if(!t(r)||!t(e))return!1;let i=!1;return e.forEach(({key:t,value:e})=>{var s=r.find(e=>e.key===t);s?s.value!==e&&(s.value=e,i=!0):(r.push({key:t,value:e}),i=!0)}),i},oo=s=>{var r=[];if(s)for(let e=0,t=s.length;e<t;e++){var{Key:i,Value:n}=s[e];r.push({key:i,value:n})}return r},ao=s=>{var r=[];for(let e=0,t=s.length;e<t;e++){var{key:i,value:n}=s[e];r.push({Key:i,Value:n})}return r};function uo(e,t){var s=jn.core["helper"];if(!s.checkBusinessCapabilityBits(t))throw new s.ChatError({functionName:e,code:3122,replacement1:e})}function lo(e,t){var s=jn.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 co=["groupID","name","avatar","type","introduction","notification","ownerID","selfInfo","createTime","infoSequence","lastInfoTime","lastMessage","nextMessageSeq","memberCount","maxMemberCount","memberList","joinOption","groupCustomField","muteAllMembers","isSupportTopic","inviteOption","_lastRevokedTime","_groupAtInfoList"];class po{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}=jn.core["utils"];for(t in e)co.indexOf(t)<0||("selfInfo"!==t?"isSupportTopic"!==t?"muteAllMembers"===t&&s(e[t])?this.muteAllMembers="On"===e[t]:this[t]=e[t]:this.isSupportTopic=1===e[t]:this.updateSelfInfo(e[t]))}updateGroup(e){let{utils:{isArray:t,isUndefined:s,isNumber:r,isString:i},common:{deepMerge:n}}=jn.core;e.appid=void 0,e.grossTopicNextMsgSeq=void 0,e.selfInfo&&(e.selfInfo.grossTopicReadSeq=void 0);e=JSON.parse(JSON.stringify(e));e.lastMsgTime&&(this.lastMessage.lastTime=e.lastMsgTime),i(e.muteAllMembers)&&(e.muteAllMembers="On"===e.muteAllMembers),e.groupCustomField&&no(this.groupCustomField,e.groupCustomField),s(e.isSupportTopic)||(this.isSupportTopic=r(e.isSupportTopic)?1===e.isSupportTopic:e.isSupportTopic),n(this,e,["members","errorCode","lastMsgTime","groupCustomField","isSupportTopic"]),t(e.members)&&0<e.members.length&&e.members.forEach(e=>{e.userID===this.selfInfo.userID&&n(this.selfInfo,e,["sequence"])})}updateSelfInfo(e){var{nameCard:e,joinTime:t,role:s,messageRemindType:r,readedSequence:i,excludedUnreadSequenceList:n}=e,o=jn.core["common"]["deepMerge"];o(this.selfInfo,{nameCard:e,joinTime:t,role:s,messageRemindType:r,readedSequence:i,excludedUnreadSequenceList:n},[],["",null,void 0,0,NaN])}setSelfNameCard(e){this.selfInfo.nameCard=e}}var T=new class{constructor(){this._name="GroupDataHandler"}init(e){var e=(this._core=e)["appStore"]["groupStore"];this._groupMap=e.getGroupMap()}hasLocalGroup(e){return this._groupMap.has(e)}getLocalGroup(e){return this._groupMap.get(e)}updateLocalGroup(e){var{getCurrentUserID:t}=this._core["common"];let s;e.forEach(e=>{var t;s=e.groupID,this.hasLocalGroup(s)?null!=(t=this.getLocalGroup(s))&&t.updateGroup(e):this._groupMap.set(s,new po(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 ho(o,a){return I(this,void 0,void 0,function*(){var{type:e,limit:t,offset:s,supportTopic:r=0,memberAccount:i,responseFilter:n}=o;return a.common.buildAndSendPacket({servcmd:"group_open_http_svc.get_joined_group_list",data:{Type:e,Limit:t,Offset:s,Member_Account:i,ResponseFilter:n,SupportTopic:r,NeedAppDefineData:1}})})}function A(e,t){return{code:0,data:e||{},successLog:t}}var go=new class{constructor(){this._name="GetGroupList",this._pagingStatus=Jn,this.PAGING_GRP_COUNT_LIMIT=200}init(e){var{helper:e,constants:{WORKFLOW_NAME:t,WORKFLOW_STEP:s}}=this._core=e;e.registerApi({apiName:"getGroupList",context:this}),e.registerWorkflowStep(t.SYNC_SERVER_INFO_AFTER_LOGIN,s.GROUP_LIST_SYNC,this._syncGroupList,this)}getGroupList(){return I(this,arguments,void 0,function*(e=!1){if(e){let e=[];return yield this._pagingGetJoinedCommunityList({limit:this.PAGING_GRP_COUNT_LIMIT,offset:0,groupList:e}),T.updateLocalGroup(e),T.getLocalGroupList()}return this._core.ssoLog.debug("getGroupList",this._name+".getGroupList pagingStatus:"+this._pagingStatus),this._pagingStatus===Xn||this._pagingStatus===Jn?this._syncGroupList().then(()=>{var e=T.getLocalGroupList();return A({groupList:e,isSyncCompleted:this._isSyncCompleted()})}).catch(e=>{throw e}):(e=T.getLocalGroupList(),A({groupList:e,isSyncCompleted:this._isSyncCompleted()},{message:"return group count:"+e.length}))})}_syncGroupList(){return I(this,void 0,void 0,function*(){this._pagingStatus===Jn&&T.clearLocalGroup();var e=this.PAGING_GRP_COUNT_LIMIT,t=[];try{yield this._pagingGetGroupList({limit:e,offset:0,groupList:t}),this._pagingStatus=Qn,this._groupListTreeShaking(t),T.updateLocalGroup(t);var s=T.getLocalGroupList();return this._core.ssoLog.debug("_syncGroupList",this._name+"._syncGroupList ok, count:"+s.length),T.emitGroupListUpdate(),s}catch(e){throw this._pagingStatus=Xn,e}})}_pagingGetGroupList(e){return I(this,void 0,void 0,function*(){var i=this._core["ssoLog"],{isCommunityRelay:n=!1,groupList:o}=e;let a,{limit:u,offset:l}=e;var c=[...Hn];n&&(a=this._core.OuterConstant.GRP_COMMUNITY,c.push("AtInfoList"));try{let e=yield ho({type:a,limit:u,offset:l,memberAccount:this._core.store.get("login").userId,responseFilter:{GroupBaseInfoFilter:c,SelfInfoFilter:[...$n]}},this._core),{GroupIdList:t=[],TotalCount:s=0}=e||{},r=this._convertGroupKey(t);o.push(...r);var d=l+u,p=!(d<s),h=`offset:${l} limit:${u} total:${s} isCompleted:${p} current:${o.length} isCommunityRelay:`+n;return i.debug("_pagingGetGroupList",this._name+"._pagingGetGroupList ok. "+h),n?p?o:(l=d,this._pagingGetGroupList({isCommunityRelay:!0,limit:u,offset:l,groupList:o})):p?(i.debug("_pagingGetGroupList",this._name+"._pagingGetGroupList start to get community list"),l=0,this._pagingGetGroupList({isCommunityRelay:!0,limit:u,offset:l,groupList:o})):(l=d,this._pagingGetGroupList({limit:u,offset:l,groupList:o}))}catch(e){if(10018===e.ErrorCode)return i.warn("_pagingGetGroupList",this._name+"._pagingGetGroupList response size exceeds the limit, request count:"+u),this._pagingGetGroupList({isCommunityRelay:n,limit:50,offset:l,groupList:o});if(n)return 11e3===e.code&&i.debug("_pagingGetGroupList",this._name+"._pagingGetGroupList ok. community unavailable"),o;throw e}})}_pagingGetJoinedCommunityList(e){return I(this,void 0,void 0,function*(){var{common:{getCurrentUserID:i},OuterConstant:n,ssoLog:o}=this._core,a=e["groupList"];let{limit:u,offset:l}=e;try{let e=yield ho({limit:u,offset:l,type:n.GRP_COMMUNITY,memberAccount:i(),supportTopic:1,responseFilter:{GroupBaseInfoFilter:[...Hn],SelfInfoFilter:[...$n]}},this._core),{GroupIdList:t=[],TotalCount:s=0}=e||{},r=this._convertGroupKey(t);a.push(...r);var c=l+u,d=!(c<s),p=`offset:${l} limit:${u} total:${s} isCompleted:${d} current:`+a.length;return o.debug("_pagingGetJoinedCommunityList",this._name+"._pagingGetJoinedCommunityList ok. "+p),d?a:(l=c,this._pagingGetJoinedCommunityList({limit:u,offset:l,groupList:a}))}catch(e){if(10018===e.code)return o.warn("_pagingGetJoinedCommunityList",this._name+"._pagingGetJoinedCommunityList response size exceeds the limit, request count:"+u),this._pagingGetJoinedCommunityList({limit:50,offset:l,groupList:a});throw e}})}_groupListTreeShaking(s){var r=new Map([...T.getLocalGroupList()]);for(let e=0,t=s.length;e<t;e++)r.delete(s[e].groupID);var i=[...r.keys()];for(let e=0,t=i.length;e<t;e++)T.deleteLocalGroup(i[e])}_isSyncCompleted(){return this._pagingStatus===Qn}_convertGroupKey(s){var r=[];for(let e=0,t=s.length;e<t;e++){var{AppDefinedData:i,ApplyJoinOption:n,CreateTime:o,FaceUrl:a,GroupId:u,Introduction:l,InviteJoinOption:c,LastInfoTime:d,LastMsgTime:p,MemberNum:h,MaxMemberNum:g,MuteAllMember:_,Name:m,NextMsgSeq:v,Notification:f,Owner_Account:I,Type:E,LastRecallTime:C,SelfInfo:S,AtInfoList:M=[],SupportTopic:y}=s[e],i=oo(i),S=this._convertSelfInfo(S),M=this._convertAtInfoList(u,M);r.push({groupCustomField:i,joinOption:n,createTime:o,avatar:a,groupID:u,introduction:l,inviteOption:c,lastInfoTime:d,lastMsgTime:p,memberCount:h,maxMemberCount:g,muteAllMembers:_,name:m,nextMessageSeq:v,notification:f,ownerID:I,type:E,selfInfo:S,_lastRevokedTime:C,_groupAtInfoList:M,isSupportTopic:y})}return r}_convertSelfInfo(e){var{JoinTime:e,MsgFlag:t,MsgSeq:s,NoUnreadSeqList:r,Role:i}=e;return{joinTime:e,messageRemindType:t,readedSequence:s,excludedUnreadSequenceList:r,role:i}}_convertAtInfoList(r,e){if(0===e.length)return[];let i=[];return e.forEach(e=>{var{AtFlagList:e,AtMsgSeq:t,From_Account:s}=e;i.push({groupID:r,groupAtType:e,sequence:t,from:s})}),i}},_o=new class{constructor(){this._name="CreateGroup"}init(e){e=(this._core=e).helper;e.registerApi({apiName:"createGroup",context:this})}createGroup(u){return I(this,void 0,void 0,function*(){var o;this._preCheckParams(u);let e=this._core["helper"]["ChatError"];try{let{utils:{isEmpty:e},common:{getCurrentUserID:t}}=this._core,s=yield function(h,g){return I(this,void 0,void 0,function*(){var{name:e,type:t,groupID:s,introduction:r,notification:i,avatar:n,maxMemberNum:o,joinOption:a,inviteOption:u,memberList:l,groupCustomField:c,isSupportTopic:d}=h;let p;e={Name:e,Type:t,GroupId:s,Introduction:r,Notification:i,FaceUrl:n,MaxMemberCount:o,ApplyJoinOption:a,InviteJoinOption:u,MemberList:p=l?l.map(e=>{var{userID:e,memberCustomField:t}=e;return{Member_Account:e,AppMemberDefinedData:t?ao(t):void 0}}):p,AppDefinedData:c,SupportTopic:d,webPushFlag:1};return g.common.buildAndSendPacket({servcmd:"group_open_http_svc.create_group",data:e})})}(Object.assign(Object.assign({},u),{ownerID:t()}),this._core),{GroupId:r,OverJoinedGroupLimit_Account:i=[]}=s||{},n=`${this._name}.createGroup ok, type:${u.type} groupID:${r} overLimitUserIDList:`+i;e(u.memberList)||e(i)||(u.memberList=null==(o=u.memberList)?void 0:o.filter(e=>i.includes(e.userID))),T.updateLocalGroup([Object.assign(Object.assign({},u),{groupID:r})]);var a=T.getLocalGroup(r);return this._notNeedSendCustomMessage(u)||(this._sendCustomMessage(r,u.type),T.emitGroupListUpdate()),A({group:a},{message:n})}catch(o){var{errorCode:a,errorInfo:t}=o;throw new e({functionName:"createGroup",code:a,message:t,moreMessage:" groupID:"+u.groupID})}})}_preCheckParams(e){var{type:t,groupID:s}=e,{utils:{isEmpty:r,isUndefined:i},common:{isCommunity:n}}=this._core,r=!r(s);if(!(()=>{var{GRP_PUBLIC:e,GRP_WORK:t,GRP_MEETING:s,GRP_AVCHATROOM:r,GRP_COMMUNITY:i}=jn.core.OuterConstant;return[e,t,s,r,i]})().includes(t))throw new this._core.helper.ChatError({code:2600});if(!n({type:t})){if(r&&n({groupID:s}))throw new this._core.helper.ChatError({code:2602});i(e.isSupportTopic)||(e.isSupportTopic=void 0)}if(this._canIUseMemberList(t)||i(e.memberList)||(e.memberList=void 0),this._canIUseJoinOption(t)||i(e.joinOption)||(e.joinOption=void 0),n({type:t})){if(r&&!n({groupID:s}))throw new this._core.helper.ChatError({code:2602});e.isSupportTopic=this._canIUseTopic(e)?1:0}}_canIUseMemberList(e){return!io(e)}_canIUseJoinOption(e){return ro(e)||this._core.common.isCommunity({type:e})}_canIUseTopic(e){e=e.isSupportTopic;return!0===e}_notNeedSendCustomMessage(e){var{type:e,isSupportTopic:t}=e,{GRP_AVCHATROOM:s,GRP_COMMUNITY:r}=this._core["OuterConstant"];return e===s||e===r&&1===t}_sendCustomMessage(e,t){var s=this._core["OuterConstant"];let r="Create Group",i=0;t===s.GRP_COMMUNITY&&(r="Create Community",i=1);var t={to:e,conversationType:"GROUP",payload:{data:JSON.stringify({businessID:"group_create",content:r,cmd:i,opUser:this._core.store.get("login").userId,version:4})}},e=null==(s=null==(e=null==(s=this._core)?void 0:s.message)?void 0:e.messageFactory)?void 0:s.createCustomMessage(t);null!=(s=null==(t=null==(s=this._core)?void 0:s.message)?void 0:t.messageSender)&&s.sendMessage(e,{})}},O=new class{constructor(){this._name="AttributesDataHandler",this._groupAttributesCache=new Map,this._groupAttributesCacheValuesCopy={}}init(e){var{helper:e,constants:t}=this._core=e;e.registerWorkflowStep(t.WORKFLOW_NAME.SYNC_SERVER_INFO_AFTER_RE_ONLINE,t.WORKFLOW_STEP.GROUP_ATTRIBUTE_CACHE_CLEAR,this.clearLocalMainSequence,this)}clearLocalMainSequence(){this._groupAttributesCache.forEach(e=>{e.localMainSequence=0})}isGroupAttributesUpdated(e){var e=e["elements"]["newGroupProfile"],{isEmpty:t,isUndefined:s}=this._core["utils"];return!s(e)&&!t(e.groupAttributeOption)}handleGroupAttributesUpdated(e){var{groupID:e,groupAttributeOption:t}=e,{serverMainSequence:t,groupAttributeList:s=[],operation:r}=t,i=(this._core.ssoLog.debug("handleGroupAttributesUpdated",this._name+`.handleGroupAttributesUpdated groupID:${e} operation:`+r),this._core)["utils"]["isUndefined"];i(r)||(this.refreshGroupAttributesCache({groupID:e,serverMainSequence:t,groupAttributeList:s,operation:r}),this.emitGroupAttributesUpdated(e))}initGroupAttributesCache(e){var{groupID:e,avChatRoomKey:t}=e;this._groupAttributesCache.set(e,{lastUpdateTime:0,localMainSequence:0,serverMainSequence:0,avChatRoomKey:t,values:new Map}),this._core.ssoLog.debug("initGroupAttributesCache",this._name+`.initGroupAttributesCache. groupID:${e} avChatRoomKey:`+t)}hasGroupAttributesCache(e){return this._groupAttributesCache.has(e)}getGroupAttributesCache(e){return this.hasGroupAttributesCache(e)||this.initGroupAttributesCache({groupID:e}),this._groupAttributesCache.get(e)}deleteGroupAttributesCache(e){this.hasGroupAttributesCache(e)&&this._groupAttributesCache.delete(e)}refreshGroupAttributesCache(e){var{groupID:s,serverMainSequence:r,groupAttributeList:i,operation:n}=e;if(this.hasGroupAttributesCache(s)){let e=this.getGroupAttributesCache(s),t=e["localMainSequence"];5!==n&&r-t!=1||(e.serverMainSequence=r,e.localMainSequence=r,e.lastUpdateTime=Date.now(),this._updateGroupAttributesCacheValues({groupAttributes:e,groupAttributeList:i,operation:n})),1<r-t&&(e.serverMainSequence=r),this._groupAttributesCache.set(s,e),this._core.ssoLog.debug("refreshGroupAttributesCache",this._name+`.refreshGroupAttributesCache. operation:${n} localMainSequence:${t} serverMainSequence:`+r)}}_updateGroupAttributesCacheValues(e){let{groupAttributes:r,groupAttributeList:t=[],operation:s}=e;3!==s?4!==s?(1===s&&r.values.clear(),t.forEach(e=>{var{key:e,value:t,sequence:s}=e;r.values.set(e,{value:t,sequence:s})})):t.forEach(e=>{r.values.delete(e.key)}):r.values.clear()}getGroupAttributesCacheValues(e){let s,{groupID:r,keyList:i=[]}=e,n={};if(this.hasGroupAttributesCache(r)){let t=this.getGroupAttributesCache(r)["values"];if(0===i.length)for(let e of t.keys())n[e]=(null==(s=t.get(e))?void 0:s.value)||"";else i.forEach(e=>{t.has(e)&&(n[e]=(null==(e=t.get(e))?void 0:e.value)||"")})}return n}saveGroupAttributesCacheValuesCopy(e){this._groupAttributesCacheValuesCopy=this.getGroupAttributesCacheValues({groupID:e})}emitGroupAttributesUpdated(e){var t,s=this.getGroupAttributesCacheValues({groupID:e}),{updatedKeyList:r,deletedKeyList:i}=this._computeValuesChangedData(s);this._core.ssoLog.debug("emitGroupAttributesUpdated",`${this._name}.emitGroupAttributesUpdated update count:${r.length}, delete count:`+i.length),0===r.length&&0===i.length||this._emitEvent({name:null==(t=this._core)?void 0:t.OuterEvent.GROUP_ATTRIBUTES_UPDATED,data:{groupID:e,groupAttributes:s,updatedKeyList:r,deletedKeyList:i}})}_computeValuesChangedData(t){let{isUndefined:s}=this._core["utils"],r=[],i=[];return Object.keys(t).forEach(e=>{t[e]!==this._groupAttributesCacheValuesCopy[e]&&r.push(e)}),Object.keys(this._groupAttributesCacheValuesCopy).forEach(e=>{s(t[e])&&i.push(e)}),this._groupAttributesCacheValuesCopy={},{updatedKeyList:r,deletedKeyList:i}}_emitEvent(e){var t;null!=(t=this._core)&&t.notificationCenter.emitOuterEvent(e.name,e)}convertKeyValueMapToList(t){let s=[];return Object.keys(t).forEach(e=>{s.push({key:e,value:t[e]})}),s}reset(){this._groupAttributesCache.clear(),this._groupAttributesCacheValuesCopy={}}},mo=new class{constructor(){this._name="DismissGroup"}init(e,t){e=(this._core=e).helper;e.registerApi({apiName:"dismissGroup",context:this,matcher:()=>!t.getInstalledSubPlugins().includes(Kn)})}dismissGroup(i){return I(this,void 0,void 0,function*(){let{ChatError:t}=this._core["helper"];try{yield function(e,t){return I(this,void 0,void 0,function*(){return t.common.buildAndSendPacket({servcmd:"group_open_http_svc.destroy_group",data:{GroupId:e}})})}(i,this._core);let e=T.getLocalGroup(i)["type"];return T.deleteLocalGroup(i),T.emitGroupListUpdate(),O.deleteGroupAttributesCache(i),A({groupID:i,type:e},{message:i})}catch(e){var{errorCode:s,errorInfo:r}=e;throw new t({functionName:"dismissGroup",code:s,message:r})}})}},vo=new class{constructor(){this._name="GetGroupProfile"}init(e){e=(this._core=e).helper;e.registerApi({apiName:"getGroupProfile",context:this})}getGroupProfile(t){return I(this,void 0,void 0,function*(){let{groupID:i,groupCustomFieldFilter:e}=t,n={groupIDList:[i],responseFilter:{GroupBaseInfoFilter:[...Hn],AppDefinedDataFilter_Group:e,MemberInfoFilter:[...zn]}},{ChatError:r}=this._core["helper"];try{let e=yield this.getGroupProfileAdvance(n),{successGroupList:t,failureGroupList:s}=e;if(0<s.length)throw s[0];let r;return(r=!T.hasLocalGroup(i)&&io(t[0].type)?new po(t[0]):(T.updateLocalGroup(t),T.getLocalGroup(i))).isSupportTopic||T.updateConversationGroupProfile(i),A({group:r},{message:"groupID:"+i})}catch(e){let{code:t,message:s}=e;throw new r({functionName:"getGroupProfile",code:t,message:s})}})}getGroupProfileAdvance(a){return I(this,void 0,void 0,function*(){let e=a["groupIDList"],{isCommunity:t}=this._core["common"],s=e.filter(e=>!t({groupID:e})),r=e.filter(e=>t({groupID:e})),i=(50<s.length&&(s.length=50),50<r.length&&(r.length=50),yield Promise.all([this._getGroupProfileAdvance(Object.assign(Object.assign({},a),{groupIDList:s})),this._getGroupProfileAdvance(Object.assign(Object.assign({},a),{groupIDList:r,isCommunityProfile:!0}))])),n=[],o=[];return i.forEach(e=>{n.push(...e.successGroupList),o.push(...e.failureGroupList)}),{successGroupList:n,failureGroupList:o}})}_getGroupProfileAdvance(e){return I(this,void 0,void 0,function*(){let{ssoLog:n,utils:{isUndefined:o}}=this._core,{isCommunityProfile:t=!1}=e,a=f(e,["isCommunityProfile"]);if(0===a.groupIDList.length)return{successGroupList:[],failureGroupList:[]};try{let e=yield function(s,r){return I(this,void 0,void 0,function*(){var{groupIDList:e,responseFilter:t}=s;return r.common.buildAndSendPacket({servcmd:"group_open_http_svc.get_group_self_member_info",data:{GroupIdList:e,ResponseFilter:t}})})}(a,this._core),{GroupInfo:t=[]}=e||{},s=this._convertGroupProfileKey(t),r=s.filter(e=>o(e.errorCode)||0===e.errorCode),i=s.filter(e=>e.errorCode&&0!==e.errorCode).map(e=>({code:e.errorCode,message:e.errorInfo,data:{groupID:e.groupID}}));return n.debug("_getGroupProfileAdvance",this._name+"._getGroupProfileAdvance ok, groupID:"+a.groupIDList.join(",")),{successGroupList:r,failureGroupList:i}}catch(e){if(t)return{successGroupList:[],failureGroupList:[]};throw e}})}_convertGroupProfileKey(s){var r=[];for(let e=0,t=s.length;e<t;e++){var{AppDefinedData:i,ApplyJoinOption:n,CreateTime:o,FaceUrl:a,GroupId:u,InfoSeq:l,Introduction:c,InviteJoinOption:d,LastInfoTime:p,LastMsgTime:h,MaxMemberNum:g,MemberNum:_,MuteAllMember:m,Name:v,NextMsgSeq:f,Notification:I,Owner_Account:E,ShutUpAllMember:C,ShutUpUntil:S,Type:M,MemberList:y,ErrorCode:T,ErrorInfo:A}=s[e],i=oo(i),y=this._convertMembers(y);r.push({groupCustomField:i,joinOption:n,createTime:o,avatar:a,groupID:u,infoSequence:l,introduction:c,inviteOption:d,lastInfoTime:p,lastMsgTime:h,maxMemberCount:g,memberCount:_,muteAllMembers:m,name:v,nextMessageSeq:f,notification:I,ownerID:E,shutUpAllMember:C,muteUntil:S,type:M,members:y,errorCode:T,errorInfo:A})}return r}_convertMembers(s){if(!s)return[];var r=[];for(let e=0,t=s.length;e<t;e++){var{AppMemberDefinedData:i,JoinTime:n,Member_Account:o,MsgFlag:a,MsgSeq:u,NameCard:l,Role:c}=s[e],i=oo(i);r.push({memberCustomField:i,joinTime:n,userID:o,messageRemindType:a,sequence:u,nameCard:l,role:c})}return r}},fo=new class{constructor(){this._groupCountersMap=new Map}init(e){this._core=e}getLocalGroupCounters(e){return this._hasLocalGroupCounters(e)||this.initGroupCountersCache({groupID:e}),this._groupCountersMap.get(e)}updateLocalGroupCounters(e){var{groupID:r,counterList:i=[],groupCounterSeq:n}=e;if(this._hasLocalGroupCounters(r)){let{counters:s,avChatRoomKey:e,groupCounterSeq:t}=this.getLocalGroupCounters(r);0<n&&n<t||(i.forEach(e=>{var{Key:e,Value:t=0}=e;s.set(e,t)}),this._groupCountersMap.set(r,{lastUpdateTime:Date.now(),groupCounterSeq:n,counters:s,avChatRoomKey:e}))}}initGroupCountersCache(e){var{groupID:e,avChatRoomKey:t}=e;this._groupCountersMap.set(e,{lastUpdateTime:0,groupCounterSeq:0,counters:new Map,avChatRoomKey:t})}getLocalCounters(e,s){let r={};if(this._hasLocalGroupCounters(e)){let t=this.getLocalGroupCounters(e)["counters"];if(0<s.length)s.forEach(e=>{t.has(e)&&(r[e]=t.get(e))});else for(let e of t.keys())r[e]=t.get(e)}return r}deleteLocalGroupCounters(e){var{groupID:s,counterList:r=[],groupCounterSeq:i}=e;if(this._hasLocalGroupCounters(s)){let{counters:t,avChatRoomKey:e}=this.getLocalGroupCounters(s);r.forEach(e=>{t.delete(e.key)}),this._groupCountersMap.set(s,{lastUpdateTime:Date.now(),groupCounterSeq:i,counters:t,avChatRoomKey:e})}}setGroupCounters(t,i){if(this._hasLocalGroupCounters(t)){let e=this.getLocalGroupCounters(t),s=e["counters"],r=!1;Object.entries(i).forEach(([e,t])=>{s.has(e)&&s.get(e)!==t&&(s.set(e,t),r=!0)}),r&&this._groupCountersMap.set(t,Object.assign(Object.assign({},e),{lastUpdateTime:Date.now(),counters:s}))}}_hasLocalGroupCounters(e){return this._groupCountersMap.has(e)}reset(){this._groupCountersMap.clear()}},Io=new class{constructor(){this._name="JoinGroup"}init(e,t){e=(this._core=e).helper;e.registerApi({apiName:"joinGroup",context:this,matcher:()=>!t.getInstalledSubPlugins().includes(Kn)})}joinGroup(s){return I(this,void 0,void 0,function*(){let r=s["groupID"],{helper:{ChatError:i},OuterConstant:e,ssoLog:t}=this._core;try{if(T.hasLocalGroup(r))try{return yield vo.getGroupProfile({groupID:r}),A({status:e.JOIN_STATUS_ALREADY_IN_GROUP,group:T.getLocalGroup(r)},{message:`groupID:${r} joinedStatus:`+e.JOIN_STATUS_ALREADY_IN_GROUP})}catch(i){t.warn("joinGroup",this._name+`.joinGroup ${r} was unjoined, start to join!`),T.deleteLocalGroup(r)}return yield this._applyJoinGroup(s)}catch(e){let{errorCode:t,errorInfo:s}=e;throw new i({functionName:"joinGroup",code:t,message:s,moreMessage:"groupID:"+r})}})}_applyJoinGroup(p){return I(this,void 0,void 0,function*(){var{OuterConstant:e,helper:t,ssoLog:s}=this._core,r=p["groupID"],i=Object.assign({},p),t=t.checkBusinessCapabilityBits("AV_HISTORY_MSG"),i=(t&&(i.historyMessageFlag=1),yield function(r,i){return I(this,void 0,void 0,function*(){var{groupID:e,applyMessage:t,historyMessageFlag:s}=r;return i.common.buildAndSendPacket({servcmd:"group_open_http_svc.apply_join_group",data:{GroupId:e,ApplyMsg:t,HugeGroupHistoryMsgFlag:s}})})}(i,this._core)),{Type:i,JoinedStatus:n,LongPollingKey:o,StartSeq:a,HugeGroupFlag:u,AVChatRoomKey:l,RspMsgList:c=[]}=i||{},t=`groupID:${r} joinedStatus:${n} longPollingKey:${o} startSeq:${a} avChatRoomFlag:${u} canGetAVChatRoomHistoryMsg:${t}, historyMessageCount:`+c.length;s.debug("_applyJoinGroup",this._name+"._applyJoinGroup ok, "+t);let d=new po({groupID:r,type:i});if(n===e.JOIN_STATUS_WAIT_APPROVAL)return A({status:e.JOIN_STATUS_WAIT_APPROVAL,group:d});if(n!==e.JOIN_STATUS_SUCCESS)throw new this._core.helper.ChatError({code:2660});try{d=(yield vo.getGroupProfile({groupID:r})).data.group}catch(e){s.warn("_applyJoinGroup",this._name+`._applyJoinGroup getGroupProfile failed, groupID: ${r}, errorCode:`+(null==e?void 0:e.code))}return this._handleJoinResult({group:d,avChatRoomFlag:u,longPollingKey:o,startSequence:a,avChatRoomKey:l,historyMessageList:c})})}_handleJoinResult(e){var{group:t,avChatRoomFlag:s,avChatRoomKey:r}=e;return 1===s?(O.initGroupAttributesCache({groupID:t.groupID,avChatRoomKey:r}),fo.initGroupCountersCache({groupID:t.groupID,avChatRoomKey:r}),A(e)):(T.updateLocalGroup([t]),T.emitGroupListUpdate(),A({status:this._core.OuterConstant.JOIN_STATUS_SUCCESS,group:t},{message:"groupID:"+t.groupID}))}},Eo=new class{constructor(){this._name="QuitGroup"}init(e,t){e=(this._core=e).helper;e.registerApi({apiName:"quitGroup",context:this,matcher:()=>!t.getInstalledSubPlugins().includes(Kn)})}quitGroup(i){return I(this,void 0,void 0,function*(){if(!T.hasLocalGroup(i))throw new this._core.helper.ChatError({code:2623});let{ChatError:t}=this._core["helper"];try{yield function(e,t){return I(this,void 0,void 0,function*(){return t.common.buildAndSendPacket({servcmd:"group_open_http_svc.quit_group",data:{GroupId:e}})})}(i,this._core);let e=T.getLocalGroup(i)["type"];return T.deleteLocalGroup(i),T.emitGroupListUpdate(),O.deleteGroupAttributesCache(i),A({groupID:i,type:e},{message:"groupID:"+i})}catch(e){var{errorCode:s,errorInfo:r}=e;throw new t({functionName:"quitGroup",code:s,message:r,moreMessage:"groupID:"+i})}})}},Co=new class{constructor(){this._name="SearchGroup"}init(e){e=(this._core=e).helper;e.registerApi({apiName:"searchGroupByID",context:this})}searchGroupByID(v){return I(this,void 0,void 0,function*(){try{var t=yield function(t,s){return I(this,void 0,void 0,function*(){var e={GroupIdList:[t],GroupBasePublicInfoFilter:[...Yn]};return s.common.buildAndSendPacket({servcmd:"group_open_http_svc.get_group_public_info",data:e})})}(v,this._core),{GroupInfo:s=[]}=t||{},{AppDefinedData:e=[],ApplyJoinOption:r,CreateTime:i,FaceUrl:n,Introduction:o,InviteJoinOption:a,MaxMemberNum:u,MemberNum:l,Name:c,Owner_Account:d,Type:p,ErrorCode:h,ErrorInfo:g}=s[0];if(0!==h)throw new this._core.helper.ChatError({code:h,message:g});var _=oo(e),m=new po({groupID:v,name:c,avatar:n,introduction:o,joinOption:r,inviteOption:a,maxMemberCount:u,memberCount:l,type:p,ownerID:d,createTime:i,groupCustomField:_});return A({group:m})}catch(e){var{errorCode:t,errorInfo:s}=e;throw new this._core.helper.ChatError({functionName:"searchGroupByID",code:t,message:s})}})}},So=new class{constructor(){this._name="UpdateGroupProfile"}init(e){e=(this._core=e).helper;e.registerApi({apiName:"updateGroupProfile",context:this})}updateGroupProfile(o){return I(this,void 0,void 0,function*(){let r=o["groupID"],{utils:{isUndefined:t},ssoLog:s,helper:i}=this._core,n=T.getLocalGroup(r);if(n){let e=n["type"];this._canIUseJoinOption(e)||t(o.joinOption)||(s.warn("updateGroupProfile",this._name+`.updateGroupProfile groupID:${r} joinOption is unavailable for Work/Meeting/AVChatRoom`),o.joinOption=void 0)}t(o.muteAllMembers)||(o.muteAllMembers=!0===o.muteAllMembers?"On":"Off");try{return yield function(l,c){return I(this,void 0,void 0,function*(){var{groupID:e,name:t,avatar:s,introduction:r,notification:i,muteAllMembers:n,joinOption:o,inviteOption:a,groupCustomField:u}=l,e={GroupId:e,Name:t,FaceUrl:s,Introduction:r,Notification:i,ShutUpAllMember:n,ApplyJoinOption:o,InviteJoinOption:a,AppDefinedData:u?ao(u):void 0};return c.common.buildAndSendPacket({servcmd:"group_open_http_svc.modify_group_base_info",data:e})})}(o,this._core),n?(n.updateGroup(o),T.emitGroupListUpdate()):n=new po(o),A({group:n},{message:"groupID:"+r})}catch(e){let{errorCode:t,errorInfo:s}=e;throw new i.ChatError({code:t,message:s,moreMessage:"groupID:"+r})}})}_canIUseJoinOption(e){return ro(e)||this._core.common.isCommunity({type:e})}},Mo=new class{constructor(){this._name="ChangeGroupOwner"}init(e){e=(this._core=e).helper;e.registerApi({apiName:"changeGroupOwner",context:this})}changeGroupOwner(o){return I(this,void 0,void 0,function*(){var t="changeGroupOwner",{groupID:e,newOwnerID:s}=o,e=T.getLocalGroup(e),{helper:r,OuterConstant:i,common:{getCurrentUserID:n}}=this._core;if((null==e?void 0:e.type)===i.GRP_AVCHATROOM)throw new r.ChatError({functionName:t,code:2620});if(s===n())throw new r.ChatError({functionName:t,code:2621});try{return yield function(s,r){return I(this,void 0,void 0,function*(){var{groupID:e,newOwnerID:t}=s;return r.common.buildAndSendPacket({servcmd:"group_open_http_svc.change_group_owner",data:{GroupId:e,NewOwner_Account:t}})})}(o,this._core),e.ownerID=s,T.emitGroupListUpdate(),A({group:e})}catch(e){throw new r.ChatError({functionName:t,code:null==e?void 0:e.errorCode,message:null==e?void 0:e.errorInfo})}})}},yo=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(Kn)})}getGroupOnlineMemberCount(n){return I(this,void 0,void 0,function*(){let s="getGroupOnlineMemberCount";if(!T.hasLocalGroup(n))return A({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 A({memberCount:s})}try{let e=yield function(e,t){return I(this,void 0,void 0,function*(){return t.common.buildAndSendPacket({servcmd:"group_open_http_svc.get_online_member_num",data:{GroupId:e}})})}(n,this._core),{OnlineMemberNum:t=0}=e||{};this._onlineMemberCountMap.set(n,{lastReqTime:Date.now(),memberCount:t});var i=`${this._name}.${s} ok. groupID:${n} memberCount:`+t;return A({memberCount:t},{message:i})}catch(e){throw new this._core.helper.ChatError({functionName:s,code:null==e?void 0:e.errorCode,message:null==e?void 0:e.errorInfo})}})}},To=new class{init(e,t){e.ssoLog.debug("GroupAction.init"),go.init(e),_o.init(e),mo.init(e,t),Io.init(e,t),Eo.init(e,t),Co.init(e),vo.init(e),So.init(e),Mo.init(e),yo.init(e,t)}dismissGroup(e){return mo.dismissGroup(e)}joinGroup(e){return Io.joinGroup(e)}quitGroup(e){return Eo.quitGroup(e)}getGroupOnlineMemberCount(e){return yo.getGroupOnlineMemberCount(e)}},Ao=new class{constructor(){this._name="GetGroupApplicationList"}init(e){e=(this._core=e).helper;e.registerApi({apiName:"getGroupApplicationList",context:this})}getGroupApplicationList(){return I(this,void 0,void 0,function*(){var t="getGroupApplicationList";try{var e=yield Promise.all([this._getGroupApplicationList(),this._getGroupApplicationList({type:this._core.OuterConstant.GRP_COMMUNITY})]),s=(this._core.ssoLog.debug("getGroupApplicationList",this._name+`.${t} ok.`),this._handleGroupApplicationResult([...e[0],...e[1]]));return A({applicationList:s})}catch(e){throw new this._core.helper.ChatError({functionName:t,code:null==e?void 0:e.errorCode,message:null==e?void 0:e.errorInfo})}})}_getGroupApplicationList(n){return I(this,void 0,void 0,function*(){var{type:e,startTime:t=0,limit:s=20}=n||{},r=this._core["common"];let i;try{i=yield function(i,n){return I(this,void 0,void 0,function*(){var{type:e,startTime:t,limit:s,handleAccount:r}=i;return n.common.buildAndSendPacket({servcmd:"group_open_http_svc.get_pendency",data:{Type:e,StartTime:t,Limit:s,Handle_Account:r}})})}({type:e,startTime:t,limit:s,handleAccount:r.getCurrentUserID()},this._core)}catch(e){if(11e3!==(null==e?void 0:e.errorCode))throw e;i={}}var{NextStartTime:e=0,PendencyList:t=[]}=i||{};return 0===e?t:(s=yield this._getGroupApplicationList(Object.assign(Object.assign({},n),{startTime:e})),[...t,...s])})}_handleGroupApplicationResult(e){let s=[];return e.forEach(e=>{var e=this._convertApplicationData(e),t=e["handled"],e=f(e,["handled"]);0===t&&s.push(e)}),s}_convertApplicationData(e){var{Handled:e,AddTime:t,ApplyInviteMsg:s,Authentication:r,FromUserNickName:i,From_Account:n,GroupId:o,GroupName:a,PendencyType:u,To_Account:l}=e;return{handled:e,messageKey:t,applicant:n,applicantNick:i,groupID:o,groupName:a,authentication:r,applicationType:u,userID:l,note:s}}},Oo=new class{constructor(){this._name="HandleGroupApplication"}init(e){e=(this._core=e).helper;e.registerApi({apiName:"handleGroupApplication",context:this})}handleGroupApplication(e){return I(this,void 0,void 0,function*(){var t=e["application"],s=this._handleParams(e);try{2===(null==t?void 0:t.applicationType)?yield function(o,a){return I(this,void 0,void 0,function*(){var{groupID:e,handleAction:t,handleMessage:s,applicant:r,authentication:i,invitee:n}=o;return a.common.buildAndSendPacket({servcmd:"group_open_http_svc.handle_invite_join_permission_group",data:{GroupId:e,HandleMsg:t,ApprovalMsg:s,Applicant_Account:r,Authentication:i,Invited_Account:n}})})}(s,this._core):yield function(o,a){return I(this,void 0,void 0,function*(){var{groupID:e,handleAction:t,handleMessage:s,applicant:r,authentication:i,messageKey:n}=o;return a.common.buildAndSendPacket({servcmd:"group_open_http_svc.handle_apply_join_group",data:{GroupId:e,HandleMsg:t,ApprovalMsg:s,Applicant_Account:r,Authentication:i,MsgKey:n}})})}(s,this._core);let e=T.getLocalGroup(s.groupID);return A({group:e})}catch(e){throw new this._core.helper.ChatError({functionName:"handleGroupApplication",code:null==e?void 0:e.errorCode,message:null==e?void 0:e.errorInfo})}})}_handleParams(e){var{handleAction:e,handleMessage:t,message:s,application:r}=e;let i,n,o,a,u;if(s){let e=(s||{})["payload"];i=e.operatorID,n=null==(s=e.groupProfile)?void 0:s.groupID,o=e.authentication,a=e.messageKey}else i=(null==r?void 0:r.applicant)||"",n=(null==r?void 0:r.groupID)||"",o=(null==r?void 0:r.authentication)||"",a=(null==r?void 0:r.messageKey)||0;return 2===(null==r?void 0:r.applicationType)&&(u=r.userID),{handleAction:e,handleMessage:t,applicant:i,invitee:u,groupID:n,authentication:o,messageKey:a}}},Do=new class{init(e){e.ssoLog.debug("GroupApplication.init"),Ao.init(e),Oo.init(e)}};let Ro=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}}=jn["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&&no(this.memberCustomField,e.memberCustomField),s(this,e,["memberCustomField","marks","onlineStatus","muteTime"],t)}};function Lo(a,u){return I(this,void 0,void 0,function*(){var{groupID:e,userID:t,muteTime:s,role:r,nameCard:i,memberCustomField:n}=a;let o;e={GroupId:e,Member_Account:t,ShutUpTime:s,Role:r,NameCard:i,AppMemberDefinedData:o=n?ao(n):o};return u.common.buildAndSendPacket({servcmd:"group_open_http_svc.modify_group_member_info",data:e})})}var No=new class{constructor(){this._name="GetGroupMemberList"}init(e,t){e=(this._core=e).helper;e.registerApi({apiName:"getGroupMemberList",context:this,matcher:()=>!t.getInstalledSubPlugins().includes(Kn)})}getGroupMemberList(r){return I(this,void 0,void 0,function*(){let l="getGroupMemberList",{groupID:c,offset:d=0,count:e=100,role:t="",filter:s=""}=r,p=T.getLocalGroup(c),h=100<e?100:e,g={groupID:c,offset:d,limit:h,memberRoleFilter:Zn.includes(t)?[t]:void 0,memberInfoFilter:eo};try{let e=yield function(n,o){return I(this,void 0,void 0,function*(){var{groupID:e,offset:t,limit:s,memberRoleFilter:r,memberInfoFilter:i}=n;return o.common.buildAndSendPacket({servcmd:"group_open_http_svc.get_group_member_info",data:{GroupId:e,Offset:t,Limit:s,MemberRoleFilter:r,MemberInfoFilter:i}})})}(g,this._core),{MemberList:t,MemberNum:s,Next:r}=e||{},i=`${this._name}.${l} ok, totalMemberCount:${s} next:`+r,{utils:{isArray:n,isEmpty:o},common:{isCommunity:a}}=this._core;if(p&&(p.memberCount=s),!n(t)||0===t.length)return A({memberList:[],offset:0},{message:i});let u=d+h;a({groupID:c})&&(u=o(r)?0:r),t.length<h&&(u=0);var _=this._convertMemberInfo(t),_=yield this._patchAvatarAndNick(_),m=this._generateGroupMember(_);return A({memberList:m,offset:u},{message:i})}catch(e){throw new this._core.helper.ChatError({functionName:l,code:null==e?void 0:e.errorCode,message:null==e?void 0:e.errorInfo})}})}_convertMemberInfo(s){var r=[];for(let e=0,t=s.length;e<t;e++){var{AppMemberDefinedData:i,JoinTime:n,Member_Account:o,OnlineStatus:a,Role:u,ShutUpUntil:l,NameCard:c}=s[e],i=oo(i);r.push({userID:o,joinTime:n,onlineStatus:a,role:u,muteUntil:l,memberCustomField:i,nameCard:c})}return r}_patchAvatarAndNick(n){return I(this,void 0,void 0,function*(){let e,t=n.map(e=>e.userID),s=yield null==(e=this._core.user.userProfile)?void 0:e.getUserProfile({userIDList:t}),r=(null==s?void 0:s.data)||[],i=new Map(r.map(e=>[e.userID,e]));return n.forEach(e=>{var t,s;i.has(e.userID)&&({nick:t="",avatar:s=""}=i.get(e.userID),e.nick=t,e.avatar=s)}),n})}_generateGroupMember(s){var r=[];for(let e=0,t=s.length;e<t;e++){var i=new Ro(s[e]);r.push(i)}return r}},bo=new class{constructor(){this._name="GetGroupMemberProfile"}init(e){e=(this._core=e).helper;e.registerApi({apiName:"getGroupMemberProfile",context:this})}getGroupMemberProfile(c){return I(this,void 0,void 0,function*(){let t="getGroupMemberProfile",{groupID:r,userIDList:i,memberCustomFieldFilter:n}=c,e=T.getLocalGroup(r),{helper:s,utils:{isArray:o},ssoLog:a}=this._core;if(e&&io(e.type))throw new s.ChatError({functionName:t,replacement1:t,code:2687});50<i.length&&(a.warn("getGroupMemberProfile",`${this._name}.${t} userIDList length:${i.length} exceeds limit 50`),i.splice(50));var u=`userIDList length:${i.length} groupID:`+r;try{let e=yield function(i,n){return I(this,void 0,void 0,function*(){var{groupID:e,userIDList:t,memberInfoFilter:s,memberCustomFieldFilter:r}=i;return n.common.buildAndSendPacket({servcmd:"group_open_http_svc.get_specified_group_member_info",data:{GroupId:e,Member_List_Account:t,MemberInfoFilter:s,AppDefinedDataFilter_GroupMember:r}})})}({groupID:r,userIDList:i,memberCustomFieldFilter:n,memberInfoFilter:[...eo]},this._core),t=(e||{})["MemberList"];if(!o(t)||0===t.length)return A({memberList:[]});var l=this._convertMemberInfo(t),l=yield this._getMemberAvatarAndNick(l);let s=this._generateGroupMember(l);return A({memberList:s},{message:u})}catch(e){throw new s.ChatError({functionName:t,code:null==e?void 0:e.errorCode,message:null==e?void 0:e.errorInfo,moreMessage:u})}})}_convertMemberInfo(s){var r=[];for(let e=0,t=s.length;e<t;e++){var{AppMemberDefinedData:i,JoinTime:n,Member_Account:o,OnlineStatus:a,Role:u,ShutUpUntil:l,NameCard:c}=s[e],i=oo(i);r.push({userID:o,joinTime:n,onlineStatus:a,role:u,muteUntil:l,memberCustomField:i,nameCard:c})}return r}_getMemberAvatarAndNick(n){return I(this,void 0,void 0,function*(){let e,t=n.map(e=>e.userID),s=yield null==(e=this._core.user.userProfile)?void 0:e.getUserProfile({userIDList:t}),r=(null==s?void 0:s.data)||[],i=new Map(r.map(e=>[e.userID,e]));return n.forEach(e=>{var t,s;i.has(e.userID)&&({nick:t="",avatar:s=""}=i.get(e.userID),e.nick=t,e.avatar=s)}),n})}_generateGroupMember(s){var r=[];for(let e=0,t=s.length;e<t;e++){var i=new Ro(s[e]);r.push(i)}return r}},Go=new class{constructor(){this._name="AddGroupMember"}init(e){e=(this._core=e).helper;e.registerApi({apiName:"addGroupMember",context:this})}addGroupMember(r){return I(this,void 0,void 0,function*(){let t="addGroupMember",{groupID:o,userIDList:e}=r,a=T.getLocalGroup(o),s=this._core["helper"];if(a&&io(a.type))throw new s.ChatError({functionName:t,code:2661});var u=e.map(e=>({Member_Account:e}));try{let e=yield function(s,r){return I(this,void 0,void 0,function*(){var{groupID:e,userIDList:t}=s;return r.common.buildAndSendPacket({servcmd:"group_open_http_svc.add_group_member",data:{GroupId:e,MemberList:t}})})}({groupID:o,userIDList:u},this._core),{MemberList:t=[]}=e||{},{failureUserIDList:s,successUserIDList:r,existedUserIDList:i,overLimitUserIDList:n}=this._handleResult(t);return A({failureUserIDList:s,successUserIDList:r,existedUserIDList:i,overLimitUserIDList:n,group:a},{message:` groupID:${o} successUserIDList:${r} failureUserIDList:${s} existedUserIDList:${i} overLimitUserIDList:`+n})}catch(e){throw new s.ChatError({functionName:t,code:null==e?void 0:e.errorCode,message:null==e?void 0:e.errorInfo})}})}_handleResult(e){let s=[],r=[],i=[],n=[];return e.forEach(e=>{var{Result:e,Member_Account:t}=e;0===e?s.push(t):1===e?r.push(t):2===e?i.push(t):4===e&&n.push(t)}),{failureUserIDList:s,successUserIDList:r,existedUserIDList:i,overLimitUserIDList:n}}},Po=new class{constructor(){this._name="DeleteGroupMember"}init(e,t){e=(this._core=e).helper;e.registerApi({apiName:"deleteGroupMember",context:this,matcher:()=>!t.getInstalledSubPlugins().includes(Kn)})}deleteGroupMember(a){return I(this,void 0,void 0,function*(){var t="deleteGroupMember",{groupID:e,userIDList:s}=a,r=T.getLocalGroup(e),{helper:i,utils:{isUndefined:n},ssoLog:o}=this._core;if(n(r))throw new i.ChatError({functionName:t,code:2603});20<s.length&&(o.warn("deleteGroupMember",`${this._name}.${t} userIDList length:${s.length} exceeds limit 20`),s.splice(20));try{return yield function(r,i){return I(this,void 0,void 0,function*(){var{groupID:e,userIDList:t,reason:s}=r;return i.common.buildAndSendPacket({servcmd:"group_open_http_svc.delete_group_member",data:{GroupId:e,MemberToDel_Account:t,Reason:s}})})}({groupID:e,userIDList:s},this._core),A({group:r,userIDList:s},{message:`groupID:${e} userIDList length:`+s.length})}catch(e){throw new i.ChatError({functionName:t,code:null==e?void 0:e.errorCode,message:null==e?void 0:e.errorInfo})}})}},wo=new class{constructor(){this._name="SetGroupMemberMuteTime"}init(e){e=(this._core=e).helper;e.registerApi({apiName:"setGroupMemberMuteTime",context:this})}setGroupMemberMuteTime(o){return I(this,void 0,void 0,function*(){let t=this._core["helper"],{groupID:s,userID:r,muteTime:i}=o,n=` groupID:${s} userID:${r} muteTime:`+i;this._preCheckSettingMuteParams(o);try{yield Lo(o,this._core);let e=T.getLocalGroup(s),t=new Ro({userID:r,muteTime:i});return A({group:e,member:t},{message:n})}catch(e){throw new t.ChatError({functionName:"setGroupMemberMuteTime",code:null==e?void 0:e.errorCode,message:null==e?void 0:e.errorInfo,moreMessage:n})}})}_preCheckSettingMuteParams(e){var e=e["userID"],{store:t,helper:s}=this._core;if(e===t.get("login").userId)throw new s.ChatError({functionName:"setGroupMemberMuteTime",code:2685})}},Uo=new class{constructor(){this._name="SetGroupMemberRole"}init(e){e=(this._core=e).helper;e.registerApi({apiName:"setGroupMemberRole",context:this})}setGroupMemberRole(a){return I(this,void 0,void 0,function*(){let t="setGroupMemberRole",s=this._core["helper"],{groupID:r,userID:i,role:n}=a,o=`${this._name}.${t} ok, groupID:${r} userID:${i} role:`+n;this._preCheckSettingRoleParams(a);try{yield Lo(a,this._core);let e=T.getLocalGroup(r),t=new Ro({userID:i,role:n});return A({group:e,member:t},{message:o})}catch(e){throw new s.ChatError({functionName:t,code:null==e?void 0:e.errorCode,message:null==e?void 0:e.errorInfo,moreMessage:o})}})}_preCheckSettingRoleParams(e){var{groupID:e,userID:t,role:s}=e,{store:r,helper:i,OuterConstant:n,common:{isCommunity:o}}=this._core,a=T.getLocalGroup(e);if((null==(a=null==a?void 0:a.selfInfo)?void 0:a.role)!==n.GRP_MBR_ROLE_OWNER)throw new i.ChatError({functionName:"setGroupMemberRole",code:2681});if(t===r.get("login").userId)throw new i.ChatError({functionName:"setGroupMemberRole",code:2684});a=[...Zn];if(o({groupID:e})&&a.push(n.GRP_MBR_ROLE_CUSTOM),!a.includes(s))throw new i.ChatError({functionName:"setGroupMemberRole",code:2683})}},ko=new class{constructor(){this._name="SetGroupMemberNameCard"}init(e){e=(this._core=e).helper;e.registerApi({apiName:"setGroupMemberNameCard",context:this})}setGroupMemberNameCard(l){return I(this,void 0,void 0,function*(){let i="setGroupMemberNameCard",{helper:t,common:{getCurrentUserID:n}}=this._core;this._preCheckSettingNameCardParams(l);try{let{groupID:e,userID:t=n(),nameCard:s}=l,r={groupID:e,userID:t,nameCard:s};yield Lo(r,this._core);var o=`${this._name}.${i} ok, groupID:${e} userID:${t} nameCard:`+s,a=T.getLocalGroup(e),u=new Ro({userID:t,nameCard:s});return A({group:a,member:u},{message:o})}catch(e){throw new t.ChatError({functionName:i,code:null==e?void 0:e.errorCode,message:null==e?void 0:e.errorInfo,moreMessage:logText})}})}_preCheckSettingNameCardParams(e){var e=e["groupID"],t=this._core["helper"],e=T.getLocalGroup(e);if(io(null==e?void 0:e.type))throw new t.ChatError({functionName:"setGroupMemberNameCard",code:2687})}},Fo=new class{constructor(){this._name="SetGroupMemberCustomField"}init(e){e=(this._core=e).helper;e.registerApi({apiName:"setGroupMemberCustomField",context:this})}setGroupMemberCustomField(a){return I(this,void 0,void 0,function*(){let t="setGroupMemberCustomField",{helper:s,common:{getCurrentUserID:e}}=this._core;this._preCheckSettingCustomFiledParams(a);var{groupID:r,userID:i=e(),memberCustomField:n}=a,o=`${this._name}.${t} ok, groupID:${r}userID:${i} memberCustomField:`+JSON.stringify(n);try{let e={groupID:r,userID:i,memberCustomField:n},t=(yield Lo(e,this._core),T.getLocalGroup(r)),s=new Ro({userID:i,memberCustomField:n});return A({group:t,member:s},{message:o})}catch(e){throw new s.ChatError({functionName:t,code:null==e?void 0:e.errorCode,message:null==e?void 0:e.errorInfo,moreMessage:o})}})}_preCheckSettingCustomFiledParams(e){var e=e["groupID"],t=this._core["helper"],e=T.getLocalGroup(e);if(io(null==e?void 0:e.type))throw new t.ChatError({functionName:"setGroupMemberCustomField",code:2687})}},qo=new class{init(e,t){e.ssoLog.debug("GroupMember.init"),No.init(e,t),bo.init(e),Go.init(e),Po.init(e,t),wo.init(e),Uo.init(e),ko.init(e),Fo.init(e)}getGroupMemberList(e){return No.getGroupMemberList(e)}deleteGroupMember(e){return Po.deleteGroupMember(e)}},xo=new class{init(e){e=(this._core=e).helper;e.registerApi({apiName:"getGroupCounters",context:this})}getGroupCounters(u){return I(this,void 0,void 0,function*(){var t="getGroupCounters";try{uo(t,Wn);var e,s,r,{groupID:i,keyList:n=[]}=u,{avChatRoomKey:o,lastUpdateTime:a}=fo.getLocalGroupCounters(i);return Date.now()-a>=this._getExpireTime()&&(e=yield function(i){return I(this,void 0,void 0,function*(){var{groupID:e,GroupCounterKeys:t,avChatRoomKey:s}=i,r=jn.core["common"];return r.buildAndSendPacket({servcmd:"group_open_http_svc.get_group_counter",data:{GroupId:e,keyList:t,BytesKey:s}})})}({groupID:i,keyList:n,avChatRoomKey:o}),{GroupCounter:s=[],GroupCounterSeq:r}=e,fo.updateLocalGroupCounters({groupID:i,counterList:s,groupCounterSeq:r})),{code:0,data:{counters:fo.getLocalCounters(i,n)}}}catch(e){lo(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)}},Vo=new class{init(e){e=e.helper;e.registerApi({apiName:"setGroupCounters",context:this}),e.registerApi({apiName:"increaseGroupCounter",context:this}),e.registerApi({apiName:"decreaseGroupCounter",context:this})}setGroupCounters(e){return I(this,void 0,void 0,function*(){return this._handleCounterOperation("Set",e)})}increaseGroupCounter(e){return I(this,void 0,void 0,function*(){return this._handleCounterOperation("Increase",e)})}decreaseGroupCounter(e){return I(this,void 0,void 0,function*(){return this._handleCounterOperation("Decrease",e)})}_handleCounterOperation(a,u){return I(this,void 0,void 0,function*(){var t=a+"GroupCounter";try{uo(t,Wn);var{groupID:e,key:s,value:r=0}=u,i=fo.getLocalGroupCounters(e)["avChatRoomKey"],n="Set"===a?this._convertObjectToList(u.counters):[{Key:s,Value:r}],o=yield this._updateGroupCounters({groupID:e,counterList:n,avChatRoomKey:i,mode:a});return fo.setGroupCounters(e,o),{code:0,data:{counters:o}}}catch(e){lo(t,e)}})}_updateGroupCounters(n){return I(this,void 0,void 0,function*(){let e=yield function(){var{groupID:e,counterList:t,mode:s,avChatRoomKey:r}=n,i=jn.core["common"];return i.buildAndSendPacket({servcmd:"group_open_http_svc.update_group_counter",data:{GroupId:e,GroupCounter:t,Mode:s,BytesKey:r}})}(),{GroupCounter:t=[]}=e,s={};return t.forEach(e=>{var{Key:e,Value:t=0}=e;s[e]=t}),s})}_convertObjectToList(e){return Object.entries(e).map(([e,t])=>({Key:e,Value:t||0}))}},Bo=new class{init(e){this._core=e,xo.init(e),Vo.init(e)}isGroupCounterUpdated(e){var e=e["elements"]["groupCounterInfo"],t=this._core["utils"]["isEmpty"];return!t(e)}handleGroupCounterUpdated(e){let{to:r,elements:{groupCounterInfo:t}}=e;t.forEach(e=>{var{type:e,groupCounterSeq:t,counterList:s=[]}=e;0!==e&&2!==e||this._processAndNotifyCounterUpdate(r,t,s),1===e&&fo.deleteLocalGroupCounters({groupID:r,groupCounterSeq:t,counterList:s})})}_processAndNotifyCounterUpdate(s,e,t){let{OuterEvent:r,notificationCenter:i}=this._core;fo.updateLocalGroupCounters({groupID:s,groupCounterSeq:e,counterList:t}),t.forEach(({Key:e,Value:t=0})=>{i.emitOuterEvent(r.GROUP_COUNTER_UPDATED,{name:r.GROUP_COUNTER_UPDATED,data:{groupID:s,key:e,value:t}})})}reset(){fo.reset()}},jo=new class{constructor(){this._name="InitGroupAttributes"}init(e){e=(this._core=e).helper;e.registerApi({apiName:"initGroupAttributes",context:this})}initGroupAttributes(e){return I(this,void 0,void 0,function*(){let{groupID:i,groupAttributes:n}=e,{serverMainSequence:o,avChatRoomKey:a}=O.getGroupAttributesCache(i),u=O.convertKeyValueMapToList(n);try{let e=yield function(i,n){return I(this,void 0,void 0,function*(){var{groupID:e,mainSequence:t,groupAttributeList:s,avChatRoomKey:r}=i;return n.common.buildAndSendPacket({servcmd:"group_open_http_svc.set_group_attr",data:{GroupId:e,AttrMainSeq:t,GroupAttr:s,BytesKey:r,AttrControl:["RaceConflict"]}})})}({groupID:i,avChatRoomKey:a,groupAttributeList:u,mainSequence:o},this._core),{AttrMainSeq:t,GroupAttr:s}=e||{},r=s.map(e=>{var{Key:e,seq:t}=e;return{key:e,value:n[e],sequence:t}});return O.saveGroupAttributesCacheValuesCopy(i),O.refreshGroupAttributesCache({groupID:i,serverMainSequence:t,groupAttributeList:r,operation:1}),O.emitGroupAttributesUpdated(i),A({groupAttributes:n},{message:` groupID:${i} serverMainSequence:`+t})}catch(e){throw new this._core.helper.ChatError({functionName:"initGroupAttributes",code:null==e?void 0:e.errorCode,message:null==e?void 0:e.errorInfo})}})}},Ko=new class{constructor(){this._name="SetGroupAttributes"}init(e){e=(this._core=e).helper;e.registerApi({apiName:"setGroupAttributes",context:this})}setGroupAttributes(e){return I(this,void 0,void 0,function*(){let{groupID:i,groupAttributes:n}=e,{serverMainSequence:o,avChatRoomKey:a,values:r}=O.getGroupAttributesCache(i),u=O.convertKeyValueMapToList(n).map(e=>{var{key:t,value:s}=e;return{key:t,value:s,seq:(null==(t=r.get(e.key))?void 0:t.sequence)||0}});try{let e=yield function(i,n){return I(this,void 0,void 0,function*(){var{groupID:e,mainSequence:t,groupAttributeList:s,avChatRoomKey:r}=i;return n.common.buildAndSendPacket({servcmd:"group_open_http_svc.modify_group_attr",data:{GroupId:e,AttrMainSeq:t,GroupAttr:s,BytesKey:r,AttrControl:["RaceConflict"]}})})}({groupID:i,avChatRoomKey:a,groupAttributeList:u,mainSequence:o},this._core),{AttrMainSeq:t,GroupAttr:s}=e||{},r=s.map(e=>{var{Key:e,seq:t}=e;return{key:e,value:n[e],sequence:t}});return O.saveGroupAttributesCacheValuesCopy(i),O.refreshGroupAttributesCache({groupID:i,serverMainSequence:t,groupAttributeList:r,operation:2}),O.emitGroupAttributesUpdated(i),A({groupAttributes:n},{message:` groupID:${i} serverMainSequence:`+t})}catch(e){throw new this._core.helper.ChatError({functionName:"setGroupAttributes",code:null==e?void 0:e.errorCode,message:null==e?void 0:e.errorInfo})}})}},Wo=new class{constructor(){this._name="DeleteGroupAttributes"}init(e){e=(this._core=e).helper;e.registerApi({apiName:"deleteGroupAttributes",context:this})}deleteGroupAttributes(u){return I(this,void 0,void 0,function*(){var t="deleteGroupAttributes",{groupID:e,keyList:s=[]}=u;try{var{resultList:r,serverMainSequence:i,operation:n,groupAttributeList:o}=(0===s.length?yield this._clearGroupAttributes(e):yield this._deleteGroupAttributes(e,s))||{},a=this._name+`.${t} ok. groupID:${e} operation: `+n;return O.saveGroupAttributesCacheValuesCopy(e),O.refreshGroupAttributesCache({groupID:e,serverMainSequence:i,groupAttributeList:o,operation:n}),O.emitGroupAttributesUpdated(e),A({keyList:r},{message:a})}catch(e){throw new this._core.helper.ChatError({functionName:t,code:null==e?void 0:e.errorCode,message:null==e?void 0:e.errorInfo})}})}_deleteGroupAttributes(o,a){return I(this,void 0,void 0,function*(){let{serverMainSequence:e,avChatRoomKey:t,values:s}=O.getGroupAttributesCache(o),r=[],i=[];a.forEach(e=>{var t;s.has(e)&&({sequence:t=0}=s.get(e)||{},i.push({key:e,seq:t}),r.push(e))});var n=((yield function(i,n){return I(this,void 0,void 0,function*(){var{groupID:e,mainSequence:t,groupAttributeList:s,avChatRoomKey:r}=i;return n.common.buildAndSendPacket({servcmd:"group_open_http_svc.delete_group_attr",data:{GroupId:e,AttrMainSeq:t,GroupAttr:s,BytesKey:r,AttrControl:["RaceConflict"]}})})}({groupID:o,avChatRoomKey:t,groupAttributeList:i,mainSequence:e},this._core))||{})["AttrMainSeq"];return{resultList:r,serverMainSequence:n,groupAttributeList:i,operation:4}})}_clearGroupAttributes(r){return I(this,void 0,void 0,function*(){var{serverMainSequence:e,avChatRoomKey:t,values:s}=O.getGroupAttributesCache(r),s=[...s.keys()],t=((yield function(r,i){return I(this,void 0,void 0,function*(){var{groupID:e,mainSequence:t,avChatRoomKey:s}=r;return i.common.buildAndSendPacket({servcmd:"group_open_http_svc.clear_group_attr",data:{GroupId:e,AttrMainSeq:t,BytesKey:s,AttrControl:["RaceConflict"]}})})}({groupID:r,avChatRoomKey:t,mainSequence:e},this._core))||{})["AttrMainSeq"];return{resultList:s,serverMainSequence:t,operation:3}})}},Ho=new class{constructor(){this._name="GetGroupAttributes"}init(e){e=(this._core=e).helper;e.registerApi({apiName:"getGroupAttributes",context:this})}getGroupAttributes(u){return I(this,void 0,void 0,function*(){let r=u["groupID"],{avChatRoomKey:i,lastUpdateTime:e,localMainSequence:t,serverMainSequence:s}=O.getGroupAttributesCache(r),{ChatError:n}=this._core["helper"],o=`groupID:${r} localMainSequence:${t} serverMainSequence:${s} keyList:`+u.keyList;if(3e4<=Date.now()-e||t<s)try{let e=yield this.getGroupAttributesFromServer({groupID:r,avChatRoomKey:i}),t=O.getGroupAttributesCacheValues(u),{serverGroupAttributeList:s=[]}=e||{};return A({groupAttributes:t},{message:o,moreMessage:"from server, count:"+s.length})}catch(e){throw new n({functionName:"getGroupAttributes",code:null==e?void 0:e.errorCode,message:null==e?void 0:e.errorInfo})}var a=O.getGroupAttributesCacheValues(u);return A({groupAttributes:a},{message:o,moreMessage:"from cache"})})}getGroupAttributesFromServer(i){return I(this,void 0,void 0,function*(){var{utils:{isUndefined:e},ssoLog:t}=this._core,{groupID:s,avChatRoomKey:r}=i,{AttrMainSeq:e=0,GroupAttrAry:r}=(yield function(r,i){return I(this,void 0,void 0,function*(){var{groupID:e,groupType:t,avChatRoomKey:s}=r;return i.common.buildAndSendPacket({servcmd:"group_open_attr_http_svc.get_group_attr",data:{GroupId:e,GroupType:t,Key:s}})})}({groupID:s,avChatRoomKey:r,groupType:e(r)?0:1},this._core))||{},t=(t.debug("getGroupAttributesFromServer",this._name+`._getGroupAttributesFromServer ok. groupID:${s} serverMainSequence:`+e),r.map(e=>{var{key:e,value:t,seq:s}=e;return{key:e,value:t,sequence:s}}));return O.refreshGroupAttributesCache({groupID:s,serverMainSequence:e,groupAttributeList:t,operation:5}),{serverGroupAttributeList:r}})}},Yo=new class{init(e){e.ssoLog.debug("GroupAttribute.init"),jo.init(e),Ko.init(e),Wo.init(e),Ho.init(e),O.init(e)}isGroupAttributesUpdated(e){return O.isGroupAttributesUpdated(e)}handleGroupAttributesUpdated(e){let{to:t,elements:{newGroupProfile:s}}=e,r=s["groupAttributeOption"],{serverMainSequence:i,withChangedAttributeInfo:n}=r,o=O.getGroupAttributesCache(t)["localMainSequence"],a=i-o;if(console.log(`GroupAttribute.handleGroupAttributesUpdated groupID:${t} withChangedAttributeInfo:${n} diffSequence:`+a),0!=a)if(O.saveGroupAttributesCacheValuesCopy(t),1!==n||1!=a){if(O.hasGroupAttributesCache(t)){let e=O.getGroupAttributesCache(t)["avChatRoomKey"];Ho.getGroupAttributesFromServer({groupID:t,avChatRoomKey:e}).then(()=>{O.emitGroupAttributesUpdated(t)}).catch(()=>{})}}else O.handleGroupAttributesUpdated({groupID:t,groupAttributeOption:r})}reset(){O.reset()}};function $o(e,t="tips"){let{ClientSeq:s,From_Account:r,MsgClientTime:i,MsgPriority:n,MsgRandom:o,MsgSeq:a,MsgTimeStamp:u,TinyId:l,ToGroupId:c,GroupInfo:d,MsgBody:p}=e,h=function(){var{GroupCode:e,GroupId:t,GroupName:s,GroupType:r,MsgFrom_AccountExtraInfo:i,From_Account:n,To_Account:o}=d;return{groupCode:e,groupID:t,groupName:s,type:r,messageFromAccountExtraInformation:i,from:n,to:o}}();return{clientSequence:s,from:r,clientTime:i,priority:n,random:o,sequence:a,time:u,tinyID:l,to:c,groupProfile:h,elements:("tips"===t?zo:Qo)(p)}}function zo(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=>Jo(e));break;case"MsgOperatorMemberExtraInfo":e.operatorInfo=Jo(r[s]);break;case"MsgGroupNewInfo":e.newGroupProfile=function(o){let e={};return Object.keys(o).forEach(n=>{switch(n){case"GroupIntroduction":e.introduction=o[n];break;case"GroupName":e.groupName=o[n];break;case"GroupFaceUrl":e.avatar=o[n];break;case"GroupNotification":e.notification=o[n];break;case"ApplyJoinOption":e.joinOption=o[n];break;case"InviteJoinOption":e.inviteOption=o[n];break;case"ShutupAll":e.muteAllMembers=o[n];break;case"Owner_Account":e.ownerID=o[n];break;case"GroupAttrOption":e.groupAttributeOption=function(){var{BytesChangedKeys:e,GroupAttrSeq:t,OpType:s,PushChangedAttrValFlag:r,GroupAttrInfo:i}=o[n];return{changedKeyList:e,groupAttributeList:i.map(e=>{var{Key:e,Val:t,SubKeySeq:s}=e;return{key:e,value:t,sequence:s}}),serverMainSequence:t,operation:s,withChangedAttributeInfo:r}}()}}),e}(r[s]);break;case"MsgMemberInfo":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 Jo(e){var{ImageUrl:e,NickName:t,Role:s,UserId:r}=e;return{avatar:e,nick:t,role:s,userID:r}}function Qo(t){let s={};return Object.keys(t).forEach(e=>{switch(e){case"MsgKey":s.messageKey=t[e];break;case"Operator_Account":s.operatorID=t[e];break;case"ReportType":s.operationType=t[e];break;case"Authentication":s.authentication=t[e];break;case"MsgFlag":s.messageRemindType=t[e];break;case"UserDefinedField":s.userDefinedField=t[e];break;case"RemarkInfo":s.remarkInfo=t[e];break;case"BanDuration":s.duration=t[e];break;case"MuteTime":s.muteTime=t[e]}}),s}class Xo{constructor(e){this.type=jn.core.OuterConstant.MSG_GRP_TIP,this.content={},this._initContent(e)}static parseServerPushElement(e){e=zo(e);return new Xo(e)}_initContent(t){Object.keys(t).forEach(e=>{switch(e){case"groupProfile":this._initGroupProfile(t[e]);break;case"operatorInfo":this._initOperatorInfo(t[e]);break;case"memberInfoList":case"msgMemberInfo":this._updateMemberList(t[e]);break;case"newGroupProfile":this._initNewGroupProfile(t[e]);break;case"memberExtraInfo":case"remarkInfo":case"onlineMemberInfo":break;default:this.content[e]=t[e]}}),this.content.userIDList||(this.content.userIDList=[this.content.operatorID])}_initGroupProfile(t){this.content.groupProfile={};var s=Object.keys(t);for(let e=0;e<s.length;e++){var r=s[e];to[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 Zo=new class{constructor(){this._name="GroupTipsNotification"}init(e){var{common:{workflowManager:t},constants:{WORKFLOW_NAME:s,WORKFLOW_STEP:r}}=this._core=e,{message:{messageFactory:e},OuterConstant:i}=e;null!=e&&e.registerElementClass(i.MSG_GRP_TIP,Xo),t.registerWorkflowStep(s.SYNC_SERVER_INFO_AFTER_RE_ONLINE,r.GROUP_TIPS_RECOVER,this._handleGroupTipsRecover,this),t.registerWorkflowStep(s.RECEIVE_GROUP_TIPS_NOTIFICATION,r.HANDLE_GROUP_TIPS_NOTIFICATION,this.onNewGroupTips,this)}onNewGroupTips(e){let t=(e||{})["data"],{messageList:s,conversationUpdateFieldList:r}=this._handleGroupTips(t),{notificationCenter:i,OuterEvent:n,appStore:{conversationStore:o}}=this._core;return null!=r&&r.forEach(e=>{var{conversationID:e,lastMessage:t,unreadCount:s}=e,{unreadCount:r=0}=o.getConversation(e)||{};o.updateConversation(e,{lastMessage:t,unreadCount:s+r})}),0<s.length&&(i.emitOuterEvent(n.MESSAGE_RECEIVED,{name:n.MESSAGE_RECEIVED,data:s}),this._handleGroupTipMessage(s)),{conversationUpdateFieldList:r}}_handleGroupTips(e,s=!0){let{Event:r,GroupTips:i}=e,n=new Map,t=[],o=[];for(let t=0,e=i.length;t<e;t++){let e=$o(i[t],"tips");if(6===r){if(Yo.isGroupAttributesUpdated(e)){Yo.handleGroupAttributesUpdated(e);continue}if(Bo.isGroupCounterUpdated(e)){Bo.handleGroupCounterUpdated(e);continue}}var a=e["groupProfile"]["groupID"];if(T.hasLocalGroup(a)){a=this._assembleMessage(e);if(6===r&&(a._onlineOnlyFlag=!0,o.push(a)),4===r){if(!this._core.message.messageDataHandler.storeConversationMessage(a)&&s)continue;o.push(a)}this._handleConversationOptions(n,a)}}return t.push(...n.values()),{conversationUpdateFieldList:t,messageList:o}}_assembleMessage(e){var{OuterConstant:t,message:{messageFactory:s}}=this._core,t=(e.flow="in",e.conversationType=t.CONV_GROUP,s.createMessage(e)),s=(this._patchNickAndAvatar(e.elements,t),new Xo(Object.assign(Object.assign({},e.elements),{groupProfile:Object.assign({},e.groupProfile)})));return t.setElement(s),t.isSystemMessage=!1,t}_patchNickAndAvatar(e,s){let{utils:{isEmpty:t},OuterConstant:{GROUP_TIPS_OPERATION_TYPE:r}}=this._core,{operationType:i,memberInfoList:n,operatorInfo:o}=e,a={};if(t(n)?t(o)||(a=o):i!==r.JOINED&&i!==r.KICKED&&i!==r.ADMIN_SET&&i!==r.ADMIN_CANCELED||(a=Object.assign({},n[0])),!t(a)){let{nick:e="",avatar:t=""}=a;s.nick=e,s.avatar=t}}_handleConversationOptions(e,t){var{common:{getMessagePreviewText:s},utils:{isObject:r}}=this._core,{conversationID:i,conversationType:n}=t;let o;if(e.has(i))o=e.get(i),"in"!==t.flow||t._isExcludedFromUnreadCount||t._onlineOnlyFlag||o.unreadCount++,o.type=n,o.lastMessage=t._isExcludedFromLastMessage?"":Object.assign({},t);else{let e=0;"in"!==t.flow||t._isExcludedFromUnreadCount||t._onlineOnlyFlag||(e=1),o={conversationID:i,unreadCount:e,type:n,lastMessage:t._isExcludedFromLastMessage?"":Object.assign({},t)}}r(o.lastMessage)&&(o.lastMessage.messageForShow=s(o.lastMessage.type,o.lastMessage.payload)),e.set(i,o)}_handleGroupTipMessage(e){let{GROUP_TIPS_OPERATION_TYPE:s}=this._core["OuterConstant"];e.forEach(e=>{var t=e.payload["operationType"];switch(t){case s.JOINED:this._handleNewMemberJoined(e);break;case s.QUITTED:this._handleMemberQuitted(e);break;case s.KICKED:this._handleMemberKicked(e);break;case s.GROUP_PROFILE_UPDATED:this._handleGroupProfileUpdated(e)}})}_handleNewMemberJoined(e){this._handleGroupMemberCountUpdated(e)}_handleMemberQuitted(e){this._handleGroupMemberCountUpdated(e)}_handleMemberKicked(e){this._handleGroupMemberCountUpdated(e)}_handleGroupProfileUpdated(e){let t,{newGroupProfile:s,groupProfile:r,operatorInfo:i}=e.payload,n=r.groupID,o=T.getLocalGroup(n);Object.keys(s).forEach(e=>{switch(e){case"ownerID":this._handleGroupOwnerChanged(n,s);break;case"groupName":o.name=s[e];break;default:o[e]=s[e]}});var e=this._core["utils"]["isUndefined"];e(i)||(null==(t=null==o?void 0:o.selfInfo)?void 0:t.userID)!==i.userID||Object.keys(i).forEach(e=>{"nameCard"===e&&o.updateSelfInfo({nameCard:i[e]}),"role"===e&&this._updateSelfRole(o,i[e])}),T.emitGroupListUpdate(),T.updateConversationGroupProfile(n)}_handleGroupOwnerChanged(e,t){var{common:s,OuterConstant:r}=this._core,e=T.getLocalGroup(e),t=t["ownerID"];s.getCurrentUserID()===t&&e.updateGroup({ownerID:t,selfInfo:{role:r.GRP_MBR_ROLE_OWNER}})}_updateSelfRole(e,t){var s=this._core["OuterConstant"];let r=s.GRP_MBR_ROLE_MEMBER;400===t?r=s.GRP_MBR_ROLE_OWNER:300===t&&(r=s.GRP_MBR_ROLE_ADMIN),e.updateSelfInfo({role:r})}_handleGroupMemberCountUpdated(e){var{memberCount:e,groupProfile:{groupID:t}}=e.payload,s=T.getLocalGroup(t),r=this._core["utils"]["isNumber"];s&&r(e)&&s.memberCount!==e&&(s.memberCount=e,T.emitGroupListUpdate(),T.updateConversationGroupProfile(t))}_handleGroupTipsRecover(e){var t=this._core["utils"]["isArray"],e=((null==e?void 0:e.result)||{})["groupTipList"];t(e)&&e.forEach(e=>{e=this._handleGroupTips({Event:e.Event,GroupTips:[e]},!1).messageList;this._handleGroupTipMessage(e)})}};class ea{constructor(e){this.type=jn.core.OuterConstant.MSG_GRP_SYS_NOTICE,this.content={},this._initContent(e)}static parseServerPushElement(e){e=Qo(e);return new ea(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];so[r]&&(this.content.groupProfile[r]=t[r])}}}var ta=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,ea)}onNewGroupSystemNotification(e){var{GroupTips:e=[],isInstantMessage:t=!0}=e,{conversationUpdateFieldList:e,messageList:s}=(this._core.ssoLog.debug("onNewGroupSystemNotification",` count:${e.length} isInstantMessage:`+t),this._handleGroupSystemNotification(e,t)),{notificationCenter:r,OuterEvent:i}=this._core;0<e.length&&this._handleGroupSysTemMessage(t,s),!0===t&&0<s.length&&r.emitOuterEvent(i.MESSAGE_RECEIVED,{name:i.MESSAGE_RECEIVED,data:s})}_handleGroupSystemNotification(t,s){var r=[];let i={};for(let e=0;e<t.length;e++){var n=$o(t[e],"system"),o=n["elements"]["operationType"];15!==o&&(o=this._assembleMessage(n),this._core.message.messageDataHandler.storeConversationMessage(o))&&(r.push(o),i=this._handleConversationOptions(o,s))}return i.lastMessage=r[r.length-1],{conversationUpdateFieldList:0<r.length?[i]:[],messageList:r}}_assembleMessage(e){var{message:{messageFactory:t},OuterConstant:s,utils:{randomInt:r}}=this._core,s=(e.flow="in",e.conversationType=s.CONV_SYSTEM,e.conversationSubType=e.groupProfile.type,e.conversationID=s.CONV_SYSTEM,t.createMessage(e)),t=new ea(Object.assign(Object.assign({},e.elements),{groupProfile:Object.assign({},e.groupProfile)})),e=(s.setElement(t),s.isSystemMessage=!0,1===s.sequence&&1===s.random),t=2===s.sequence&&2===s.random;return(e||t)&&(s.sequence=r(),s.random=r(),s.generateMessageID()),s}_handleConversationOptions(e,t){var s=this._core["OuterConstant"],s={conversationID:s.CONV_SYSTEM,unreadCount:0,type:s.CONV_SYSTEM,subType:e.conversationSubType,lastMessage:null};return t&&s.unreadCount++,s}_handleGroupSysTemMessage(e,t){e&&t.forEach(e=>{var t=e.payload["operationType"];switch(t){case 2:this._handleGroupJoinResult(e);break;case 4:this._handleMemberKicked(e);break;case 5:this._handleGroupDismissed(e);break;case 7:this._handleGroupInvitedResult(e);break;case 8:this._handleGroupQuitResult(e);break;case 20:this._handleMessageRemindTypeSynced(e);break;case 21:this._handleAVChatRoomMemberBanned(e)}})}_handleGroupJoinResult(e){var e=e.payload["groupProfile"],{groupID:t,type:s}=e,r=T.hasLocalGroup(t);this._core.ssoLog.debug("_handleGroupJoinResult",` groupID:${t} type:${s} hasLocalGroup:`+r),r||io(s)||(T.updateLocalGroup([Object.assign({},e)]),T.emitGroupListUpdate())}_handleMemberKicked(e){var{groupID:e,type:t}=e.payload["groupProfile"];T.hasLocalGroup(e)&&this._deleteLocalGroup(e,t),this._updateConversationProfile(e,{unreadCount:0})}_handleGroupDismissed(e){var{groupID:e,type:t}=e.payload["groupProfile"];T.hasLocalGroup(e)&&this._deleteLocalGroup(e,t),this._updateConversationProfile(e,{unreadCount:0})}_handleGroupInvitedResult(e){var e=e.payload["groupProfile"],e=e["groupID"],t=T.hasLocalGroup(e);this._core.ssoLog.debug("_handleGroupInvitedResult",` groupID:${e} hasLocalGroup:`+t),t||vo.getGroupProfile({groupID:e}).then(e=>{var e=e["data"]["group"];T.updateLocalGroup([Object.assign({},e)]),T.emitGroupListUpdate()})}_handleGroupQuitResult(e){var{groupID:e,type:t}=e.payload["groupProfile"],s=T.hasLocalGroup(e);this._core.ssoLog.debug("_handleGroupQuitResult",` groupID:${e} type:${t} hasLocalGroup:`+s),s&&this._deleteLocalGroup(e,t),this._updateConversationProfile(e,{unreadCount:0})}_handleMessageRemindTypeSynced(e){var{groupProfile:{groupID:e},messageRemindType:t}=e.payload;this._updateConversationProfile(e,{messageRemindType:t})}_handleAVChatRoomMemberBanned(e){var{groupID:e,type:t}=e.payload["groupProfile"];this._deleteLocalGroup(e,t)}_deleteLocalGroup(s,e){if(io(e)){let{appStore:{conversationStore:e},OuterConstant:{CONV_GROUP:t}}=this._core;e.deleteConversation(""+t+s)}T.deleteLocalGroup(s),T.emitGroupListUpdate()}_updateConversationProfile(e,t){var{appStore:{conversationStore:s},OuterConstant:{CONV_GROUP:r}}=this._core,r=""+r+e;s.getConversation(r)&&s.updateConversation(r,t)}},sa=new class{init(e){(this._core=e).ssoLog.debug("GroupNotificationHandler.init"),Zo.init(e),ta.init(e);var{notificationCenter:e,InnerEvent:t}=e,s=e["InnerEventSubType"];e.subscribeInnerEvent(t.MESSAGE_PUSH,s.GROUP_TIPS_NOTIFICATION,this._onNewGroupTipsNotification,this),e.subscribeInnerEvent(t.MESSAGE_PUSH,s.GROUP_SYSTEM_NOTIFICATION,this._onNewGroupSystemNotification,this),e.subscribeInnerEvent(t.DESTROY,this._dispose,this)}_onNewGroupTipsNotification(e){var{common:{workflowManager:t},constants:{WORKFLOW_NAME:s}}=this._core;t.executeWorkflow(s.RECEIVE_GROUP_TIPS_NOTIFICATION,e)}_onNewGroupSystemNotification(e){ta.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 D={required:!0,rules:["string"],allowEmpty:!1},ra={required:!0,rules:["number"],allowEmpty:!1},ia={required:!0,rules:["array"],allowEmpty:!1},na={required:!0,rules:["object"],allowEmpty:!1},oa={createGroup:{name:D,type:D},dismissGroup:[Object.assign({key:"groupID"},D)],joinGroup:{groupID:D,applyMessage:{required:!1,rules:["string"],allowEmpty:!0}},quitGroup:[Object.assign({key:"groupID"},D)],searchGroupByID:[Object.assign({key:"groupID"},D)],getGroupProfile:{groupID:D,groupCustomFieldFilter:{required:!1,rules:["array"],allowEmpty:!0}},updateGroupProfile:{groupID:D,muteAllMembers:{required:!1,rules:["boolean"],allowEmpty:!1}},changeGroupOwner:{groupID:D,newOwnerID:D},getGroupOnlineMemberCount:[Object.assign({key:"groupID"},D)],handleGroupApplication:{handleAction:D},getGroupMemberList:{groupID:D},getGroupMemberProfile:{groupID:D,userIDList:ia,memberCustomFieldFilter:{required:!1,rules:["array"],allowEmpty:!0}},addGroupMember:{groupID:D,userIDList:ia},deleteGroupMember:{groupID:D,userIDList:ia},setGroupMemberMuteTime:{groupID:D,userID:D,muteTime:Object.assign(Object.assign({},ra),{customValidator:e=>!(e<0)||"muteTime must be a non-negative number."})},setGroupMemberRole:{groupID:D,userID:D,role:D},setGroupMemberNameCard:{groupID:D,userID:{required:!1,rules:["string"],allowEmpty:!1},nameCard:D},setGroupMemberCustomField:{groupID:D,userID:{required:!1,rules:["string"],allowEmpty:!1},memberCustomField:ia},markGroupMemberList:{groupID:D,markType:Object.assign(Object.assign({},ra),{customValidator:e=>!(e<1e3)||"markType must be greater than or equal to 1000."}),enableMark:{required:!0,rules:["boolean"],allowEmpty:!1},userIDList:ia},initGroupAttributes:{groupID:D,groupAttributes:na},setGroupAttributes:{groupID:D,groupAttributes:na},deleteGroupAttributes:{groupID:D,keyList:Object.assign(Object.assign({},ia),{allowEmpty:!0})},getGroupAttributes:{groupID:D,keyList:Object.assign(Object.assign({},ia),{allowEmpty:!0})},getGroupCounters:{groupID:D,keyList:{required:!1,rules:["array"],allowEmpty:!0}},setGroupCounters:{groupID:D,counters:na},increaseGroupCounter:{groupID:D,key:D,value:ra},decreaseGroupCounter:{groupID:D,key:D,value:ra}},aa={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},ua=new class{constructor(){this._installedSubPlugins=[],this.groupDataHandler=T,this.groupAction=To,this.groupAttribute=Yo,this.groupMember=qo,this.name="Group"}install(e,t=[]){this._core=e,jn.init(e),T.init(e),To.init(e,this),qo.init(e,this),Do.init(e),Bo.init(e),Yo.init(e),sa.init(e),e.helper.registerValidateConfig({auth:aa,params:oa}),this._installSubPlugins(t);var{notificationCenter:t,InnerEvent:e}=e;t.subscribeInnerEvent(e.LOGOUT,this._reset,this),t.subscribeInnerEvent(e.DESTROY,this._dispose,this)}getInstalledSubPlugins(){return this._installedSubPlugins}_installSubPlugins(e){var{isArray:t}=this._core["utils"];e&&t(e)&&e.forEach(e=>{var t;this._installedSubPlugins.includes(e.name)||(null!=(t=e.install)&&t.call(e,this._core,this),this._installedSubPlugins.push(e.name))})}_reset(){T.reset(),Yo.reset(),Bo.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)}},la=new class{init(e){this.core=e}},ca={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},da={GROUP_DISMISSED:5,QUIT_GROUP:8,AVCHATROOM_MEMBER_BANNED:21};class pa{constructor(e){var{core:e,manager:t,groupID:s,getRequestParams:r,onSuccess:i,onFail:n}=e;this._name="Polling",this._core=e,this._manager=t,this._timeoutID=-1,this._isRunning=!1,this._groupID=s,this._getRequestParams=r,this._onSuccess=i,this._onFail=n}start(){this._isRunning=!0,this._request(),console.log(this._name+".start pollingInterval:"+this._manager.getCurrentPollingInterval(this._groupID))}isRunning(){return this._isRunning}_request(){return I(this,void 0,void 0,function*(){try{var e=yield function(i,n){return I(this,void 0,void 0,function*(){var{longPollingKey:e,startSequence:t,startBroadcastSeq:s,simplifiedMessage:r}=i;return n.common.buildAndSendPacket({servcmd:"group_open_long_polling_http_svc.get_msg",data:{Key:e,StartSeq:t,StartBroadcastSeq:s,DownsizeFlag:r,USP:1,HoldTime:90}})})}(this._getRequestParams(this._groupID),this._core),t=(this._onSuccess(this._groupID,e),this._manager.getCurrentPollingInterval(this._groupID));this._runNextPolling(t)}catch(e){this._onFail(this._groupID,e),this._runNextPolling(2e3)}})}_runNextPolling(e){this.isRunning()&&(-1<this._timeoutID&&clearTimeout(this._timeoutID),this._timeoutID=setTimeout(this._request.bind(this),e))}stop(){console.log(this._name+".stop timerID:"+this._timeoutID),-1<this._timeoutID&&(clearTimeout(this._timeoutID),this._timeoutID=-1),this._isRunning=!1}}class ha{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 ga=e=>e===ca.GROUP_TIPS_HAS_NO_ROAMING||e===ca.GROUP_TIPS_HAS_ROAMING,_a=e=>e===ca.GROUP_SYSTEM_MESSAGE;function ma(h){var e,t,s,r,i,n,o,a=function(){var{E:e,MCT:t,MR:s,MP:r,MTS:i,GId:n,MS:o,CCD:a,F_Account:u,IsSys:l,GInf:c,MsgBody:d}=h,p=f(h,["E","MCT","MR","MP","MTS","GId","MS","CCD","F_Account","IsSys","GInf","MsgBody"]);return Object.assign({Event:e,MsgClientTime:t,MsgRandom:s,MsgPriority:r,MsgTimeStamp:i,ToGroupId:n,MsgSeq:o,CloudCustomData:a,From_Account:u,IsSystemMsg:l,GroupInfo:function(e){var e=e||{},{GN:t,GT:s,F_Hd:r,F_NN:i,F_Ll:n}=e,e=f(e,["GN","GT","F_Hd","F_NN","F_Ll"]),t=Object.assign({GroupName:t,GroupType:s},e);return r&&(t.From_AccountHeadurl=r),i&&(t.From_AccountNick=i),n&&(t.From_AccountLevel=n),t}(c),MsgBody:function(e){let t=e,s=(t=Array.isArray(e)?t:[e]).map(e=>{var{O_Account:t,Opt:s,L_Account:r,RT:i,UDF:n,OpInf:o,OnlineInf:a,MsgMemberExtraInfo:u}=e,e=f(e,["O_Account","Opt","L_Account","RT","UDF","OpInf","OnlineInf","MsgMemberExtraInfo"]),t=Object.assign({Operator_Account:t,OpType:s,List_Account:r,ReportType:i,UserDefinedField:n},e);return o&&(t.MsgOperatorMemberExtraInfo=function(){var{Img:e,NN:t}=o,s=f(o,["Img","NN"]);return Object.assign({ImageUrl:e,NickName:t},s)}()),u&&(t.MsgMemberExtraInfo=u.map(e=>{var{Img:t,NN:s}=e,e=f(e,["Img","NN"]);return Object.assign({ImageUrl:t,NickName:s},e)})),a&&(t.OnlineMemberInfo=function(){var{ET:e,Num:t}=a;return{ExpireTime:e,OnlineMemberNum:t}}()),t});return Array.isArray(e)?s:s[0]}(d)},p)}(),u=a,l=u["Event"];if((ga(l)||_a(l))&&(u.From_Account=u.From_Account||"@TIM#SYSTEM"),l===ca.BROADCAST_MESSAGE||l===ca.NORMAL_MESSAGE){var c=u;let e=la["core"]["OuterConstant"];c.CloudCustomData=c.CloudCustomData||"",c.MsgBody=c.MsgBody.map(t=>{if(t.MsgType===e.MSG_CUSTOM){let{content:e={}}=t;t.content=Object.assign({Data:"",Desc:"",Ext:""},e)}return t})}return ga(l)&&({GroupJoinType:e,MsgOperatorMemberExtraInfo:t={},MsgMemberExtraInfo:s,Operator_Account:r,List_Account:i,OpType:n}=(c=u).MsgBody||{},"number"==typeof e||1!==n&&2!==n||(c.MsgBody.GroupJoinType=2===n?0:1),s||(c.MsgBody.MsgMemberExtraInfo=i.map(e=>({UserId:e}))),1!==n||s||(c.MsgBody.MsgMemberExtraInfo=[{UserId:t.UserId}]),c.MsgBody.MsgOperatorMemberExtraInfo=Object.assign({Operator_Account:r,ImageUrl:"",NickName:""},t)),_a(l)&&({MsgOperatorMemberExtraInfo:e={},Operator_Account:i}=(o=u).MsgBody||{},o.MsgBody.MsgMemberExtraInfo=Object.assign({UserId:i,ImageUrl:"",NickName:""},e),o.MsgBody=Object.assign({Authentication:"",RemarkInfo:"",MsgKey:1e3*o.MsgTimeStamp},o.MsgBody),o.MsgBody=Object.keys(o.MsgBody).filter(e=>"MsgOperatorMemberExtraInfo"!==e).reduce((e,t)=>Object.assign(Object.assign({},e),{[t]:o.MsgBody[t]}),{})),a}var va=new class{constructor(){this._name="MessageParser",this._sequenceList=new ha(200),this._messageIDList=new ha(100),this._broadcastMessageIDMap=new Map,this._reportMessageStackedCount=0}init(e,t){this._core=e,this._avChatRoomHandler=t}onMessageReceived(i,e,n=!1){this._sortServerMessageList({groupID:i,serverMessageList:e,isHistoryMessage:n});var o=this._handleMessageList(i,e);if(0!==o.length){if(!n){let{appStore:{conversationStore:e},OuterConstant:{CONV_GROUP:t}}=this._core,s=(e=>{var{common:{getMessagePreviewText:t}}=la["core"];return{lastTime:(null==e?void 0:e.time)||(null==e?void 0:e.lastTime)||0,lastSequence:(null==e?void 0:e.sequence)||(null==e?void 0:e.lastSequence)||0,fromAccount:(null==e?void 0:e.from)||(null==e?void 0:e.fromAccount)||"",messageForShow:t(null==e?void 0:e.type,null==e?void 0:e.payload),payload:(null==e?void 0:e.payload)||null,type:(null==e?void 0:e.type)||"",isRevoked:(null==e?void 0:e.isRevoked)||!1,cloudCustomData:(null==e?void 0:e.cloudCustomData)||"",onlineOnlyFlag:(null==e?void 0:e._onlineOnlyFlag)||!1,nick:(null==e?void 0:e.nick)||"",nameCard:(null==e?void 0:e.nameCard)||"",version:(null==e?void 0:e.version)||0,isPeerRead:(null==e?void 0:e.isPeerRead)||!1,revoker:(null==e?void 0:e.revoker)||null}})(o[o.length-1]);e.updateConversation(""+t+i,{lastMessage:s})}this._checkMessageStacked(o);let e=o.filter(e=>!0===e.isModified),t=o.filter(e=>!1===e.isModified),{MESSAGE_RECEIVED:s,MESSAGE_MODIFIED:r}=this._core["OuterEvent"];0<e.length&&this._emitEvent({name:r,data:e}),0<t.length&&this._emitEvent({name:s,data:t})}}_sortServerMessageList(e){var{groupID:e,serverMessageList:t,isHistoryMessage:s}=e;let r=[];r=this._avChatRoomHandler.isPollingSimplifiedMessage()&&!s?(t.sort((e,t)=>e.MS-t.MS),t.map(e=>e.MS)):(t.sort((e,t)=>e.MsgSeq-t.MsgSeq),t.map(e=>e.MsgSeq)),console.log(`${this._name}._sortServerMessageList groupID:${e} count:${r.length} sequenceList:`+r),r.length=0}_handleMessageList(s,r){var i,n,{messageDataHandler:o,messageHelper:a}=this._core["message"],u=this._avChatRoomHandler.isPollingSimplifiedMessage(),l=[],e=r.length;for(let t=0;t<e;t++){let e=r[t];if(u&&(e=ma(e)),_a(e.Event)&&Object.values(da).includes(e.MsgBody.ReportType)){this._onGroupDismissed(s);break}null!==this._filterMessageItem(e)&&(this._patchMessageType(e),i=a.parseServerGroupMessage(e),(n=this._createMessage(i)).level=e.GroupInfo.From_AccountLevel,ga(e.Event)&&this._avChatRoomHandler.isGroupAttributesUpdated(i)?this._avChatRoomHandler.handleGroupAttributesUpdated(i):null===this._filterDuplicateMessage(n)||o.isMessageSentByCurrentInstance(n)||(1===i.isModified&&(n.isModified=!0),ga(e.Event)&&this._updateLocalOnlineMemberCountFromTips(e),l.push(n)))}return l}_patchMessageType(e){var t=this._core["OuterConstant"];ga(e.Event)&&(e.MsgBody.MsgType=t.MSG_GRP_TIP),_a(e.Event)&&(e.MsgBody.MsgType=t.MSG_GRP_SYS_NOTICE)}_filterMessageItem(e){var t=e["Event"];return Object.values(ca).includes(t)?t===ca.MESSAGE_REVOKED?(this._handleMessageRevoked(e),null):t===ca.LIVE_CUSTOM_DATA?(this._onLiveCustomData(e),null):t===ca.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===ca.GROUP_SYSTEM_MESSAGE&&(r=s.CONV_SYSTEM);s=!!e.isSystemMessage,t=t.createMessage(Object.assign(Object.assign({},e),{conversationType:r,isSystemMessage:s,flow:"in"}));return t.setElement(e.elements),t}_filterDuplicateMessage(e){var t=this._core["common"];if(!t.isUnlimitedAVChatRoom()){if(this._sequenceList.has(e.sequence))return null;this._sequenceList.set(e.sequence)}t=this._messageIDList.has(e.ID);return t?(console.warn(`${this._name}_filterDuplicateMessageItem ID:${e.ID} has:`+t),null):(this._messageIDList.set(e.ID),e)}_handleMessageRevoked(e){let{OuterConstant:i,OuterEvent:{MESSAGE_REVOKED:t}}=this._core,{ToGroupId:n,MsgBody:{RevokeMsgList:s},RevokerInfo:{Revoker_Account:o,Reason:a=""}}=e,u=[];s.forEach(e=>{var{TinyId:e,MsgClientTime:t,Random:s,MsgSeq:r}=e,e={conversationID:""+i.CONV_GROUP+n,ID:e+`-${t}-`+s,revoker:o,revokeReason:a,revokerInfo:{userID:o,nick:"",avatar:""},sequence:r};u.push(e)}),0!==u.length&&this._emitEvent({name:t,data:u})}_onLiveCustomData(e){var t=this._core["OuterEvent"]["ROOM_CUSTOM_DATA_RECEIVED"],{ToGroupId:e,MsgSeq:s,MsgTimeStamp:r,MsgBody:i}=e,i=(null==i?void 0:i.MsgContent)||"";this._emitEvent({name:t,data:i}),console.log(this._name+`._onLiveCustomData groupID:${e} sequence:${s} time:${r} data:`+i)}_onGroupDismissed(e){this._avChatRoomHandler.reset(e)}_checkMessageStacked(e){var t=e["length"];if(100<=t&&this._reportMessageStackedCount<5){let e=this._avChatRoomHandler.getJoinedGroups();this._core.ssoLog.info("MessageStacked",`count:${t} groupID:`+e.join(",")),this._reportMessageStackedCount+=1}}_emitEvent(e){this._core.notificationCenter.emitOuterEvent(e.name,e)}onBroadcastMessageReceived(s){var{message:{messageHelper:r},OuterEvent:{MESSAGE_RECEIVED:e}}=this._core,i=this._avChatRoomHandler.isPollingSimplifiedMessage(),n=[],o=s.length;for(let t=0;t<o;t++){let e=s[t];i&&(e=ma(e));var a=r.parseServerGroupMessage(e);Object.values(ca).includes(e.Event)?((a=this._createMessage(a)).isBroadcastMessage=!0,this._broadcastMessageIDMap.has(a.ID)||(n.push(a),this._broadcastMessageIDMap.set(a.ID,1))):console.warn(this._name+".onBroadcastMessageReceived unknown event:"+e.Event)}0<n.length&&this._emitEvent({name:e,data:n})}_updateLocalOnlineMemberCountFromTips(t){var s=this._core["utils"]["isEmpty"],{ToGroupId:t,MsgBody:{OnlineMemberInfo:r}}=t;if(!s(r)){var{OnlineMemberNum:r=0,ExpireTime:i=60}=r,n=Date.now();let e=this._avChatRoomHandler.getLocalOnlineMemberCount(t);s(e)?e={lastReqTime:0,lastSyncTime:0,latestUpdateTime:n,memberCount:r,expireTime:i}:(e.latestUpdateTime=n,e.memberCount=r),this._avChatRoomHandler.updateLocalOnlineMemberCount(t,e)}}reset(){this._reportMessageStackedCount=0,this._sequenceList.clear(),this._messageIDList.clear(),this._broadcastMessageIDMap.clear()}};let fa=e=>{var{store:t}=la["core"];return(t.get("cloudConfig")||{})[e]},Ia=e=>{var{utils:{isUndefined:t}}=la["core"];return!t(e)},Ea=()=>{var e=fa("polling_interval");return Ia(e)?parseInt(e,10):300},Ca=()=>{var e=fa("polling_simplified_msg");return Ia(e)?parseInt(e,10):0};var Sa=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,va.init(e,this),e.ssoLog.debug("AVChatRoomHandler.init")}onAVChatRoomSystemNotification(e){var t=this._core["OuterConstant"]["GRP_AVCHATROOM"],{GroupTips:s=[]}=e;for(let e=0;e<s.length;e++){var{MsgBody:r,GroupInfo:{GroupId:i,GroupType:n}}=s[e],r=Object.values(da).includes(r.ReportType);n===t&&r&&this.reset(i)}}getCurrentPollingInterval(e){return this._pollingIntervalMap.get(e)||Ea()}isPollingSimplifiedMessage(){return 0!==Ca()}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(u){return I(this,void 0,void 0,function*(){var{utils:{isUndefined:e},OuterConstant:{CONV_GROUP:t},apiMap:{getConversationProfile:s},OuterConstant:r}=this._core,{longPollingKey:i,group:n,historyMessageList:o=[]}=u,a=n["groupID"];return yield this._preCheck(n),this._joinedGroupMap.set(a,n),this._parentPlugin.groupDataHandler.updateLocalGroup([n]),this._parentPlugin.groupDataHandler.emitGroupListUpdate(),s(""+t+a),0<o.length&&va.onMessageReceived(a,o,!0),e(i)?{status:r.JOIN_STATUS_SUCCESS,group:n}:this.startMessageLongPolling(u)})}_preCheck(n){return I(this,void 0,void 0,function*(){var{common:t,OuterConstant:e,helper:s,apiMap:{quitGroup:r},ssoLog:i}=this._core;if(t.isUnlimitedAVChatRoom()){if(this._pollingInstanceMap.size>(t=fa("polling_count_limit"),Ia(t)&&0<t?parseInt(t,10):20))throw new s.ChatError({code:2688,message:"the count of longPolling exceeds the max limit"})}else if(0!==this._joinedAVChatRoomCount()&&n.type!==e.GRP_LIVE){var[t,s]=this._joinedGroupMap.entries().next().value;if(s.selfInfo.role===e.GRP_MBR_ROLE_OWNER)this._parentPlugin.groupDataHandler.deleteLocalGroup(t);else try{yield r(t)}catch(e){i.debug("quitGroup",this._name+`._preCheck quitGroup failed, groupID:${t} info:`,e)}this.reset(t)}})}startMessageLongPolling(e){var t=this._core["OuterConstant"],{longPollingKey:e,startSequence:s=1,group:r}=e,i=r["groupID"];return this._pollingRequestInfoMap.set(i,{longPollingKey:e,startSequence:s}),this._pollingIntervalMap.set(i,Ea()),this._startPolling(i),this._reportLongPollingCount(),{status:t.JOIN_STATUS_SUCCESS,group:r}}_startPolling(t){if(this._core.ssoLog.debug("_startPolling",this._name+"._startPolling groupID:"+t),this._pollingInstanceMap.has(t)){let e=this._pollingInstanceMap.get(t);void((null==e?void 0:e.isRunning())||null==e||e.start())}else{let e=new pa({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:Ca()}:{longPollingKey:t,startSequence:s,simplifiedMessage:Ca()}}_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:i=[],RspBroadcastMsgList:n=[]}=e;if(e&&s&&this._pollingRequestInfoMap.set(t,{longPollingKey:e,startSequence:s}),r&&r>this._startBroadcastSequence&&(this._startBroadcastSequence=r),0<i.length)0!==this._getPollingNoMessageCount(t)&&(this._updatePollingNoMessageCount(t,0),this._pollingIntervalMap.set(t,Ea())),va.onMessageReceived(t,i);else{e=this._getPollingNoMessageCount(t);if(this._updatePollingNoMessageCount(t,e+=1),e===(s=fa("polling_no_msg_count"),Ia(s)?parseInt(s,10):20)){let e=Ea()+(r=fa("polling_interval_plus"),Ia(r)?parseInt(r,10):2e3);this._pollingIntervalMap.set(t,e)}}0<n.length&&va.onBroadcastMessageReceived(n)}_handleFailure(e,t){var{ssoLog:s,utils:{safeStringify:r}}=this._core;s.warn("polling",this._name+`._handleFailure groupID:${e} error: `+r(t))}_joinedAVChatRoomCount(){let t=this._core["OuterConstant"],e=[];return(e=0<this._joinedGroupMap.size?this.getJoinedGroups().filter(e=>e.type===t.GRP_AVCHATROOM):e).length}_hasJoinedAVChatRoom(e){return this._joinedGroupMap.has(e)}getJoinedGroups(){return[...this._joinedGroupMap.values()]}updateLocalLiveGroup(e,t){this._joinedGroupMap.set(e,t),this._parentPlugin.groupDataHandler.updateLocalGroup([t])}handleLiveHistoryMessages(e,t){va.onMessageReceived(e,t,!0)}isOverFrequencyLimit(e){var t,s,r,i;return!this._membersReqInfoMap.has(e)||({startTime:t,requestCount:s}=this._membersReqInfoMap.get(e),{interval:r,count:i}=(()=>{var e=fa("av_members_freq_limit");if(Ia(e)){var{interval:e,count:t}=JSON.parse(e);if(0<t&&0<e)return{interval:e,count:t}}return{interval:30,count:4}})(),Date.now()-t>1e3*r)?(this._membersReqInfoMap.set(e,{startTime:Date.now(),requestCount:1}),!1):(this._membersReqInfoMap.set(e,{startTime:t,requestCount:s+=1}),i<s)}_stopPolling(e){var t,s;if(this._core.ssoLog.debug("_stopPolling",this._name+"._stopPolling groupID:"+e),e)({appStore:{conversationStore:s},OuterConstant:{CONV_GROUP:t}}=this._core),s.deleteConversation(""+t+e),null!=(s=this._pollingInstanceMap.get(e))&&s.stop(),this._parentPlugin.groupDataHandler.deleteLocalGroup(e),this._pollingInstanceMap.delete(e),this._pollingRequestInfoMap.delete(e),this._joinedGroupMap.delete(e),this._onlineMemberCountMap.delete(e),this._pollingIntervalMap.delete(e),this._pollingNoMessageCountMap.delete(e),this._membersReqInfoMap.delete(e);else{for(let e of this._pollingInstanceMap.values())null!=e&&e.stop();this._pollingInstanceMap.clear(),this._pollingRequestInfoMap.clear(),this._joinedGroupMap.clear(),this._onlineMemberCountMap.clear(),this._pollingIntervalMap.clear(),this._pollingNoMessageCountMap.clear(),this._membersReqInfoMap.clear()}}_updatePollingNoMessageCount(e,t){this._pollingNoMessageCountMap.set(e,t)}_getPollingNoMessageCount(e){return this._pollingNoMessageCountMap.get(e)||0}_reportLongPollingCount(){var o=this._joinedGroupMap.size;if(1<o){let{common:e,OuterConstant:s,ssoLog:t}=this._core,r=e.isUnlimitedAVChatRoom()?1:0,i=[],n=[];this._joinedGroupMap.values().forEach(({groupID:e,type:t})=>{(t===s.GRP_LIVE?n:i).push(e)}),t.info("longPollingCount",String(o),{moreMessage:`av:${i.join(",")} live:${n.join(",")} code: `+r,eventType:29})}}reset(e){this._stopPolling(e),this._startBroadcastSequence=1,va.reset()}},Ma=new class{init(e,t){this._core=e,this._parentPlugin=t;e=e.helper;e.registerApi({apiName:"joinGroup",context:this,matcher:()=>0<t.getInstalledSubPlugins().length})}joinGroup(i){return I(this,void 0,void 0,function*(){var e=this._core["OuterConstant"],t=yield this._parentPlugin.groupAction.joinGroup(i),{status:s,group:{type:r}}=t["data"];return r!==e.GRP_AVCHATROOM||s===e.JOIN_STATUS_ALREADY_IN_GROUP?t:Sa.handleJoinGroupResult(t.data)})}},ya=new class{init(e,t){this._core=e,this._parentPlugin=t;e=e.helper;e.registerApi({apiName:"quitGroup",context:this,matcher:()=>0<t.getInstalledSubPlugins().length})}quitGroup(r){return I(this,void 0,void 0,function*(){var e=this._core["OuterConstant"],t=yield this._parentPlugin.groupAction.quitGroup(r),{type:s}=t["data"];return s===e.GRP_AVCHATROOM&&Sa.reset(r),t})}},Ta=new class{init(e,t){this._core=e,this._parentPlugin=t;e=e.helper;e.registerApi({apiName:"dismissGroup",context:this,matcher:()=>0<t.getInstalledSubPlugins().length})}dismissGroup(r){return I(this,void 0,void 0,function*(){var e=this._core["OuterConstant"],t=yield this._parentPlugin.groupAction.dismissGroup(r),{type:s}=t["data"];return s===e.GRP_AVCHATROOM&&Sa.reset(r),t})}},Aa=new class{constructor(){this._name="GetAVChatRoomMemberList"}init(e,t){this._core=e,this._parentPlugin=t;e=e.helper;e.registerApi({apiName:"getGroupMemberList",context:this,matcher:()=>0<t.getInstalledSubPlugins().length})}getGroupMemberList(i){return I(this,void 0,void 0,function*(){var{appStore:{groupStore:e},helper:t,OuterConstant:s}=this._core,r=i["groupID"],e=e.getGroup(r);if((null==e?void 0:e.type)===s.GRP_AVCHATROOM&&t.checkBusinessCapabilityBits("AV_MBR_LIST")){if(Sa.isOverFrequencyLimit(r))throw{code:2996,message:"Over frequency limit: get_members-"+r};return this._getGroupMemberList(i)}return this._parentPlugin.groupMember.getGroupMemberList(i)})}_getGroupMemberList(n){return I(this,void 0,void 0,function*(){let i="_getGroupMemberList",t=this._core["helper"];try{let e=yield function(s,r){return I(this,void 0,void 0,function*(){var{groupID:e,offset:t=0}=s;return r.common.buildAndSendPacket({servcmd:"group_open_avchatroom_http_svc.get_members",data:{GroupId:e,Timestamp:t}})})}(n,this._core),{MemberList:t=[],NextTimestamp:s=0}=e||{},r=this._handleMemberList(t);return console.log(`${this._name}.${i} ok, groupID:${n.groupID} count:${r.length} nextOffset:`+s),{code:0,data:{memberList:r,offset:s}}}catch(e){var s=new t.ChatError({functionName:i,code:null==e?void 0:e.errorCode,message:null==e?void 0:e.errorInfo});throw console.error(this._name+`.${i} fail:`,s),s}})}_handleMemberList(e){return e.map(e=>{var{Member_Account:e,NickName:t="",Avatar:s="",Remark:r="",JoinTime:i=0,Marks:n=[]}=e;return{userID:e,nick:t,avatar:s,remark:r,joinTime:i,marks:n,isOnline:!0}})}},Oa=new class{constructor(){this._name="GetAVChatRoomOnlineMemberCount"}init(e,t){this._core=e,this._parentPlugin=t;e=e.helper;e.registerApi({apiName:"getGroupOnlineMemberCount",context:this,matcher:()=>0<t.getInstalledSubPlugins().length})}getGroupOnlineMemberCount(s){return I(this,void 0,void 0,function*(){var{appStore:{groupStore:e},OuterConstant:t}=this._core,e=e.getGroup(s);return e?e.type===t.GRP_AVCHATROOM?this._getOnlineMemberCount(s):this._parentPlugin.groupAction.getGroupOnlineMemberCount(s):{code:0,data:{memberCount:0}}})}_getOnlineMemberCount(r){return I(this,void 0,void 0,function*(){let t="_getOnlineMemberCount",{isEmpty:e}=this._core["utils"],s=Sa.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=Sa.getLocalOnlineMemberCount(e),t=Date.now(),s=t-e.lastSyncTime>1e3*e.expireTime,r=1e4<t-e.latestUpdateTime,t=3e3<t-e.lastReqTime;return s&&r&&t}_getOnlineMemberCountFromServer(n){return I(this,void 0,void 0,function*(){let t="_getOnlineMemberCountFromServer";try{let e=yield function(e,t){return I(this,void 0,void 0,function*(){return t.common.buildAndSendPacket({servcmd:"group_open_http_svc.get_online_member_num",data:{GroupId:e}})})}(n,this._core),{OnlineMemberNum:t=0,ExpireTime:s=60}=e||{},r=Date.now(),i={lastSyncTime:r,latestUpdateTime:r,lastReqTime:r,memberCount:t,expireTime:s};return Sa.updateLocalOnlineMemberCount(n,i),{memberCount:t}}catch(e){var s=new this._core.helper.ChatError({functionName:t,code:null==e?void 0:e.errorCode,message:null==e?void 0:e.errorInfo});throw console.error(`${this._name}.${t} fail:`,s),s}})}},Da=new class{constructor(){this._name="DeleteAVChatRoomMember"}init(e,t){this._core=e,this._parentPlugin=t;e=e.helper;e.registerApi({apiName:"deleteGroupMember",context:this,matcher:()=>0<t.getInstalledSubPlugins().length})}deleteGroupMember(o){return I(this,void 0,void 0,function*(){var e="deleteGroupMember",{appStore:{groupStore:t},utils:{isUndefined:s},helper:r,OuterConstant:i}=this._core,n=o["groupID"],t=t.getGroup(n);if(s(t))throw new r.ChatError({functionName:e,code:2603});if(t.type!==i.GRP_AVCHATROOM)return this._parentPlugin.groupMember.deleteGroupMember(o);if(r.checkBusinessCapabilityBits("AV_BAN_MBR"))return this._deleteGroupMember(o);throw new r.ChatError({functionName:e,code:3122})})}_deleteGroupMember(a){return I(this,void 0,void 0,function*(){var t="_deleteGroupMember",{appStore:{groupStore:e},helper:s,ssoLog:r}=this._core,{groupID:i,duration:n=0,userIDList:o}=a;if(0===n)throw new s.ChatError({functionName:t,code:2686});try{return yield function(i,n){return I(this,void 0,void 0,function*(){var{groupID:e,userIDList:t,duration:s,reason:r}=i;return n.common.buildAndSendPacket({servcmd:"group_open_http_svc.ban_group_member",data:{GroupId:e,Members_Account:t,Duration:s,Description:r}})})}(a,this._core),r.debug(t,this._name+`.${t} ok, groupID:`+i),{code:0,data:{group:e.getGroup(i),userIDList:o}}}catch(e){throw new s.ChatError({functionName:t,code:null==e?void 0:e.errorCode,message:null==e?void 0:e.errorInfo})}})}},Ra=new class{constructor(){this._name="MarkAVChatRoomMember"}init(e){e=(this._core=e).helper;e.registerApi({apiName:"markGroupMemberList",context:this})}markGroupMemberList(e){return I(this,void 0,void 0,function*(){var i="markGroupMemberList",{groupID:n,markType:o,enableMark:a,userIDList:u=[]}=e,l=this._generateRequestData(e);try{let e=yield function(r,i){return I(this,void 0,void 0,function*(){var{groupID:e,operationType:t,memberList:s}=r;return i.common.buildAndSendPacket({servcmd:"group_open_avchatroom_http_svc.modify_user_info",data:{GroupId:e,CommandType:t,MemberList:s}})})}(l,this._core),{MemberList:t=[]}=e||{},{successUserIDList:s,failureUserIDList:r}=this._handleResult(t,u);return{code:0,data:{successUserIDList:s,failureUserIDList:r},successLog:{message:`${this._name}.${i} ok, groupID:${n} markType:${o} enableMark:${a} success:${s.length} fail:`+r.length}}}catch(e){throw new this._core.helper.ChatError({functionName:i,code:null==e?void 0:e.errorCode,message:null==e?void 0:e.errorInfo})}})}_generateRequestData(e){let{groupID:t,markType:s,enableMark:r,userIDList:i=[]}=e,n=!0===r?1:2,o=[...i];return 500<o.length&&console.warn(this._name+"._generateRequestData, the length of userIDList cannot exceed 500"),{groupID:t,operationType:n,memberList:o.map(e=>({Member_Account:e,Marks:[s]}))}}_handleResult(e,t){let s=[],r=[];return e.length===t.length?s.push(...t):t.forEach(t=>{(e.find(e=>e.Member_Account===t)?s:r).push(t)}),{successUserIDList:s,failureUserIDList:r}}},La=new class{init(e,t){e.ssoLog.debug("AVChatRoomAction.init"),Ma.init(e,t),ya.init(e,t),Ta.init(e,t),Aa.init(e,t),Oa.init(e,t),Da.init(e,t),Ra.init(e)}},Na=new class{constructor(){this._name="LiveHandler"}init(e){var{helper:e,ssoLog:t}=this._core=e;e.registerExperimentalAPI("startMessageLongPolling",this),e.registerExperimentalAPI("stopMessageLongPolling",this),t.debug("LiveHandler.init")}startMessageLongPolling(e){var{common:t,utils:{isEmpty:s},OuterConstant:r,ssoLog:i}=this._core,{groupID:e,longPollingKey:n,longPollingSequence:o=1}=e;if(s(n))return i.warn("startMessageLongPolling",this._name+".startMessageLongPolling longPollingKey is empty."),Promise.resolve({});Sa.hasPollingInstance(e)&&this.stopMessageLongPolling({groupID:e});s=Sa.getJoinedLiveList(),t=t.isUnlimitedAVChatRoom(),!t&&0<s.length&&this.stopMessageLongPolling({groupID:s[0].groupID}),i.debug("startMessageLongPolling",this._name+`.startMessageLongPolling isUnlimited:${t} groupID:${e} longPollingKey:${n} longPollingSequence:`+o),s={groupID:e,type:r.GRP_LIVE};return Sa.updateLocalLiveGroup(e,s),this._getLiveHistoryMessages({groupID:e,longPollingKey:n,startSequence:o}),Sa.startMessageLongPolling({group:s,longPollingKey:n,startSequence:o})}stopMessageLongPolling(e){e=e.groupID;return Sa.reset(e),this._core.ssoLog.debug("stopMessageLongPolling",this._name+".stopMessageLongPolling ok, groupID:"+e),Promise.resolve({groupID:e})}_getLiveHistoryMessages(i){return I(this,void 0,void 0,function*(){var t=this._core["ssoLog"],s=i["groupID"];try{var e=yield function(r,i){return I(this,void 0,void 0,function*(){var{groupID:e,longPollingKey:t,startSequence:s}=r;return i.common.buildAndSendPacket({servcmd:"group_open_http_svc.get_huge_group_msg",data:{GroupId:e,LongPollingKey:t,PullPreSeq:s}})})}(i,this._core),{RspMsgList:r=[]}=e||{};t.debug("_getLiveHistoryMessages",this._name+`._getLiveHistoryMessages ok, groupID:${s} count:`+r.length),0<r.length&&Sa.handleLiveHistoryMessages(s,r)}catch(e){t.debug("_getLiveHistoryMessages",this._name+`._getLiveHistoryMessages failed, groupID:${s} info:`+e.message)}})}},ba=new class{constructor(){this.name="AVChatRoom"}install(e,t){this._core=e,la.init(e),Sa.init(e,t),La.init(e,t),Na.init(e);var{notificationCenter:t,InnerEvent:e}=e,s=t["InnerEventSubType"];t.subscribeInnerEvent(e.MESSAGE_PUSH,s.GROUP_SYSTEM_NOTIFICATION,this._onAVChatRoomSystemNotification,this),t.subscribeInnerEvent(e.LOGOUT,this._reset,this),t.subscribeInnerEvent(e.DESTROY,this._dispose,this)}_onAVChatRoomSystemNotification(e){Sa.onAVChatRoomSystemNotification(e)}_reset(){Sa.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 R="friend",Ga="Tag_SNS_IM_",Pa={GROUP:Ga+"Group",REMARK:Ga+"Remark",ADDSOURCE:Ga+"AddSource",ADDWORDING:Ga+"Wording",ADDTIME:Ga+"AddTime"},wa="Update_Type_Add",Ua="Update_Type_Delete",ka="remove",Fa=e=>void 0===e;function qa(e,t="ResultItem",s=e=>({userID:e.To_Account,resultCode:e.ResultCode,resultInfo:e.ResultInfo})){var{[t]:e=[],ActionStatus:t,ErrorCode:r,ErrorInfo:i,ErrorDisplay:n}=e;return{resultList:e.map(s),actionStatus:t,errorCode:r,errorInfo:i,errorDisplay:n}}let xa={[Pa.REMARK]:(e,t)=>{e.remark=t},[Pa.GROUP]:(e,t)=>{e.groupList=t?JSON.parse(JSON.stringify(t)):[]},[Pa.ADDSOURCE]:(e,t)=>{e.source=t},[Pa.ADDWORDING]:(e,t)=>{e.wording=t},[Pa.ADDTIME]:(e,t)=>{e.addTime=t}},Va=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}),xa[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=xa[t];null!=e&&e(this,s)})}};var Ba=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 I(this,void 0,void 0,function*(){var{appStore:{userStore:e},ssoLog:t,utils:{safeStringify:s}}=this._core,e=[...e.getFriendMap().values()];return t.debug("getFriendListFromCache",R+" getFriendListFromCache, data:"+s(e)),{code:0,data:e}})}syncFriendListFromServer(){return I(this,void 0,void 0,function*(){let a,{ssoLog:u,helper:t}=this._core;try{u.debug("syncFriendListFromServer",R+" syncFriendListFromServer");let e={From_Account:null==(a=this._core.store.get("login"))?void 0:a.userId,StartIndex:this._startIndex,StandardSequence:this._standardSequence,CustomSequence:this._customSequence},t=yield function(c,d){return I(this,void 0,void 0,function*(){var{UserDataItem:e=[],StandardSequence:t,CustomSequence:s,FriendNum:r,CompleteFlag:i,NextStartIndex:n,ActionStatus:o,ErrorCode:a,ErrorInfo:u,ErrorDisplay:l}=e=yield d.common.buildAndSendPacket({servcmd:"sns.friend_get",data:c});return{friendList:e.map(e=>{return{userID:e.To_Account,tagValueList:null==(e=e.ValueItem)?void 0:e.map(e=>({tag:e.Tag,value:e.Value}))}}),standardSequence:t,customSequence:s,friendNumber:r,completeFlag:i,nextStartIndex:n,actionStatus:o,errorCode:a,errorInfo:u,errorDisplay:l}})}(e,this._core),{friendList:s,nextStartIndex:r,standardSequence:i,customSequence:n,completeFlag:o}=t;this._startIndex=r,this._standardSequence=i,this._customSequence=n,this._processFriendList(s),0===o?yield this.syncFriendListFromServer():(this._emitFriendListUpdated(),this._fetchFriendProfile()),u.debug("syncFriendListFromServer",R+" syncFriendListFromServer ok")}catch(a){let e=(a||{})["errorCode"];throw new t.ChatError({code:e})}})}getFriendProfile(u){return I(this,void 0,void 0,function*(){var t;try{let e=u["userIDList"];100<e.length&&(e=e.slice(0,100));var s,r,i,{friendUserIdList:n,unFriendUserIdList:o}=this.partitionByIsFriend(e),a=this._createNonFriendErrorList(o);return 0===n.length?{code:0,data:{friendList:[],failureUserIDList:a}}:(s=(yield function(n,o){return I(this,void 0,void 0,function*(){var{InfoItem:e=[],ActionStatus:t,ErrorCode:s,ErrorInfo:r,ErrorDisplay:i}=e=yield o.common.buildAndSendPacket({servcmd:"sns.friend_get_specified",data:n});return{friendProfileList:e.map(e=>{return{userID:e.To_Account,resultCode:e.ResultCode,resultInfo:e.ResultInfo,relation:e.Relation,standardSequence:e.StandardSequence,customSequence:e.CustomSequence,profileItem:(null==(e=e.SnsProfileItem)?void 0:e.map(e=>({tag:e.Tag,value:e.Value})))||[]}}),actionStatus:t,errorCode:s,errorInfo:r,errorDisplay:i}})}({From_Account:null==(t=this._core.store.get("login"))?void 0:t.userId,To_Account:n},this._core))||{},{successProfiles:r,failedProfiles:i}=this._processFriendProfileResponse(s),{code:0,data:{friendList:r,failureUserIDList:[...i,...a]}})}catch(e){let t=(e||{})["errorCode"];throw new this._core.helper.ChatError({code:t})}})}addFriend(g){return I(this,void 0,void 0,function*(){var e,{helper:s,store:t,ssoLog:r}=this._core;try{var{to:i,source:n,type:o,wording:a,remark:u,groupName:l}=g,c=yield function(e,t){return I(this,void 0,void 0,function*(){return qa(yield t.common.buildAndSendPacket({servcmd:"sns.friend_add",data:e}))})}({From_Account:null==(e=t.get("login"))?void 0:e.userId,AddFriendItem:[{To_Account:i,AddSource:n,AddWording:a,GroupName:l,Remark:u}],AddType:o},this._core),{resultList:d=[]}=c,{userID:p,resultCode:h}=d[0];if(0===h)return r.debug("addFriend",R+" addFriend ok"),{code:0,data:{userID:p}};if(30539===h)return r.debug("addFriend",R+" addFriend wait for the other party to agree"),{code:0,data:{userID:p,code:h,message:"wait for the other party to agree"}};throw new s.ChatError({functionName:"addFriend",code:h})}catch(e){let t=(e||{})["errorCode"];throw new s.ChatError({code:t})}})}deleteFriend(p){return I(this,void 0,void 0,function*(){var s,{store:r,ssoLog:i,helper:n}=this._core;try{let{userIDList:e,type:t}=p;var o,a,u,l=null==(s=r.get("login"))?void 0:s.userId,{friendUserIdList:c,unFriendUserIdList:d}=(1e3<e.length&&(i.info("deleteFriend",R+" deleteFriend the length of userIDList cannot exceed:1000"),e=e.slice(0,100)),this.partitionByIsFriend(e));return 0===c.length?{code:0,data:{friendList:[],failureUserIDList:this._createNonFriendErrorList(d)}}:(o=yield function(e,t){return I(this,void 0,void 0,function*(){return qa(yield t.common.buildAndSendPacket({servcmd:"sns.friend_delete",data:e}))})}({From_Account:l,To_Account:c,DeleteType:t},this._core),{successUserIDList:a,failureUserIDList:u}=this._processOperationResult({resultList:o.resultList,includeRelation:!1}),{code:0,data:{successUserIDList:a,failureUserIDList:u}})}catch(e){let t=(e||{})["errorCode"];throw new n.ChatError({code:t})}})}updateFriend(p){return I(this,void 0,void 0,function*(){var e,{helper:s,store:t,appStore:{userStore:r}}=this._core;try{var{userID:i,remark:n,friendCustomField:o}=p,a=null==(e=t.get("login"))?void 0:e.userId;if(!r.getFriendMap().has(i))throw new s.ChatError({functionName:"updateFriend",code:2700});var u=(yield function(e,t){return I(this,void 0,void 0,function*(){return qa(yield t.common.buildAndSendPacket({servcmd:"sns.friend_update",data:e}),"ResultItem",e=>({to:e.To_Account,resultCode:e.ResultCode,resultInfo:e.ResultInfo}))})}({From_Account:a,UpdateItem:[{To_Account:i,SnsItem:this._buildSnsItemList(n,o)}]},this._core))["resultList"],{to:l,resultCode:c,resultInfo:d}=u[0];if(Fa(c)||0===c)return{code:0,data:this._updateLocalFriend({userID:l,remark:n,friendCustomField:o})};throw new s.ChatError({functionName:"updateFriend",code:c,message:d})}catch(e){let t=(e||{})["errorCode"];throw new s.ChatError({code:t})}})}checkFriend(c){return I(this,void 0,void 0,function*(){var a;let{OuterConstant:u,store:l,helper:s}=this._core;try{let{userIDList:e,type:t}=c,s=null==(a=l.get("login"))?void 0:a.userId,r={From_Account:s,To_Account:e,CheckType:t===u.SNS_CHECK_TYPE_SINGLE?t:u.SNS_CHECK_TYPE_BOTH},i=yield function(e,t){return I(this,void 0,void 0,function*(){return qa(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}))})}(r,this._core),{successUserIDList:n=[],failureUserIDList:o=[]}=this._processOperationResult({resultList:i.resultList,includeRelation:!0});return{code:0,data:{successUserIDList:n,failureUserIDList:o}}}catch(e){let t=(e||{})["errorCode"];throw new s.ChatError({code:t})}})}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(n){return I(this,void 0,void 0,function*(){var{ssoLog:e,utils:{safeStringify:t}}=this._core;e.debug("updateFriendList",R+" updateFriendList data:"+t(n));let s=this._core.appStore["userStore"],{addedFriendList:r=[],removedFriendList:i=[]}=n;0<r.length&&(r.forEach(e=>{var t=new Va({userID:e,core:this._core});s.getFriendMap().set(e,t)}),yield this.getFriendProfile({userIDList:r}),this._emitFriendListUpdated()),0<i.length&&(i.forEach(e=>{s.getFriendMap().delete(e)}),this._emitFriendListUpdated())})}updateFriendInfo(e){var{ssoLog:t,utils:{safeStringify:s}}=this._core;t.debug("updateFriendList",R+" updateFriendInfo data:"+s(e));let{appStore:{userStore:r,conversationStore:i},utils:{isEmpty:n}}=this._core,{userID:o,tagValueList:a}=e[0]||{},u=r.getFriend(o);if(!n(a)&&u){let r=a.map(e=>({tag:e.BytesTag,value:e.BytesValue}));r.forEach(e=>{var{tag:e,value:t}=e,s=null==(s=i.getConversation("C2C"+o))?void 0:s.remark;e===Pa.REMARK&&t!==s&&i.updateConversation("C2C"+o,{remark:t}),u.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 Va({userID:e,tagValueList:t,core:this._core}),s.getFriendMap().set(e,t))})}_isInvalidFriend(e){return"@TLS#NOT_FOUND"===e||""===e}_fetchFriendProfile(){return I(this,void 0,void 0,function*(){let{appStore:{userStore:n},user:{userProfile:o},ssoLog:e}=this._core,a=(e.debug("_fetchFriendProfile",R+" _fetchFriendProfile"),[...n.getFriendMap().keys()]),t=Math.ceil(a.length/100);for(let i=0;i<t;i++){let e=100*i,t=Math.min(100+e,a.length),s=a.slice(e,t),r=yield null==o?void 0:o.getUserProfile({userIDList:s});r&&r.data&&r.data.forEach(e=>{var t=n.getFriend(e.userID);t&&(t.profile=e)}),this._emitFriendListUpdated()}})}_emitFriendListUpdated(){var{notificationCenter:e,OuterEvent:t,appStore:{userStore:s}}=this._core,s=Array.from(s.getFriendMap().values());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 i=!1;return e.forEach(({key:t,value:e})=>{var s=r.find(e=>e.key===t);s?s.value!==e&&(s.value=e,i=!0):(r.push({key:t,value:e}),i=!0)}),i}_updateLocalFriend(e){var t=this._core.appStore["userStore"],{userID:e,remark:s,friendCustomField:r}=e,t=t.getFriend(e);if(t)return Fa(s)||(t.remark=s),Array.isArray(r)&&0<r.length&&this._updateCustomField(t.friendCustomField,r),this._emitFriendListUpdated(),t}_processOperationResult(e){let{resultList:t,includeRelation:i=!1}=e,s=this._core.utils["isEmpty"],n=[],o=[];return Array.isArray(t)&&!s(t)&&t.forEach(e=>{var{userID:t,relation:s,resultCode:e,resultInfo:r}=e;if(Fa(e)||0===e){let e={userID:t};i&&(e.code=0,e.relation=s),n.push(e)}else o.push({userID:t,code:e,message:r})}),{successUserIDList:n,failureUserIDList:o}}_createNonFriendErrorList(e){return e.map(e=>({userID:e,code:2700,message:"The specified userID is not my friend"}))}_buildSnsItemList(e,t){let s=[];return Fa(e)||s.push({Tag:Pa.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,i=this._core.appStore["userStore"],n=[],o=[];return t.forEach(e=>{var{userID:t,resultCode:e,resultInfo:s,profileItem:r}=e;if(0===e){let e=new Va({userID:t,tagValueList:r,core:this._core});n.push(e),i.getFriendMap().set(t,e)}else o.push({userID:t,code:e,message:s})}),{successProfiles:n,failedProfiles:o}}partitionByIsFriend(e){let s=[],r=[];return e.forEach(e=>{var t=this._core.appStore["userStore"];(t.getFriendMap().has(e)?s:r).push(e)}),{friendUserIdList:s,unFriendUserIdList:r}}isMyFriend(e){var t=this._core.appStore["userStore"];return t.getFriendMap().has(e)}},ja=new class{init(e){this.core=e}};function Ka(s){return I(this,void 0,void 0,function*(){var{store:e,common:t}=ja.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 Ya(yield t.buildAndSendPacket({servcmd:"sns.friend_response",data:e}))})}function Wa(s){return I(this,void 0,void 0,function*(){var{store:e,common:t}=ja.core,e={From_Account:null==(e=e.get("login"))?void 0:e.userId,ResponseFriendItem:[{To_Account:s.userID,ResponseAction:"Response_Action_Reject"}]};return Ya(yield t.buildAndSendPacket({servcmd:"sns.friend_response",data:e}))})}function Ha(s){return I(this,void 0,void 0,function*(){var{store:e,common:t}=ja.core,e={From_Account:null==(e=e.get("login"))?void 0:e.userId,To_Account:[s.userID],PendencyType:s.type};return Ya(yield t.buildAndSendPacket({servcmd:"sns.pendency_delete",data:e}))})}function Ya(e){var{ResultItem:e=[],ActionStatus:t,ErrorCode:s,ErrorInfo:r,ErrorDisplay:i}=e;return{resultList:e.map(e=>({userID:e.To_Account,resultCode:e.ResultCode,resultInfo:e.ResultInfo})),actionStatus:t,errorCode:s,errorInfo:r,errorDisplay:i}}var $a=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 I(this,void 0,void 0,function*(){var{ssoLog:e,utils:{safeStringify:t}}=this._core,s=[...this._friendApplicationMap.values()];return e.debug("getFriendApplicationListFromCache",R+" getFriendApplicationListFromCache friendApplicationList:"+t(s)),{code:0,data:{friendApplicationList:s,unreadCount:this._unreadCount}}})}syncFriendApplicationListFromServer(){return I(this,void 0,void 0,function*(){let{ssoLog:e,utils:{safeStringify:t}}=this._core,s="syncFriendApplicationListFromServer";try{let e=yield function(u){return I(this,void 0,void 0,function*(){var{store:e,OuterConstant:t,common:s}=ja.core,e={From_Account:null==(e=e.get("login"))?void 0:e.userId,PendencyType:t.SNS_APPLICATION_TYPE_BOTH,MaxLimited:100,StartTime:u.startTime,LastSequence:u.currentSequence},{PendencyItem:t=[],StartTime:s,UnreadPendencyCount:e,CurrentSequence:r,ActionStatus:i,ErrorCode:n,ErrorInfo:o,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:i,errorCode:n,errorInfo:o,errorDisplay:a}})}({startTime:this._startTime,currentSequence:this._currentSequence}),{resultList:t,unreadCount:s,startTime:r,currentSequence:i}=e;this._startTime=r,this._currentSequence=i,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(t){var r=new this._core.helper.ChatError({functionName:s,code:null==t?void 0:t.errorCode,message:null==t?void 0:t.errorInfo});throw e.error("syncFriendApplicationListFromServer",R+` ${s} error:`,{error:r}),r}})}acceptFriendApplication(e){return I(this,void 0,void 0,function*(){return this._operationApplication({functionName:"acceptFriendApplication",options:e,protocolFunction:Ka})})}refuseFriendApplication(e){return I(this,void 0,void 0,function*(){return this._operationApplication({functionName:"refuseFriendApplication",options:e,protocolFunction:Wa})})}deleteFriendApplication(s){return I(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:Ha})})}_checkApplicationExists(e,t,s){if(!this._friendApplicationMap.has(e+"_"+t))throw new this._core.helper.ChatError({functionName:s,code:2716})}_operationApplication(e){return I(this,void 0,void 0,function*(){let{functionName:i,options:n,protocolFunction:o}=e;console.log(R+` ${i} options:`,n);try{let e=yield o(n),{resultList:t=[]}=e,{resultCode:s,resultInfo:r}=t[0];if(0===s)return console.log(R+` ${i} ok`),{code:0,data:{}};throw{errorCode:s,errorInfo:r}}catch(e){let t=new this._core.helper.ChatError({functionName:i,code:null==e?void 0:e.errorCode,message:null==e?void 0:e.errorInfo});throw console.error(R+` ${i} error:`,t),t}})}setFriendApplicationRead(){return I(this,void 0,void 0,function*(){try{return yield function(){return I(this,void 0,void 0,function*(){var{store:e,common:t}=ja.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(),{code:0,data:{}}}catch(e){throw new this._core.helper.ChatError({functionName:"setFriendApplicationRead",code:null==e?void 0:e.errorCode,message:null==e?void 0:e.errorInfo})}})}updateFriendApplicationList(e){var{from:e,addedApplicationList:t=[],removedApplicationList:s=[]}=e,r=this._core.utils["isEmpty"];r(t)||this.onApplicationAdded(t,e),r(s)||this.onApplicationDeleted()}onApplicationAdded(e,t){let s,{store:r,OuterConstant:i}=this._core,n=t===(null==(s=r.get("login"))?void 0:s.userId)?i.SNS_APPLICATION_SENT_BY_ME:i.SNS_APPLICATION_SENT_TO_ME;e.forEach(e=>{var t=e.userID+"_"+n;n!==i.SNS_APPLICATION_SENT_TO_ME||this._friendApplicationMap.has(t)||(this._unreadCount+=1),this._friendApplicationMap.set(t,this._createFriendApplication(Object.assign(Object.assign({},e),{type:n})))}),this._emitApplicationListUpdated()}onApplicationDeleted(){this._startTime=0,this._currentSequence=0,this.syncFriendApplicationListFromServer()}onApplicationRead(){this._unreadCount=0,this._emitApplicationListUpdated()}reset(){this._startTime=0,this._currentSequence=0,this._unreadCount=0,this._friendApplicationMap.clear()}dispose(){this.reset()}_createFriendApplication(e){return{userID:e.userID||"",nick:e.nick||"",avatar:e.avatar||"",time:e.time||0,source:e.source||"",wording:e.wording||"",type:e.type||""}}_emitApplicationListUpdated(){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 za(r){return I(this,void 0,void 0,function*(){var e=ja.core["common"],{name:t,userIDList:s}=r,s=Qa(s,wa),t={From_Account:e.getCurrentUserID(),GroupOldName:t,UpdateGroupItem:s};return Xa(yield e.buildAndSendPacket({servcmd:"sns.group_update",data:t}),e=>({userID:e.To_Account,updateType:e.UpdateType,resultCode:e.ResultCode,resultInfo:e.ResultInfo}))})}function Ja(r){return I(this,void 0,void 0,function*(){var e=ja.core["common"],{name:t,userIDList:s}=r,s=Qa(s,Ua),t={From_Account:e.getCurrentUserID(),GroupOldName:t,UpdateGroupItem:s};return Xa(yield e.buildAndSendPacket({servcmd:"sns.group_update",data:t}),e=>({userID:e.To_Account,updateType:e.UpdateType,resultCode:e.ResultCode,resultInfo:e.ResultInfo}))})}function Qa(e,t){return e.filter(e=>Ba.isMyFriend(e)).map(e=>({To_Account:e,UpdateType:t}))}function Xa(e,t){var{CurrentSequence:e,ActionStatus:s,ErrorCode:r,ErrorInfo:i,ErrorDisplay:n,ResultItem:o=[]}=e,e={currentSequence:e,actionStatus:s,errorCode:r,errorInfo:i,errorDisplay:n};return t&&0<o.length?Object.assign(Object.assign({},e),{resultList:o.map(t)}):e}class Za{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 eu=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 I(this,void 0,void 0,function*(){var{ssoLog:e,utils:{safeStringify:t}}=this._core,s=[...this._friendGroupMap.values()];return e.debug(R+" getFriendGroupListFromCache, data:"+t(s)),{code:0,data:s}})}syncFriendGroupListFromServer(){return I(this,void 0,void 0,function*(){var e=this._core["ssoLog"],t="syncFriendGroupListFromServer";try{var s=yield function(){return I(this,void 0,void 0,function*(){var e=ja.core["common"],t={From_Account:e.getCurrentUserID(),LastSequence:0,NeedFriend:"Need_Friend_Type_Yes"};return Xa(yield e.buildAndSendPacket({servcmd:"sns.group_get",data:t}),e=>({name:e.GroupName,userIDList:e.To_Account||[],count:e.FriendNumber}))})}(),{resultList:r=[]}=s;this._core.helper.isEmpty(r)&&e.debug("syncFriendGroupListFromServer",R+` ${t} ok. count: 0`),r.forEach(e=>{var t=new Za(e);this._friendGroupMap.set(e.name,t)}),this._emitGroupListUpdated()}catch(e){this._handleError(t,e)}})}createFriendGroup(o){return I(this,void 0,void 0,function*(){var t="createFriendGroup";try{var e=o["name"],s=(this._checkGroupExist(t,e),yield function(r){return I(this,void 0,void 0,function*(){var{name:e,userIDList:t}=r,s=ja.core["common"],e={From_Account:s.getCurrentUserID(),GroupName:[e],To_Account:t};return Xa(yield s.buildAndSendPacket({servcmd:"sns.group_add",data:e}),e=>({userID:e.To_Account,resultCode:e.ResultCode,resultInfo:e.ResultInfo}))})}(o)),{successUserIDList:r,failureUserIDList:i}=this._parseCreateGroupResponse(s),n=new Za({name:e,userIDList:r});return this._friendGroupMap.set(e,n),this._emitGroupListUpdated(),{code:0,data:{friendGroup:n,failureUserIDList:i}}}catch(e){this._handleError(t,e)}})}deleteFriendGroup(r){return I(this,void 0,void 0,function*(){var t="deleteFriendGroup";try{var e=r["name"],s=(this._checkGroupNotExist(t,e),yield function(s){return I(this,void 0,void 0,function*(){var e=ja.core["common"],t={From_Account:e.getCurrentUserID(),GroupName:[s.name]};return Xa(yield e.buildAndSendPacket({servcmd:"sns.group_delete",data:t}))})}(r),this._friendGroupMap.get(e));return s&&(this._updateFriendGroup({name:e,userIDList:s.userIDList,action:ka}),this._friendGroupMap.delete(e)),this._emitGroupListUpdated(),{code:0,data:s}}catch(e){this._handleError(t,e)}})}addToFriendGroup(e){return I(this,void 0,void 0,function*(){return this._updateFriendGroupMember({functionName:"addToFriendGroup",params:e,protocolFunction:za})})}removeFromFriendGroup(e){return I(this,void 0,void 0,function*(){return this._updateFriendGroupMember({functionName:"removeFromFriendGroup",params:e,protocolFunction:Ja})})}renameFriendGroup(i){return I(this,void 0,void 0,function*(){var t="renameFriendGroup";try{var{oldName:e,newName:s}=i,r=(this._checkGroupNotExist(t,e),this._checkGroupExist(t,s),yield function(r){return I(this,void 0,void 0,function*(){var e=ja.core["common"],{oldName:t,newName:s}=r,t={From_Account:e.getCurrentUserID(),GroupOldName:t,GroupNewName:s};return Xa(yield e.buildAndSendPacket({servcmd:"sns.group_update",data:t}))})}(i),this._updateGroupNameInCache(e,s));return r&&this._updateFriendGroup({name:e,userIDList:r.userIDList,action:"rename",newName:s}),this._emitGroupListUpdated(),{code:0,data:r}}catch(e){this._handleError(t,e)}})}_updateFriendGroupMember(e){return I(this,void 0,void 0,function*(){var{functionName:t,params:s,protocolFunction:r}=e;try{let e=s["name"];this._checkGroupNotExist(t,e);var i=yield r(s),{friendGroup:n,failureUserIDList:o}=this._parseUpdateFriendGroupResponse(e,i);return this._emitGroupListUpdated(),{code:0,data:{friendGroup:n,failureUserIDList:o}}}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=[],i=[];return t.forEach(({userID:e,resultCode:t,resultInfo:s})=>{Fa(t)||0===t?r.push(e):i.push({userID:e,code:t,message:s})}),{successUserIDList:r,failureUserIDList:i}}_parseUpdateFriendGroupResponse(t,e){let{resultList:s=[]}=e,r=this._friendGroupMap.get(t),i=[],n=[],o=[];return s.forEach(e=>{0===e.resultCode?r&&(e.updateType===wa?this._addFriendToGroup(t,e.userID,r,n):e.updateType===Ua&&this._removeFriendFromGroup(t,e.userID,r,o)):i.push({userID:e.userID,code:e.resultCode,message:e.resultInfo})}),{friendGroup:r,failureUserIDList:i}}_addFriendToGroup(e,t,s,r){s.addToUserIDList(t),r.push(t),this._updateFriendGroup({name:e,userIDList:r,action:"add"})}_removeFriendFromGroup(e,t,s,r){s.removeFromUserIDList(t),r.push(t),this._updateFriendGroup({name:e,userIDList:r,action:ka})}_emitGroupListUpdated(){var{notificationCenter:e,OuterEvent:t}=this._core,s=[...this._friendGroupMap.values()];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:2711})}_checkGroupExist(e,t){if(this._friendGroupMap.has(t))throw new this._core.helper.ChatError({functionName:e,code:2710})}_updateFriendGroup(e){let{name:r,userIDList:t,action:i,newName:n}=e,o=this._core.appStore["userStore"];r&&!this._core.utils.isEmpty(t)&&t.forEach(e=>{var t=o.getFriend(e);if(t){var s=t["groupList"];switch(i){case"add":-1===s.indexOf(r)&&(s.push(r),t.count=s.length);break;case ka:{let e=s.indexOf(r);-1<e&&(s.splice(e,1),t.count=s.length);break}case"rename":if(n){let e=s.indexOf(r);-1!==e&&(s[e]=n)}}}})}_handleError(e,t){throw new this._core.helper.ChatError({functionName:e,code:null==t?void 0:t.errorCode,message:null==t?void 0:t.errorInfo})}reset(){this._friendGroupMap.clear()}dispose(){this.reset()}};function tu(e){return e&&0!==e.length?e.map(e=>({userID:e.To_Account,addBlackTimeStamp:e.AddBlackTimeStamp})):[]}var su=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 I(this,void 0,void 0,function*(){return{code:0,data:Array.from(this._blacklistMap.keys())}})}syncBlacklistFromServer(){return I(this,void 0,void 0,function*(){try{this._core.ssoLog.debug(R+" syncBlacklistFromServer");var e=yield function(r,i){return I(this,void 0,void 0,function*(){var{helper:e,channel:t}=i,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:tu(t),startIndex:e}})}({From_Account:this._core.common.getCurrentUserID(),MaxLimited:100,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,e}})}addToBlacklist(i){return I(this,void 0,void 0,function*(){let t=this._core["helper"];try{let e=this._preprocessBlacklist(i),t={From_Account:this._core.common.getCurrentUserID(),To_Account:e},s=yield function(r,i){return I(this,void 0,void 0,function*(){var{helper:e,channel:t}=i,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:tu(t)}})}(t,this._core),{blackList:r=[]}=s;return this._addBlacklistMap(r),this._emitBlackListUpdated(),{code:0,data:Array.from(this._blacklistMap.keys())}}catch(e){var s=(e||{})["errorCode"];throw new t.ChatError({code:s})}})}removeFromBlacklist(r){return I(this,void 0,void 0,function*(){let t=this._core["helper"];try{let e={From_Account:this._core.common.getCurrentUserID(),To_Account:r.userIDList},t=yield function(r,i){return I(this,void 0,void 0,function*(){var{helper:e,channel:t}=i,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:tu(t)}})}(e,this._core),{blackList:s=[]}=t;return this._deleteBlacklistMap(s),this._emitBlackListUpdated(),{code:0,data:Array.from(this._blacklistMap.keys())}}catch(e){var s=(e||{})["errorCode"];throw new t.ChatError({code:s})}})}dispose(){this.reset()}reset(){this._retryCount=0,this._startIndex=0,this._blacklistMap.clear()}updateBlacklist(e){var{ssoLog:t,utils:{safeStringify:s}}=this._core,{addedBlacklist:t=[],removedBlacklist:s=[]}=(t.debug("updateBlacklist",R+" updateBlacklist data: "+s(e)),e);let r=!1;0<t.length&&t.some(e=>!this._blacklistMap.has(e))&&(r=!0,this._addBlacklistMap(t.map(e=>({userID:e})))),0<s.length&&s.some(e=>this._blacklistMap.has(e))&&(r=!0,this._deleteBlacklistMap(s.map(e=>({userID:e})))),r&&this._emitBlackListUpdated()}_addBlacklistMap(e){var{ssoLog:t,utils:{safeStringify:s}}=this._core;t.debug("_addBlacklistMap",R+" _addBlacklistMap blackList: "+s(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){var{ssoLog:t,utils:{safeStringify:s}}=this._core;t.debug("_deleteBlacklistMap",R+" _deleteBlacklistMap blackList: "+s(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:2742});return t=t.includes(s)?e.userIDList.filter(e=>e!==s):t}_emitBlackListUpdated(){var{notificationCenter:e,OuterEvent:t,ssoLog:s,utils:{safeStringify:r}}=this._core,i=Array.from(this._blacklistMap.keys());s.debug(R+" _emitBlackListUpdated blackList:"+r(i)),e.emitOuterEvent(t.BLACKLIST_UPDATED,{name:t.BLACKLIST_UPDATED,data:i})}};let ru={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=ja.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=ja.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=ja.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=ja.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}}},iu={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},nu=new class{constructor(){this.name="Friend"}install(e){e.ssoLog.debug(R+" install");var{helper:t,notificationCenter:s,InnerEvent:r,constants:{WORKFLOW_NAME:i,WORKFLOW_STEP:n}}=this._core=e;ja.init(e),Ba.init(e),$a.init(e),eu.init(e),su.init(e),t.registerValidateConfig({auth:iu,params:ru}),t.registerWorkflowStep(i.SYNC_SERVER_INFO_AFTER_LOGIN,n.FRIEND_AND_BLACKLIST_SYNC,this.handleLoginSuccess,this),s.subscribeInnerEvent(r.LOGOUT,this.reset,this),s.subscribeInnerEvent(r.MESSAGE_PUSH,s.InnerEventSubType.FRIEND_LIST_MODIFIED,this.onFriendModified,this)}handleLoginSuccess(){su.syncBlacklistFromServer(),Ba.syncFriendListFromServer(),$a.syncFriendApplicationListFromServer(),eu.syncFriendGroupListFromServer()}onFriendModified(e){var{from:e,addedBlacklist:t,removedBlacklist:s,addedFriendList:r,removedFriendList:i,addedApplicationList:n,removedApplicationList:o,friendUpdateInfo:a,reportTime:u}=this._parseFriendListModification(null==e?void 0:e.FriendListMod[0]),l=this._core.utils["isEmpty"];l(t)&&l(s)||su.updateBlacklist({addedBlacklist:t,removedBlacklist:s}),l(r)&&l(i)||(Ba.updateFriendList({addedFriendList:r,removedFriendList:i}),$a.updateFriendApplicationList({from:e,removedApplicationList:r})),l(a)||Ba.updateFriendInfo(a),l(n)&&l(o)||$a.updateFriendApplicationList({from:e,addedApplicationList:n,removedApplicationList:o}),u&&$a.onApplicationRead()}_parseFriendListModification(e){var{PushType:e,From_Account:t,To_Account:s,ReportTime:r,BlackListAdd_Account:i=[],BlackListDel_Account:n=[],FriendAdd_Account:o=[],FriendDel_Account:a=[],PendencyAdd:u=[],FrienPencydDel_Account:l=[],FriendUpInfo:c=[]}=e,c=c.map(e=>({userID:e.Friend_Account,tagValueList:[...e.SNS]}));return{pushType:e,from:t,to:s,reportTime:r,addedBlacklist:i,removedBlacklist:n,addedFriendList:o,removedFriendList:a,addedApplicationList:u.map(e=>({userID:e.PendencyAdd_Account,source:e.AddSource,time:e.AddTime,wording:e.AddWording,nick:e.ProfileImNick})),friendUpdateInfo:c,removedApplicationList:l}}reset(){su.reset(),Ba.reset(),$a.reset(),eu.reset()}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),su.dispose(),Ba.dispose(),$a.dispose(),eu.dispose()}},ou=new class{init(e){this.core=e}},au="Follow",uu={NONE:0,FOLLOWERS:1,FOLLOWING:2,MUTUAL:3};function lu(o,a){return I(this,void 0,void 0,function*(){var{common:e,store:t}=ou.core,t={FollowType:o,From_Account:null==(t=t.get("login"))?void 0:t.userId,StartCursor:a,WantNum:function(){let e=ou.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}}()},{FollowItem:e=[],NextCursor:t,ActionStatus:s,ErrorCode:r,ErrorInfo:i,ErrorDisplay:n}=e=yield e.buildAndSendPacket({servcmd:"follow.follow_get",data:t});return{resultList:e.map(e=>({userID:e.To_Account,followTime:e.FollowTime,profileItem:e.ProfileItem,profileSequence:e.ProfileSequence})),nextPageToken:t,actionStatus:s,errorCode:r,errorInfo:i,errorDisplay:n}})}function cu(e){return I(this,void 0,void 0,function*(){return lu(uu.FOLLOWERS,e)})}function du(e){return I(this,void 0,void 0,function*(){return lu(uu.MUTUAL,e)})}function pu(e){return I(this,void 0,void 0,function*(){return lu(uu.FOLLOWING,e)})}function hu(n){return I(this,void 0,void 0,function*(){var{common:e,store:t}=ou.core,t={From_Account:null==(t=t.get("login"))?void 0:t.userId,FollowItem:n.map(e=>({To_Account:e}))},{ResultItem:e=[],ActionStatus:t,ErrorCode:s,ErrorInfo:r,ErrorDisplay:i}=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:i}})}function gu(n){return I(this,void 0,void 0,function*(){var{common:e,store:t}=ou.core,t={From_Account:null==(t=t.get("login"))?void 0:t.userId,To_Account:n},{ResultItem:e=[],ActionStatus:t,ErrorCode:s,ErrorInfo:r,ErrorDisplay:i}=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:i}})}let _u={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}]},mu={getMyFollowersList:!0,getMyFollowingsList:!0,getMutualFollowersList:!0,followUser:!0,unfollowUser:!0,checkFollow:!0,getUserFollowInfo:!0},vu=new class{constructor(){this.name="Follow"}install(e){var{helper:t,notificationCenter:s,InnerEvent:r}=this._core=e;ou.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:mu,params:_u}),s.subscribeInnerEvent(r.MESSAGE_PUSH,s.InnerEventSubType.FOLLOW_LIST_UPDATED,this.onFollowListUpdated,this)}getMyFollowingList(){return I(this,arguments,void 0,function*(e=""){return this._getFollowList({functionName:"getMyFollowingList",protocolFunction:pu,nextCursor:e})})}getMyFollowersList(){return I(this,arguments,void 0,function*(e=""){return this._getFollowList({functionName:"getMyFollowersList",protocolFunction:cu,nextCursor:e})})}getMutualFollowersList(){return I(this,arguments,void 0,function*(e=""){return this._getFollowList({functionName:"getMutualFollowersList",protocolFunction:du,nextCursor:e})})}_getFollowList(e){return I(this,void 0,void 0,function*(){var{functionName:r,protocolFunction:i,nextCursor:n=""}=e;try{this._checkBusinessCapabilityBits(r);let e=yield i(n),{resultList:t=[],nextPageToken:s=""}=e;return{code:0,data:{resultList:this._parseFollowItems(t),nextCursor:s},successLog:{message:r+` nextCursor: ${n} from remote`}}}catch(e){this._handleError(r,e)}})}followUser(e){return I(this,void 0,void 0,function*(){return this._handleUserFollowRelation({functionName:"followUser",userIDList:e,protocolFunction:hu})})}unfollowUser(e){return I(this,void 0,void 0,function*(){return this._handleUserFollowRelation({functionName:"unfollowUser",userIDList:e,protocolFunction:gu})})}_handleUserFollowRelation(e){return I(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:i=[]}=yield r(e);return{code:0,data:i}}catch(e){this._handleError(t,e)}})}getUserFollowInfo(n){return I(this,void 0,void 0,function*(){var s="getUserFollowInfo";try{this._checkBusinessCapabilityBits(s);var i=n||[this._core.common.getCurrentUserID()];console.log(au+` ${s} userIDList: `+i);let e=yield function(n){return I(this,void 0,void 0,function*(){var{common:e,store:t}=ou.core,t={From_Account:null==(t=t.get("login"))?void 0:t.userId,To_Account:n},{FollowInfo:e=[],ActionStatus:t,ErrorCode:s,ErrorInfo:r,ErrorDisplay:i}=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:i}})}(n),{followInfoList:t=[]}=e,r=[];return t.forEach(e=>{var{followerCount:e,followingCount:t,mutualFollowingCount:s}=e;r.push({followerCount:e,followingCount:t,mutualFollowingCount:s})}),{code:0,data:r}}catch(e){this._handleError(s,e)}})}checkFollowType(r){return I(this,void 0,void 0,function*(){var t="checkFollowType";try{this._checkBusinessCapabilityBits(t),100<r.length&&(r=r.slice(0,100),this._core.ssoLog.warn(t,au+` ${t} the length of userIDList cannot exceed 100`));var e=yield function(n){return I(this,void 0,void 0,function*(){var{common:e,store:t}=ou.core,t={From_Account:null==(t=t.get("login"))?void 0:t.userId,To_Account:n},{ResultItem:e=[],ActionStatus:t,ErrorCode:s,ErrorInfo:r,ErrorDisplay:i}=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:i}})}(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){var{ssoLog:t,utils:{safeStringify:s}}=this._core,{FollowChangeList:t=[]}=(t.debug("onFollowListUpdated",au+" onFollowListUpdated "+s(e)),e);t.forEach(e=>this._processFollowChangeItem(e))}_processFollowChangeItem(e){let{From_Account:t,FollowDiffList:s=[]}=e,r=f(e,["From_Account","FollowDiffList"]),i={userID:t,avatar:r.FaceUrl,nick:r.NickName};s.forEach(e=>{e=this._updateFollowRelation(e,i);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={[uu.FOLLOWERS]:t.MY_FOLLOWERS_LIST_UPDATED,[uu.FOLLOWING]:t.MY_FOLLOWING_LIST_UPDATED,[uu.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(uu).forEach(e=>{e!==uu.NONE&&(t[e]={userInfoList:[],isAdd:!1})}),t}_emitFollowUpdated(e,t){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("FOLLOW"))throw new t.ChatError({functionName:e,code:3122,replacement1:e})}_handleError(e,t){throw new this._core.helper.ChatError({functionName:e,code:null==t?void 0:t.errorCode,message:null==t?void 0:t.errorInfo})}_parseFollowItems(e){return e.map(e=>{let t,{userID:s,followTime:r,profileItem:i=[]}=e,n=[];i.forEach(e=>{n.push({tag:e.Tag,value:e.Value})});e=null==(t=this._core.user.userProfile)?void 0:t.createProfile(s,n);return{userID:s,followTime:r,nick:null==e?void 0:e.nick,avatar:null==e?void 0:e.avatar,allowType:null==e?void 0:e.allowType,adminForbidType:null==e?void 0:e.adminForbidType}})}},fu=new class{init(e){this.core=e}},Iu="message",Eu="user",Cu={OR:"or",AND:"and"},Su={required:!1,rules:["array"],allowEmpty:!0,customValidator:e=>!e||!!(Array.isArray(e)&&e.length<=5)||"keywordList should be an array and length <= 5"},Mu={required:!1,rules:["string"],allowEmpty:!0,customValidator:e=>!e||!![Cu.OR,Cu.AND].includes(e)||"keywordListMatchType should be OR or AND"},yu={required:!1,rules:["number"],allowEmpty:!0,customValidator:e=>"number"==typeof e&&1<=e&&e<=100||"count must be a number between 1 and 100"},Tu={required:!1,rules:["string"],allowEmpty:!0},Au={required:!1,rules:["array"],allowEmpty:!0,customValidator:t=>{var e=fu.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"}},Ou={required:!1,rules:["array"],allowEmpty:!0,customValidator:t=>{var e=fu.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"}},Du={required:!1,rules:["string"],allowEmpty:!0,customValidator:e=>{var t=fu.core["OuterConstant"];return!!(null!=e&&e.startsWith(t.CONV_C2C)||null!=e&&e.startsWith(t.CONV_GROUP)||e===t.CONV_SYSTEM)||"conversationID is invalid"}},Ru=t=>({required:!1,rules:["number"],allowEmpty:!0,customValidator:e=>"number"==typeof e&&0<=e||t+" should be a number >= 0';"}),Lu={required:!1,rules:["string"],allowEmpty:!0,customValidator:e=>{var t=fu.core["OuterConstant"];return!![t.GENDER_FEMALE,t.GENDER_MALE].includes(e)||"gender is invalid"}},Nu={searchCloudMessages:{keywordList:Su,keywordListMatchType:Mu,cursor:Tu,senderUserIDList:{required:!1,rules:["array"],allowEmpty:!0,customValidator:e=>!!(Array.isArray(e)&&e.length<=5)||"senderUserIDList should be an array and length <= 5"},messageTypeList:Ou,conversationID:Du,timePosition:Ru("timePosition"),timePeriod:Ru("timePeriod")},searchCloudUsers:{keywordList:Su,keywordListMatchType:Mu,cursor:Tu,count:yu,miniBirthday:Ru("miniBirthday"),maxBirthday:Ru("maxBirthday"),gender:Lu},searchCloudGroupMembers:{keywordList:Su,keywordListMatchType:Mu,cursor:Tu,count:yu,groupTypeList:Au,groupIDList:{required:!1,rules:["array"],allowEmpty:!0}},searchCloudGroups:{keywordList:Su,keywordListMatchType:Mu,cursor:Tu,count:yu,groupTypeList:Au}},bu={searchCloudMessages:!0,searchCloudUsers:!0,searchCloudGroupMembers:!0,searchCloudGroups:!0},Gu=new class{constructor(){this.name="CloudSearch"}install(e){this._core=e,fu.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:bu,params:Nu})}searchCloudMessages(g){return I(this,void 0,void 0,function*(){try{let{OuterConstant:o,helper:a}=this._core,{conversationID:e,timePeriod:t,timePosition:s}=g,r=f(g,["conversationID","timePeriod","timePosition"]),i=Object.assign({count:100},r);e&&(e.startsWith(o.CONV_C2C)?i.account=e.replace(o.CONV_C2C,""):e.startsWith(o.CONV_GROUP)&&(i.groupID=e.replace(o.CONV_GROUP,""))),this._setTimeRangeParams(i,{timePeriod:t,timePosition:s});var n=yield function(c){return I(this,void 0,void 0,function*(){var{count:e,keywordList:t,keywordListMatchType:s,senderUserIDList:r,messageTypeList:i,endTime:n,startTime:o,cursor:a,account:u,groupID:l}=c,e={Count:e,KeywordList:t,MatchType:s,SendUserIDList:r,MsgTypeList:i,EndTime:n,StartTime:o,Cursor:a,PeerAccount:u,GroupID:l};return fu.core.common.buildAndSendPacket({servcmd:"message_search.query",data:e})})}(i);if(!n)return{code:0,data:{}};var{ErrorCode:u,ErrorInfo:l,TotalCount:c,Cursor:d="",ConversationMsgs:p=[]}=n;if(0!==u)throw{errorCode:u,errorInfo:l};var h=`keywordList:${g.keywordList} keywordListMatchType:${g.keywordListMatchType} cursor:${g.cursor} res: totalCount:`+c;return{code:0,data:{searchResultList:p.map(e=>{let{MsgList:t,Count:s,GroupID:i,UserID:r}=e,n=i?""+o.CONV_GROUP+i:""+o.CONV_C2C+r;return this._isSearchingAllConversations(g)&&1<s?{conversationID:n,messageCount:s,messageList:[]}:{conversationID:n,messageCount:s,messageList:t.map(e=>{return a.isEmpty(i)?(t=this._core,s=t.OuterConstant.CONV_C2C,r=t.message.messageHelper.parseServerPushMessage(e),(t=t.message.messageFactory.createMessage(Object.assign(Object.assign({},r),{conversationType:s,flow:"in"}))).setElement(r.elements),t):(s=this._core,r=s.OuterConstant.CONV_GROUP,t=s.message.messageHelper.parseServerGroupMessage(e),(s=s.message.messageFactory.createMessage(Object.assign(Object.assign({},t),{conversationType:r,flow:"in"}))).setElement(t.elements),s);var t,s,r})}}),cursor:d,totalCount:c},successLog:{message:h}}}catch(e){var{errorCode:n,errorInfo:u}=e||{};this._handleError({errorCode:n,errorInfo:u,searchType:Iu,functionName:"searchCloudMessages"})}})}searchCloudUsers(v){return I(this,void 0,void 0,function*(){var s;try{var{keywordListMatchType:e,count:t=20}=v,r=f(v,["keywordListMatchType","count"]),i=Object.assign({count:t,keywordListMatchType:e===Cu.AND?1:0},r),n=(this._setBirthdayRangeParams(i,v),yield function(a){return I(this,void 0,void 0,function*(){var{count:e,keywordList:t,keywordListMatchType:s,miniBirthday:r,maxBirthday:i,cursor:n,gender:o}=a,e={Count:e,Keywords:t,KeywordMatchType:s,Cursor:n,UserBirthStart:r,UserBirthEnd:i,Gender:o};return fu.core.common.buildAndSendPacket({servcmd:"user_search.query",data:e})})}(i));if(!n)return{error:0,data:{}};var{ErrorCode:o,ErrorInfo:a,TotalCount:u,Cursor:l="",Users:c=[]}=n;if(0!==o)throw{errorCode:o,errorInfo:a};var d=`keywordList:${v.keywordList} keywordListMatchType:${v.keywordListMatchType} cursor:${v.cursor} count:${v.count} res: totalCount:`+u,p=[];for(let e=0,t=c.length;e<t;e++){var h,g,{UserID:_,ProfileItems:m}=c[e];_!==this._core.OuterConstant.USER_NOT_FOUND&&""!==_&&(h=m.map(e=>({tag:e.Tag,value:e.StrValue})),g=null==(s=this._core.user.userProfile)?void 0:s.createProfile(_,h),p.push(g))}return{code:0,data:{searchResultList:p,cursor:l,totalCount:u},successLog:{message:d}}}catch(e){let{errorCode:t,errorInfo:s}=e||{};this._handleError({errorCode:t,errorInfo:s,searchType:Eu,functionName:"searchCloudUsers"})}})}searchCloudGroupMembers(d){return I(this,void 0,void 0,function*(){try{var{count:t=20,keywordListMatchType:s}=d,r=f(d,["count","keywordListMatchType"]),i=yield function(o){return I(this,void 0,void 0,function*(){var{count:e,keywordList:t,keywordListMatchType:s,groupTypeList:r,cursor:i,groupIDList:n}=o,e={Count:e,Keywords:t,KeywordMatchType:s,Cursor:i,GroupType:r,GroupIdList:n};return fu.core.common.buildAndSendPacket({servcmd:"group_member_search.query",data:e})})}(Object.assign({count:t,keywordListMatchType:s===Cu.AND?1:0},r));if(!i)return{code:0,data:{}};var{ErrorCode:n,ErrorInfo:o,GroupMembers:a=[],Cursor:l,TotalCount:c}=i;if(0!==n)throw{errorCode:n,errorInfo:o};let e=`keywordList:${d.keywordList} keywordListMatchType:${d.keywordListMatchType} cursor:${d.cursor} count:${d.count} res: totalCount:`+c,u=new Map;return a.forEach(e=>{var{GroupID:t,GroupName:e,GroupType:s,GroupFaceUrl:r,GroupMemberUserName:i,GroupMemberUserID:n,GroupMemberNameCard:o,GroupMemberAvatar:a=""}=e,e={groupID:t,name:e,type:s,avatar:r},s={userID:n,nick:i,nameCard:o,avatar:a};if(u.has(t)){let e=u.get(t);e.memberList.push(s),u.set(t,e)}else u.set(t,{groupInfo:e,memberList:[s]})}),{code:0,data:{searchResultList:[...u.values()],cursor:l,totalCount:c},successLog:{message:e}}}catch(e){var{errorCode:t,errorInfo:s}=e||{};this._handleError({errorCode:t,errorInfo:s,searchType:Eu,functionName:"searchCloudGroupMembers"})}})}searchCloudGroups(c){return I(this,void 0,void 0,function*(){try{var{count:t=20,keywordListMatchType:s}=c,e=f(c,["count","keywordListMatchType"]),r=yield function(n){return I(this,void 0,void 0,function*(){var{count:e,keywordList:t,keywordListMatchType:s,groupTypeList:r,cursor:i}=n,e={Count:e,Keywords:t,KeywordMatchType:s,Cursor:i,GroupType:r};return fu.core.common.buildAndSendPacket({servcmd:"group_search.query",data:e})})}(Object.assign({count:t,keywordListMatchType:s===Cu.AND?1:0},e));if(!r)return{code:0,data:{}};var{ErrorCode:i,ErrorInfo:n,Groups:o,Cursor:a,TotalCount:u}=r;if(0!==i)throw{errorCode:i,errorInfo:n};var l=`keywordList:${c.keywordList} keywordListMatchType:${c.keywordListMatchType} cursor:${c.cursor} count:${c.count} res: totalCount:`+u;return{code:0,data:{searchResultList:(null==o?void 0:o.map(e=>{var{GroupFaceUrl:e,GroupID:t,GroupIntroduction:s,GroupMemberNum:r,GroupName:i,GroupOwnerTinyID:n,GroupOwnerUserID:o,GroupOwnerUserName:a,GroupType:u,GroupAddOption:l,GroupInviteOption:c}=e;return{avatar:e,groupID:t,introduction:s,memberCount:r,name:i,ownerTinyID:n,ownerID:o,ownerNick:a,type:u,joinOption:l,inviteOption:c}}))||[],cursor:a,totalCount:u},successLog:{message:l}}}catch(e){var{errorCode:t,errorInfo:s}=e||{};this._handleError({errorCode:t,errorInfo:s,searchType:Eu,functionName:"searchCloudGroups"})}})}_setTimeRangeParams(e,{timePeriod:t,timePosition:s}){t&&0<t&&(e.startTime=s&&0<s?s-t:this._core.helper.timeManager.getServerTimeSeconds()-t),e.startTime&&e.startTime<0&&(e.startTime=void 0),s&&0<s&&(e.endTime=s)}_handleError({errorCode:e,errorMessage:t,searchType:s}){var r=this._core["helper"];let i=e;throw 60020===e?i="SearchUnable":s!==Iu&&27003===e?i="SearchParamsError":s!==Iu&&60018===e&&(i="SearchOverLimit"),new r.ChatError({code:i,message:t})}_isSearchingAllConversations(e){return this._core.helper.isEmpty(e.conversationID)}_setBirthdayRangeParams(e,t){var{miniBirthday:t,maxBirthday:s}=t;void 0!==t&&(e.miniBirthday=t,void 0===s)&&(e.maxBirthday=4294967295),void 0!==s&&(e.maxBirthday=s)}};var Pu=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 wu=new class{init(e){this.core=e}},Uu="NOT_STARTED";function ku(e){var{helper:t,constants:s}=wu.core;if(!t.checkBusinessCapabilityBits("CONV_GROUP"))throw new t.ChatError({functionName:e,code:s.ERROR_CODE.NO_USE,replacement1:e})}function Fu(){var{notificationCenter:e,OuterEvent:t}=wu.core;e.emitOuterEvent(t.CONVERSATION_GROUP_LIST_UPDATED,{name:t.CONVERSATION_GROUP_LIST_UPDATED,data:[...Pu.getConversationGroupMap().values()]})}function qu(e){var{utils:{isUndefined:t},constants:{OuterConstant:s}}=wu.core,{Type:e,To_Account:r,GroupId:i,ToGroupId:i=i,Peer_Account:n}=e;let o="";return 1===e?t(n)?t(r)||(o=""+s.CONV_C2C+r):o=""+s.CONV_C2C+n:2===e&&(o=""+s.CONV_GROUP+i),o}function xu(e){let t=[],{OuterConstant:s,common:{isC2CConv:r,isGroupConv:i}}=wu.core,{conversationIDList:n,failureConversationIDList:o,additionalData:a={}}=e;return n.forEach(e=>{Vu(e,o),r(e)?t.push(Object.assign({ContactItem:{Type:1,To_Account:e.replace(s.CONV_C2C,"")}},a)):i(e)&&t.push(Object.assign({ContactItem:{Type:2,ToGroupId:e.replace(s.CONV_GROUP,"")}},a))}),t}function Vu(e,t){var{appStore:{conversationStore:s},common:{isC2CConv:r,isGroupConv:i}}=wu.core;s.getConversation(e)?r(e)||i(e)||t.push({conversationID:e,code:2503}):t.push({conversationID:e,code:2500})}function Bu(t){var{isString:e}=wu.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 ju(i){null!=i&&i.forEach((e,t)=>{var s=wu.core["appStore"],{conversationID:e,data:r}=e,t=t===i.length-1;s.conversationStore.updateConversation(e,r,{emit:t})})}function Ku(e){var{conversationInfoList:e,fromAccount:t}=e,t={From_Account:t,MarkItem:e};return wu.core.common.buildAndSendPacket({servcmd:"recentcontact.mark_contact",data:t})}function Wu(e){var{fromAccount:e,groupName:t,conversationInfoList:s}=e,e={From_Account:e,UpdateType:1,UpdateGroup:{UpdateGroupType:2,OldGroupName:t,ContactUpdateItem:s}};return wu.core.common.buildAndSendPacket({servcmd:"recentcontact.update_contact_group",data:e})}var Hu=new class{init(e){var{registerApi:t}=e["helper"];this._core=e,t({apiName:"createConversationGroup",context:this})}createConversationGroup(s){return I(this,void 0,void 0,function*(){let{utils:{isPlainObject:n,isArray:o},appStore:a}=this._core,{groupName:u,conversationIDList:e}=(ku("createConversationGroup"),s),l=[],t=this._generateConversationInfo(e,l);if(l.length===e.length)return{code:0,data:{successConversationIDList:[],failureConversationIDList:l}};try{let i=yield function(e){var{buildAndSendPacket:t,getCurrentUserID:s}=wu.core["common"],{item:e,groupName:r}=e;return t({servcmd:"recentcontact.create_contact_group",data:{From_Account:s(),GroupContactItem:[{GroupName:r,ContactItem:e}]}})}({groupName:u,item:t});if(i){let{GroupResultItem:e=[]}=i,{GroupItem:s,ResultItem:t}=(null==e?void 0:e[0])||{},r=[];if(n(s)){let{GroupName:e,GroupId:t}=s;Pu.setConversationGroup(t,e),Fu()}if(o(t)){let n=[];t.forEach(e=>{let{ContactItem:t,ResultCode:s,ResultInfo:r}=e,i=qu(t);if(0===s){let t=a.conversationStore.getConversation(i);if(t&&!t.conversationGroupList.includes(u)){let e=t.conversationGroupList.slice();e.push(u),n.push({conversationID:i,data:{conversationGroupList:e}})}}else l.push({conversationID:i,code:s,message:r})}),0<n.length&&(ju(n),Fu())}return{code:0,data:{successConversationIDList:r,failureConversationIDList:l}}}}catch(e){let{errorCode:t,errorInfo:s}=e;throw new this._core.helper.ChatError({functionName:"createConversationGroup",code:t,message:s})}})}_generateConversationInfo(e,t,s={}){let r=[],{OuterConstant:i,common:{isC2CConv:n,isGroupConv:o}}=this._core;return e.forEach(e=>{Vu(e,t),n(e)?r.push(Object.assign({Type:1,To_Account:e.replace(i.CONV_C2C,"")},s)):o(e)&&r.push(Object.assign({Type:2,ToGroupId:e.replace(i.CONV_GROUP,"")},s))}),r}},Yu=new class{constructor(){this._fetchConversationGroupStatus=Uu}init(e){var{helper:{registerApi:t,registerWorkflowStep:s},constants:{WORKFLOW_NAME:r,WORKFLOW_STEP:i}}=e;this._core=e,t({apiName:"getConversationGroupList",context:this}),s(r.SYNC_SERVER_INFO_AFTER_LOGIN,i.CONVERSATION_GROUP_LIST_SYNC,this._syncConversationGroupList,this),s(r.SYNC_SERVER_INFO_AFTER_LOGIN,i.CONVERSATION_GROUP_UPDATE,this._updateConversation,this)}getConversationGroupList(){return I(this,void 0,void 0,function*(){return ku("getConversationGroupList"),"FAILED"===this._fetchConversationGroupStatus&&(yield this._fetchConversationGroupList(0)),{code:0,data:[...Pu.getConversationGroupMap().values()]}})}_syncConversationGroupList(){return I(this,void 0,void 0,function*(){return yield this._fetchConversationGroupList(0)})}_fetchConversationGroupList(e){return I(this,arguments,void 0,function*(r,n=[]){let{common:{getCurrentUserID:e},utils:{isArray:o}}=this._core;this._fetchConversationGroupStatus="FETCHING";try{let s=e(),i=yield function(){var{fromAccount:e,startIndex:t}={fromAccount:s,startIndex:r},e={From_Account:e,StartIndex:t};return wu.core.common.buildAndSendPacket({servcmd:"recentcontact.get_contact_group",data:e})}();if(i){let{CompleteFlag:e,ContactItem:t=[],NextStartIndex:s=0,GroupItem:r=[]}=i;return(o(r)&&r.forEach(e=>{var{GroupName:e,GroupId:t}=e;Pu.setConversationGroup(t,e)}),n.push(...t),0===e)?this._fetchConversationGroupList(s):1===e?(this._fetchConversationGroupStatus="FINISHED",n):void 0}}catch(r){this._fetchConversationGroupStatus="FAILED",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])||[];ju(this._generateConversationUpdateFields(e)),Fu()}_generateConversationUpdateFields(e){let{utils:{isArray:o},appStore:a}=this._core,u=[];if(o(e)){let n;e.forEach(e=>{let t=[],{StandardMark:s,CustomMark:r="",ContactGroupId:i}=e;o(i)&&i.forEach(e=>{Pu.getConversationGroupMap().has(e)&&t.push(Pu.getConversationGroup(e))});e=qu(e);(n=a.conversationStore.getConversation(e))&&u.push({conversationID:e,data:{markList:Bu(s),customData:r,conversationGroupList:[...t]}})})}return u}reset(){this._fetchConversationGroupStatus=Uu}dispose(){this.reset()}},$u=new class{init(e){var{notificationCenter:t,helper:{registerApi:s},InnerEvent:{MESSAGE_PUSH:r},InnerEventSubType:{CONVERSATION_MARK_UPDATED:i,CONVERSATION_GROUP_ADD:n,CONVERSATION_GROUP_DELETED:o,CONVERSATION_GROUP_UPDATED:a}}=e;this._core=e,s({apiName:"renameConversationGroup",context:this}),s({apiName:"deleteConversationGroup",context:this}),s({apiName:"markConversation",context:this}),s({apiName:"setConversationCustomData",context:this}),s({apiName:"deleteConversationsFromGroup",context:this}),s({apiName:"addConversationsToGroup",context:this}),t.subscribeInnerEvent(r,n,this._handleConversationGroupAdd,this),t.subscribeInnerEvent(r,o,this._handleConversationGroupDeleted,this),t.subscribeInnerEvent(r,a,this._handleConversationGroupUpdated,this),t.subscribeInnerEvent(r,i,this._handleConversationMarkUpdated,this)}renameConversationGroup(e){return I(this,void 0,void 0,function*(){ku("renameConversationGroup");let{getCurrentUserID:r}=this._core["common"],{oldName:i,newName:n}=e,o=`oldName:${i} newName:`+n;try{let s=yield function(){var{fromAccount:e,oldName:t,newName:s}={fromAccount:r(),oldName:i,newName:n},e={From_Account:e,UpdateType:1,UpdateGroup:{UpdateGroupType:1,OldGroupName:t,NewGroupName:s}};return wu.core.common.buildAndSendPacket({servcmd:"recentcontact.update_contact_group",data:e})}();if(s){let e=s["UpdateGroupResult"],t=e["GroupId"];Pu.setConversationGroup(t,n),Fu(),this._updateLocalConversationGroupName({oldName:i,newName:n})}return{successLog:{message:o}}}catch(e){let{errorCode:t,errorInfo:s}=e;throw new this._core.helper.ChatError({functionName:"renameConversationGroup",code:t,message:s,moreMessage:o})}})}deleteConversationGroup(r){return I(this,void 0,void 0,function*(){ku("deleteConversationGroup");let s=this._core["common"]["getCurrentUserID"];try{var t=yield function(){var{fromAccount:e,groupName:t}={fromAccount:s(),groupName:r},e={From_Account:e,GroupName:[t]};return wu.core.common.buildAndSendPacket({servcmd:"recentcontact.del_contact_group",data:e})}();if(t){let e=t["GroupItem"],s=!1;return null!=e&&e.forEach(e=>{var e=e["GroupId"],t=Pu.getConversationGroupMap();t.has(e)&&(t.delete(e),s=!0)}),s&&Fu(),this._deleteLocalConversationGroupName([r]),{successLog:{message:"groupName:"+r}}}}catch(s){var{errorCode:t,errorInfo:e}=s;throw new this._core.helper.ChatError({functionName:"deleteConversationGroup",code:t,message:e,moreMessage:"groupName:"+r})}})}markConversation(p){return I(this,void 0,void 0,function*(){ku("markConversation");let{utils:{isNumber:e},common:{getCurrentUserID:s},appStore:o}=this._core,{conversationIDList:t,markType:a,enableMark:u}=p,r=this._getFlagBit(a),l=[],c=[],i,n;!0===u&&e(r)?i=[r]:n=[r];var d=xu({conversationIDList:t,failureConversationIDList:l,additionalData:{SetMark:i,ClearMark:n,OptType:1}});if(l.length===t.length)return{code:0,data:{successConversationIDList:[],failureConversationIDList:l}};try{let t=yield Ku({conversationInfoList:d,fromAccount:s()});if(t){let e=t["ResultItem"],n=[];e.forEach(e=>{let{ContactItem:t,ResultCode:s,ResultInfo:r}=e,i=qu(t);if(0===s){c.push(i);let s=o.conversationStore.getConversation(i);if(s){let t=s.markList.indexOf(a),e=!1===u&&-1!==t;if(!0===u&&-1===t)n.push({conversationID:i,data:{markList:[...s.markList,a]}});else if(e){let e=s.markList.slice();e.splice(t,1),n.push({conversationID:i,data:{markList:e}})}}}else l.push({conversationID:i,code:s,message:r})}),ju(n)}return{code:0,data:{successConversationIDList:c,failureConversationIDList:l}}}catch(e){let{errorCode:t,errorInfo:s}=e;throw new this._core.helper.ChatError({functionName:"markConversation",code:t,message:s})}})}setConversationCustomData(r){return I(this,void 0,void 0,function*(){ku("setConversationCustomData");let{common:{getCurrentUserID:e},appStore:i}=this._core,{conversationIDList:t,customData:n}=r,o=[],a=[],s=xu({conversationIDList:t,failureConversationIDList:o,additionalData:{CustomMark:n,OptType:2}});if(o.length===t.length)return{code:0,data:{successConversationIDList:[],failureConversationIDList:o}};try{let t=yield Ku({fromAccount:e(),conversationInfoList:s});if(t){let e=t["ResultItem"],r=[];null!=e&&e.forEach(e=>{var{ContactItem:s,ResultCode:e,ResultInfo:t}=e;if(0===e){let e=qu(s),t=(a.push(e),i.conversationStore.getConversation(e));t&&t.customData!==n&&r.push({conversationID:e,data:{customData:n}})}else o.push({conversationID:conversationID,code:e,message:t})}),ju(r)}return{code:0,data:{successConversationIDList:a,failureConversationIDList:o}}}catch(e){let{errorCode:t,errorInfo:s}=e;throw new this._core.helper.ChatError({functionName:"setConversationCustomData",code:t,message:s})}})}deleteConversationsFromGroup(i){return I(this,void 0,void 0,function*(){ku("deleteConversationsFromGroup");let{common:{getCurrentUserID:e},appStore:n}=this._core,{conversationIDList:t,groupName:o}=i,s=[],a=[],r=xu({conversationIDList:t,failureConversationIDList:s,additionalData:{ContactOptType:2}});if(s.length===t.length)return{code:0,data:{successConversationIDList:[],failureConversationIDList:s}};try{let t=yield Wu({fromAccount:e(),groupName:o,conversationInfoList:r});if(t){let i=[],{ContactResultItem:e}=t["UpdateGroupResult"];null!=e&&e.forEach(e=>{var r=qu(e.ContactItem);if(0===e.ResultCode){let s=n.conversationStore.getConversation(r);if(s){let t=s.conversationGroupList.indexOf(o);if(-1!==t){let e=s.conversationGroupList.slice();e.splice(t,1),a.push(r),i.push({conversationID:r,data:{conversationGroupList:e}})}}}else s.push({conversationID:r,code:e.ResultCode,message:e.ResultInfo})}),0<i.length&&(Fu(),ju(i))}return{code:0,data:{successConversationIDList:a,failureConversationIDList:s}}}catch(e){let{errorCode:t,errorInfo:s}=e;throw new this._core.helper.ChatError({functionName:"deleteConversationsFromGroup",code:t,message:s})}})}addConversationsToGroup(r){return I(this,void 0,void 0,function*(){ku("deleteConversationsFromGroup");let{common:{getCurrentUserID:e},appStore:i}=this._core,{conversationIDList:t,groupName:n}=r,o=[],a=[],s=xu({conversationIDList:t,failureConversationIDList:o,additionalData:{ContactOptType:1}});if(o.length===t.length)return{code:0,data:{successConversationIDList:[],failureConversationIDList:o}};try{let t=yield Wu({fromAccount:e(),groupName:n,conversationInfoList:s});if(t){let r=[],{ContactResultItem:e}=t["UpdateGroupResult"];null!=e&&e.forEach(e=>{var s=qu(e.ContactItem);if(0===e.ResultCode){let t=i.conversationStore.getConversation(s);if(t&&-1===t.conversationGroupList.indexOf(n)){let e=t.conversationGroupList.slice();e.push(n),a.push(s),r.push({conversationID:s,data:{conversationGroupList:e}})}}else o.push({conversationID:s,code:e.ResultCode,message:e.ResultInfo})}),0<r.length&&(Fu(),ju(r))}return{code:0,data:{successConversationIDList:a,failureConversationIDList:o}}}catch(e){let{errorCode:t,errorInfo:s}=e;throw new this._core.helper.ChatError({functionName:"deleteConversationsFromGroup",code:t,message:s})}})}_updateLocalConversationGroupName(e){let t=this._core["appStore"],{oldName:s,newName:r}=e,i=[],n=[],o;Array.from(t.conversationStore.getConversationMap().values()).forEach(e=>{var t;i=e.conversationGroupList,-1!==(o=i.indexOf(s))&&((t=i.slice()).splice(o,1,r),n.push({conversationID:e.conversationID,data:{conversationGroupList:t}}))}),ju(n)}_deleteLocalConversationGroupName(i){var{utils:{isEmpty:e},appStore:t}=this._core;if(!e(i)){let r=[];Array.from(t.conversationStore.getConversationMap().values()).forEach(e=>{var{conversationID:e,conversationGroupList:t}=e,s=t.filter(e=>!i.includes(e));s.length<t.length&&r.push({conversationID:e,data:{conversationGroupList:s}})}),ju(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:u}=this._core;null!=(t=null==e?void 0:e.RecentContactMod)&&t.forEach(e=>{var e=e["RecentContactCreateContactGroup"]["MsgContactGroupContactItem"];let o=!1;null!=e&&e.forEach(e=>{let{MsgGroupItem:t,MsgRecentContactItem:s}=e,{GroupId:r,GroupName:i}=t,n=[];Pu.getConversationGroup(r)!==i&&(Pu.setConversationGroup(r,i),o=!0),a(s)&&s.forEach(e=>{var t=qu(e),s=u.conversationStore.getConversation(t);if(s&&(null==(e=s.conversationGroupList)||!e.includes(i))){let e=s.conversationGroupList.slice();e.push(i),n.push({conversationID:t,data:{conversationGroupList:e}})}}),o&&Fu(),ju(n)})})}_handleConversationGroupDeleted(e){let t,{isArray:s}=this._core.utils;null!=(t=null==e?void 0:e.RecentContactMod)&&t.forEach(e=>{e=((null==e?void 0:e.RecentContactDelContactGroup)||{}).MsgGroupItem;if(s(e)){let r=!1,i=[];e.forEach(e=>{var{GroupId:e,GroupName:t}=e,s=Pu.getConversationGroupMap();s.has(e)&&(s.delete(e),r=!0,i.push(t))}),r&&Fu(),0<i.length&&this._deleteLocalConversationGroupName(i)}})}_handleConversationGroupUpdated(e){null!=(e=e.RecentContactMod)&&e.forEach(e=>{var{GroupId:e,GroupName:t,OldGroupName:s,RecentContactUpdateGroupItem:r,UpdateGroupType:i}=e["RecentContactUpdateContactGroup"]["MsgUpdateGroup"];1===i?this._handleGroupNameUpdated({groupID:e,newName:t,oldName:s}):2===i&&this._handleGroupAddOrDeleteFromConversation({groupInfoList:r,groupName:s})})}_handleConversationMarkUpdated(e){let t,n=this._core.appStore;null!=(t=null==e?void 0:e.RecentContactMod)&&t.forEach(e=>{let{RecentContactMarkContactItem:t}=e["RecentContactMarkContact"],i=[];null!=t&&t.forEach(e=>{var{RecentContactItem:e,CustomMark:t,StandardMark:s,OptType:r}=e,e=qu(e),e=n.conversationStore.getConversation(e);e&&(1===r?this._updateStandMark({conversation:e,standardMark:s,updateConversationList:i}):2===r?this._updateCustomMark({conversation:e,customMark:t,updateConversationList:i}):3===r&&(this._updateStandMark({conversation:e,standardMark:s,updateConversationList:i}),this._updateCustomMark({conversation:e,customMark:t,updateConversationList:i})))}),ju(i)})}_updateStandMark(e){var{conversation:e,standardMark:t,updateConversationList:s}=e,t=Bu(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;Pu.getConversationGroup(e)!==s&&(Pu.setConversationGroup(e,s),Fu(),this._updateLocalConversationGroupName({oldName:t,newName:s}))}_handleGroupAddOrDeleteFromConversation({groupInfoList:e,groupName:n}){let o=this._core["appStore"],a=[];e.forEach(e=>{var{RecentContactItem:e,ContactOptType:t}=e,s=qu(e),r=o.conversationStore.getConversation(s),i=r.conversationGroupList.indexOf(n);if(r){let e=r.conversationGroupList.slice();1===t&&-1===i?(e.push(n),a.push({conversationID:s,data:{conversationGroupList:e}})):2===t&&-1!==i&&(e.splice(i,1),a.push({conversationID:s,data:{conversationGroupList:e}}))}}),ju(a)}dispose(){var{notificationCenter:e,InnerEvent:{MESSAGE_PUSH:t},InnerEventSubType:{CONVERSATION_MARK_UPDATED:s,CONVERSATION_GROUP_ADD:r,CONVERSATION_GROUP_DELETED:i,CONVERSATION_GROUP_UPDATED:n}}=this._core;e.unSubscribeInnerEvent(t,r,this._handleConversationGroupAdd,this),e.unSubscribeInnerEvent(t,i,this._handleConversationGroupDeleted,this),e.unSubscribeInnerEvent(t,n,this._handleConversationGroupUpdated,this),e.unSubscribeInnerEvent(t,s,this._handleConversationMarkUpdated,this)}};let zu={required:!0,rules:["string"],allowEmpty:!1},Ju={required:!0,rules:["array"],allowEmpty:!1},Qu={createConversationGroup:{groupName:zu,conversationIDList:{required:!0,rules:["array"],allowEmpty:!1}},renameConversationGroup:{oldName:zu,newName:Object.assign(Object.assign({},zu),{customValidator:e=>!(32<e.length)||"newName length cannot longer than 32"})},deleteConversationGroup:[{required:!0,rules:["string"],allowEmpty:!1}],addConversationsToGroup:{conversationIDList:Ju,groupName:zu},deleteConversationsFromGroup:{conversationIDList:Ju,groupName:zu},markConversation:{conversationIDList:Ju,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:Ju,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"}}},Xu={createConversationGroup:!0,deleteConversationGroup:!0,renameConversationGroup:!0,getConversationGroupList:!0,addConversationsToGroup:!0,deleteConversationsFromGroup:!0,markConversation:!0,setConversationCustomData:!0},Zu=new class{constructor(){this.name="ConversationGroup"}install(e){this._core=e,wu.init(e),Pu.init(e),Hu.init(e),Yu.init(e),$u.init(e),e.helper.registerValidateConfig({auth:Xu,params:Qu}),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),$u.dispose(),Yu.dispose()}reset(){Yu.reset()}},el=new class{init(e){this.core=e}},tl=["topicID","topicName","avatar","introduction","notification","unreadCount","muteAllMembers","customData","nextMessageSeq","selfInfo","lastMessage"],sl=e=>{var{common:{getMessagePreviewText:t}}=el["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 rl{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=sl(),this.selfInfo={muteTime:0,readedSequence:0,messageRemindType:"",excludedUnreadSequenceList:void 0},this._init(e)}_init(e){for(var t in e)tl.includes(t)&&("lastMessage"===t?this[t]=sl(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=sl(e)}updateGroupAtInfoList(e){var{common:{updateGroupAtInfo:t}}=el["core"];t(e,this.groupAtInfoList)}updateTopic(e){var{utils:{isUndefined:t},common:{deepMerge:s}}=el["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}}=el["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 L=new class{constructor(){this._name="TopicDataHandler",this._topicMap=new Map,this._topicRequestInfo=new Map}init(e){var{helper:t,constants:s,notificationCenter:r,InnerEvent:{LOGOUT:i,DESTROY:n}}=this._core=e;t.registerWorkflowStep(s.WORKFLOW_NAME.SYNC_SERVER_INFO_AFTER_RE_ONLINE,s.WORKFLOW_STEP.TOPIC_REQUEST_INFO_RESET,this._resetTopicRequestInfo,this),r.subscribeInnerEvent(i,this._reset,this),r.subscribeInnerEvent(n,this._dispose,this),e.ssoLog.debug(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 rl(e),this._setTopic(t,s,r));e=this.computeUnreadCount(r);null!=r&&r.updateUnreadCount(e)})}_getLastMessage(s){var{isEmpty:r,isUndefined:i,isArray:n}=this._core["utils"];if(!i(s.lastMsg)){let e=null,t="";t=(n(s.lastMsg.elements)?(e=s.lastMsg.elements[0].content,s.lastMsg.elements[0]):(e=s.lastMsg.elements.content,s.lastMsg.elements)).type;i={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=i}}computeUnreadCount(s){let{excludedUnreadSequenceList:e=[],readedSequence:r}=s.selfInfo,i=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&&(i-=t)}return 0<i?i: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:i,isEmpty:t}}=this._core,n=e(),o=null;s.forEach(e=>{var{groupID:t,topicID:s,from:r}=e;r!==n&&((o=this.getTopic(t,s))&&o.updateGroupAtInfoList(e),i(o))&&a&&(this.updateTopic([{groupID:t,topicID:s}]),null!=(r=this.getTopic(t,s)))&&r.updateGroupAtInfoList(e)}),t(o)||this.emitTopicUpdate(o)}}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,i=(null==t?void 0:t.getLocalMessageList(""+r+e))||[];if(0!==i.length){e=i["length"];for(let t=e-1;0<=t;t--){let e=i[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 i=!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),i=!0),i)&&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 il=(e="")=>{var{OuterConstant:t}=el["core"];return e.replace(t.CONV_GROUP,"")},nl=(e="")=>e.split("@TOPIC#_")[0];var ol,al=new class{constructor(){this._name="TopicMessageHandler"}init(e){var{helper:t,notificationCenter:s,constants:{WORKFLOW_NAME:r,WORKFLOW_STEP:i},InnerEvent:{MESSAGE_PUSH:n,TOPIC_NEW_MESSAGE:o,TOPIC_MESSAGE_DELETED:a,TOPIC_MESSAGE_REVOKED:u,TOPIC_MESSAGE_MODIFIED:l,DESTROY:c}}=this._core=e,{TOPIC_AT_TIPS:d,TOPIC_LATEST_MESSAGE:p}=s["InnerEventSubType"];t.registerWorkflowStep(r.SYNC_SERVER_INFO_AFTER_LOGIN,i.UPDATE_TOPIC_AFTER_UNREAD_SYNC_FINISHED,this._handleUnreadSyncFinished,this),t.registerWorkflowStep(r.RECEIVE_GROUP_NEW_MESSAGE,i.UPDATE_TOPIC_BY_RECEIVE_NEW_MESSAGE,this._handleNewMessage,this),s.subscribeInnerEvent(o,this._handleNewMessage,this),s.subscribeInnerEvent(a,this._handleMessageDeleted,this),s.subscribeInnerEvent(u,this._handleMessageRevoked,this),s.subscribeInnerEvent(l,this._handleMessageModified,this),s.subscribeInnerEvent(n,d,this._handleTopicAtTips,this),s.subscribeInnerEvent(n,p,this._handleLatestMessage,this),s.subscribeInnerEvent(c,this._dispose,this),e.ssoLog.debug(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 o=this._core["common"]["getCurrentUserID"];e.forEach(e=>{let{conversationID:t="",lastMessage:i}=e,s=il(t),r=nl(s),n=L.getTopic(r,s);if(n){let{from:e,sequence:t}=i,s=t+1,r=e===o();if(s>n.nextMessageSeq){n.updateNextMessageSeq(s),n.updateLastMessage(i),n.updateReadSequence(t,r);let e=r?0:L.computeUnreadCount(n);n.updateUnreadCount(e),this._emitTopicUpdate(n)}}})}}}_handleMessageDeleted(s){var r=il(s),i=nl(r),i=L.getTopic(i,r);if(console.log(this._name+`._handleMessageDeleted, topicID:${r} hasTopic:`+!!i),i){var{message:{messageDataHandler:n},utils:{isEmpty:o}}=this._core,a=(null==n?void 0:n.getLocalMessageList(s))||[];let t={};for(let e=(a.length||0)-1;0<=e;e--)if(!a[e].isDeleted){t=a[e];break}let e=!1;i.lastMessage.lastSequence!==t.sequence&&(o(t)&&(t={}),i.updateLastMessage(t),e=!0),e&&(this._emitTopicUpdate(i),console.log(this._name+`._handleMessageDeleted, topicID:${r} with lastMessage:`+i.lastMessage))}}_handleMessageRevoked(e){var{messageList:e=[]}=e;if(console.log(this._name+"._handleMessageRevoked messageList:"+e.length),0!==e.length){let i=null,n=!1;e.forEach(e=>{var{to:e,sequence:t,revoker:s}=e,r=nl(e);if(i=L.getTopic(r,e)){i.reduceUnreadCount()&&(n=!0),i.isLastMessageRevoked(t)&&(i.setLastMessageRevoked(!0),i.setLastMessageRevoker(s),n=!0);let{excludedUnreadSequenceList:e=[]}=i.selfInfo;e.push(t),i.updateSelfInfo({excludedUnreadSequenceList:e})}}),n&&this._emitTopicUpdate(i)}}_handleMessageModified(e){let{conversationID:t,messageList:s}=e,r=il(t),i=nl(r),a=L.getTopic(i,r);if(console.log(`${this._name}._handleMessageModified topicID:${r} hasTopic:`+!!a),a){var u=a["lastMessage"];if(u){let o=(null==s?void 0:s[0])||{};if(this._shouldUpdateLastMessage(u,o)){let{getMessagePreviewText:e}=this._core["common"],{time:t,sequence:s,elements:r,cloudCustomData:i,messageVersion:n}=o;u.type=r[0].type,u.payload=r[0].content,u.messageForShow=e(u.type,u.payload),u.cloudCustomData=i,u.version=n,u.lastSequence=s,u.lastTime=t,this._emitTopicUpdate(a)}}}}_shouldUpdateLastMessage(e,t){var s;return null===e.payload||({sequence:t,messageVersion:s}=t,e.lastSequence===t&&e.version!==s)}_emitTopicUpdate(e){var{notificationCenter:t,OuterEvent:s}=this._core;t.emitOuterEvent(s.TOPIC_UPDATED,{name:s.TOPIC_UPDATED,data:e})}_handleTopicAtTips(e){let{GroupTips:t=[]}=e,n=[],o=!1;t.forEach(e=>{var{GroupAtTips:e,MsgBody:t,MsgRandom:s,ClientSeq:r}=e;let i={};e?i=this._convertAtInfo(e):t&&(i=this._convertAtInfo(t),o=!0),i.__random=s,i.__sequence=r,n.push(i)}),L.updateGroupAtInfoList(n,o)}_convertAtInfo(e){var{From_Account:e,GroupId:t,TopicId:s,MsgSeq:r,GroupAtType:i}=e;return{groupID:t,topicID:s,from:e,sequence:r,groupAtType:i}}_handleLatestMessage(e){let{utils:{isEmpty:t},message:{messageHelper:r,messageFactory:i}}=this._core,{NewMsg:n,NoUnreadSeqList:o}=e||{};if(!t(n)){let{TopicId:e}=n["GroupInfo"],t=r.parseServerGroupMessage(n),s=i.createMessage(t);s.setElement(t.elements),this._updateUnreadCountAndLastMessage({topicID:e,message:s,excludedUnreadSequenceList:o})}}_updateUnreadCountAndLastMessage(e){let{isUndefined:t}=this._core["utils"],{topicID:s,message:r,excludedUnreadSequenceList:i}=e,n=nl(s),o=L.getTopic(n,s);if(o){let e=o.selfInfo.excludedUnreadSequenceList||[];if(t(i)||(e=i),r._isExcludedFromUnreadCount&&e.push(r.sequence),o.updateSelfInfo({excludedUnreadSequenceList:e}),console.log(`${this._name}._updateUnreadCountAndLastMessage latest message sequence:${r.sequence} lastMessage sequence:`+o.lastMessage.lastSequence),r.sequence>o.lastMessage.lastSequence){let e=r.sequence+1,t=(o.updateLastMessage(r),o.updateNextMessageSeq(e),L.computeUnreadCount(o));o.updateUnreadCount(t),this._emitTopicUpdate(o)}}}_dispose(){var{notificationCenter:e,InnerEvent:{MESSAGE_PUSH:t,TOPIC_NEW_MESSAGE:s,TOPIC_MESSAGE_DELETED:r,TOPIC_MESSAGE_REVOKED:i,TOPIC_MESSAGE_MODIFIED:n,DESTROY:o}}=this._core,{TOPIC_AT_TIPS:a,TOPIC_LATEST_MESSAGE:u}=e["InnerEventSubType"];e.unSubscribeInnerEvent(s,this._handleNewMessage,this),e.unSubscribeInnerEvent(r,this._handleMessageDeleted,this),e.unSubscribeInnerEvent(i,this._handleMessageRevoked,this),e.unSubscribeInnerEvent(n,this._handleMessageModified,this),e.unSubscribeInnerEvent(t,a,this._handleTopicAtTips,this),e.unSubscribeInnerEvent(t,u,this._handleLatestMessage,this),e.unSubscribeInnerEvent(o,this._dispose,this)}},ul=new class{constructor(){this._name="TopicOperationHandler"}init(e){var{notificationCenter:t,InnerEvent:{MESSAGE_PUSH:s,DESTROY:r}}=this._core=e,{TOPIC_TIPS_NOTIFICATION:i,TOPIC_SYSTEM_NOTIFICATION:n,TOPIC_MESSAGE_READ_SYNC:o}=t["InnerEventSubType"];t.subscribeInnerEvent(s,i,this._handleTopicTips,this),t.subscribeInnerEvent(s,n,this._handleTopicNotices,this),t.subscribeInnerEvent(s,o,this._handleTopicMessageReadSynced,this),t.subscribeInnerEvent(r,this._dispose,this),e.ssoLog.debug(this._name+".init")}_handleTopicTips(e){var{GroupTips:t=[]}=e;for(let e=0;e<t.length;e++){var s=t[e];7!==s.MsgBody.OpType?8!==s.MsgBody.OpType?this._emitTopicTips(s):this._handleTopicProfileUpdated(s):this._handleMuteTimeUpdated(s)}}_handleMuteTimeUpdated(e){var{getCurrentUserID:t}=this._core["common"],{GroupInfo:{GroupId:s,TopicId:r},MsgBody:{MsgMemberInfo:i=[]}}=e;for(let e=0;e<i.length;e++){var{User_Account:n,ShutupTime:o}=i[e];if(n===t()&&0<=o){L.updateSelfInfo({groupID:s,topicID:r,selfInfo:{muteTime:o}});break}}}_handleTopicProfileUpdated(e){var{GroupInfo:{GroupId:e,TopicId:t},MsgBody:{MsgTopicNewInfo:{CustomString:s,ShutupAll:r,TopicFaceUrl:i,TopicIntroduction:n,TopicName:o,TopicNotification:a}}}=e,u=L.getTopic(e,t);u&&(u.updateTopic({groupID:e,topicID:t,customData:s,muteAllMembers:r,avatar:i,introduction:n,topicName:o,notification:a}),L.emitTopicUpdate(u))}_handleTopicNotices(e){var{GroupTips:t=[]}=e;for(let e=0;e<t.length;e++){var s=t[e],{MsgBody:{ReportType:r,TopicIdArray:i,MsgFlag:n},GroupInfo:{GroupId:o,TopicId:a}}=s;17===r?this._handleTopicCreated({groupID:o,topicID:a}):18===r?this._handleTopicDeleted({groupID:o,topicIDList:i}):20===r?this._handleMessageRemindTypeUpdated({groupID:o,topicID:a,messageRemindType:n}):this._emitTopicNotices(s)}}_handleTopicCreated(e){var{OuterEvent:t,notificationCenter:s}=this._core;L.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:i=[]}=e;L.deleteTopicList(r,i),s.emitOuterEvent(t.TOPIC_DELETED,{name:t.TOPIC_DELETED,data:e})}_handleMessageRemindTypeUpdated(e){var{groupID:e,topicID:t,messageRemindType:s}=e;L.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),L.updateSelfInfo({groupID:e,topicID:t,selfInfo:{readedSequence:s}}),L.clearGroupAtInfoList(e,t),L.markMessageAsRead(t,s),L.updateUnreadCount(e,t)})})}_emitTopicTips(e){var{message:{messageHelper:t,messageFactory:s},OuterConstant:r,OuterEvent:i,notificationCenter:n}=this._core,t=(e.MsgBody.MsgType=r.MSG_GRP_TIP,t.parseServerGroupMessage(e)),e=(t.flow="in",t.conversationType=r.CONV_GROUP,s.createMessage(t));e.setElement(t.elements),e.isSystemMessage=!0,n.emitOuterEvent(i.MESSAGE_RECEIVED,{name:i.MESSAGE_RECEIVED,data:[e]})}_emitTopicNotices(e){var{message:{messageHelper:t,messageFactory:s},OuterConstant:r,OuterEvent:i,notificationCenter:n}=this._core,t=(e.MsgBody.MsgType=r.MSG_GRP_SYS_NOTICE,t.parseServerGroupMessage(e)),e=(t.flow="in",t.conversationType=r.CONV_SYSTEM,t.conversationID=r.CONV_SYSTEM,s.createMessage(t));e.setElement(t.elements),e.isSystemMessage=!0,n.emitOuterEvent(i.MESSAGE_RECEIVED,{name:i.MESSAGE_RECEIVED,data:[e]})}_dispose(){var{notificationCenter:e,InnerEvent:{MESSAGE_PUSH:t,DESTROY:s}}=this._core,{TOPIC_TIPS_NOTIFICATION:r,TOPIC_SYSTEM_NOTIFICATION:i,TOPIC_MESSAGE_READ_SYNC:n}=e["InnerEventSubType"];e.unSubscribeInnerEvent(t,r,this._handleTopicTips,this),e.unSubscribeInnerEvent(t,i,this._handleTopicNotices,this),e.unSubscribeInnerEvent(t,n,this._handleTopicMessageReadSynced,this),e.unSubscribeInnerEvent(s,this._dispose,this)}},ll=new class{constructor(){this._name="GetJoinedCommunityHandler"}init(e){e=(this._core=e).helper;e.registerApi({apiName:"getJoinedCommunityList",context:this})}getJoinedCommunityList(){return I(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}}})}},cl=new class{constructor(){this._name="CreateTopicHandler"}init(e){e=(this._core=e).helper;e.registerApi({apiName:"createTopicInCommunity",context:this})}createTopicInCommunity(n){return I(this,void 0,void 0,function*(){let s="createTopicInCommunity",{utils:{isUndefined:e},common:{isTopic:t},helper:{ChatError:r}}=this._core,i=n["topicID"];if(!e(i)&&!t(i)){let e=new r({functionName:s,code:3021});throw console.error(this._name+`.${s} fail:`,e),e}try{let e=yield function(a,u){return I(this,void 0,void 0,function*(){var{groupID:e,topicID:t,topicName:s,avatar:r,notification:i,introduction:n,customData:o}=a;return u.common.buildAndSendPacket({servcmd:"million_group_open_http_svc.create_topic",data:{GroupId:e,TopicId:t,TopicName:s,FaceUrl:r,Notification:i,Introduction:n,CustomString:o}})})}(n,this._core),{TopicId:t=""}=e||{};return console.log(this._name+`.${s} ok, topicID:`+t),L.updateTopic([Object.assign(Object.assign({},n),{topicID:t})]),{code:0,data:{topicID:t}}}catch(e){throw console.error(this._name+`.${s} failed, error:`,e),e}})}},dl=new class{constructor(){this._name="DeleteTopicHandler"}init(e){e=(this._core=e).helper;e.registerApi({apiName:"deleteTopicFromCommunity",context:this})}deleteTopicFromCommunity(u){return I(this,void 0,void 0,function*(){var s="deleteTopicFromCommunity",{groupID:o,topicIDList:a=[]}=u;try{let e=yield function(s,r){return I(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:o,topicIDList:a},this._core),{DestroyResultItem:t=[]}=e||{},r=[],i=[],n=[];return t.forEach(e=>{var{TopicId:e,ErrorCode:t,ErrorInfo:s}=e;0===t?(r.push({topicID:e}),n.push(e)):i.push({topicID:e,code:t,message:s})}),0<n.length&&L.deleteTopicList(u.groupID,n),console.log(`${this._name}.${s} ok, groupID:${o} success:${r.length} fail:`+i.length),{code:0,data:{successTopicList:r,failureTopicList:i}}}catch(e){throw console.error(this._name+`.${s} failed, error:`,e),e}})}},pl=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 I(this,void 0,void 0,function*(){var{groupID:t,topicIDList:s=[]}=e,r=0===s.length;if(this._isFetchingFromCache(t,r)){let e=L.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}=L.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)&&0<=(t=parseInt(t,10))&&t<=3600?1e3*t:3e5}_getTopicListFromServer(l,c){return I(this,void 0,void 0,function*(){var r="_getTopicListFromServer",{isEmpty:i}=this._core["utils"],u=l["groupID"];try{let e=yield function(s,r){return I(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"]}})})}(l,this._core),{TopicAndSelfInfo:t=[]}=e||{},n=[],o=[],a=[],s=(this._convertTopicInfoList(t).forEach(e=>{var{topic:e,selfInfo:t,code:s,message:r}=e,i=e["topicID"];0===s?(n.push(Object.assign(Object.assign({},e),{selfInfo:t})),o.push(i)):a.push({topicID:i,code:s,message:r})}),L.updateTopic(n),L.updateTopicAtInfo(n),console.log(`${this._name}.${r} groupID:${u} from remote, success count:${o.length}, fail count:`+a.length),[]);return i(o)||(L.setTopicRequestInfo(u,{hasFetchedAllTopics:c,time:Date.now()}),s=L.getTopicList(u,o)),{code:0,data:{successTopicList:s,failureTopicList:a}}}catch(e){throw console.error(this._name+`.${r} failed, error:`,e),e}})}_convertTopicInfoList(e){let i=[];return e.forEach(e=>{var{TopicInfo:e={},SelfInfo:t={},ErrorCode:s,ErrorInfo:r}=e;i.push({code:s,message:r,topic:this._convertTopicInfo(e),selfInfo:this._convertSelfInfo(t)})}),i}_convertTopicInfo(e){var t,s,r,i,n,o,a,u,l,c,d,p=this._core["utils"]["isEmpty"];return p(e)?{}:({CreateTime:p,CustomString:e,FaceUrl:t,GroupId:s,LastMsgTime:r,NextMsgSeq:i,Introduction:n,Notification:o,ShutUpAllFlag:a,TopicId:u,TopicName:l,LastMsg:c,AtInfoList:d}=e,{createTime:p,customData:e,avatar:t,groupID:s,lastMessageTime:r,nextMessageSeq:i,introduction:n,notification:o,muteAllMembers:a,topicID:u,topicName:l,lastMsg:this._convertLastMsg(c),groupAtInfoList:this._convertAtInfoList({groupID:s,topicID:u,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:i,atInfoList:t=[]}=e;if(0===t.length)return[];let n=[];return t.forEach(e=>{var{AtFlagList:e,AtMsgSeq:t,From_Account:s}=e;n.push({groupID:r,topicID:i,groupAtType:e,sequence:t,from:s})}),n}_convertSelfInfo(e){var t,s,r,i=this._core["utils"]["isEmpty"];return i(e)?{}:({InheritGroupReceiveOption:i,MsgFlag:e,MsgSeq:t,NoUnreadSeqList:s,ShutUpTime:r}=e,{inheritGroupReceiveOption:i,messageRemindType:e,readedSequence:t,excludedUnreadSequenceList:s,muteTime:r})}},hl=new class{constructor(){this._name="UpdateTopicHandler"}init(e){e=(this._core=e).helper;e.registerApi({apiName:"updateTopicProfile",context:this})}updateTopicProfile(n){return I(this,void 0,void 0,function*(){var t="updateTopicProfile",{isUndefined:e}=this._core["utils"],{groupID:s,topicID:r,muteAllMembers:i}=n;e(n.muteAllMembers)||(n.muteAllMembers=!0===i?"On":"Off");try{return yield function(u,l){return I(this,void 0,void 0,function*(){var{groupID:e,topicID:t,topicName:s,avatar:r,notification:i,introduction:n,customData:o,muteAllMembers:a}=u;return l.common.buildAndSendPacket({servcmd:"million_group_open_http_svc.modify_topic",data:{GroupId:e,TopicId:t,TopicName:s,FaceUrl:r,Notification:i,Introduction:n,CustomString:o,ShutUpAllMember:a}})})}(n,this._core),console.log(this._name+`.${t} ok, topicID:`+r),L.updateTopic([n]),{code:0,data:{topic:L.getTopic(s,r)}}}catch(e){throw console.error(this._name+`.${t} failed, topicID:${r} error:`,e),e}})}},gl=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(c){return I(this,void 0,void 0,function*(){let{utils:{isEmpty:e},ssoLog:t,helper:{ChatError:r}}=this._core,s=c["conversationID"],i={code:0,data:{}},n=il(s),o=nl(n),a=L.getTopic(o,n),u=this._name+`.setMessageRead topicID:${n} conversationID:${s} unreadCount:`+((null==a?void 0:a.unreadCount)||0);if(i.successLog={message:u},!a)return i;if(e(a.groupAtInfoList)||this._deleteTopicAtTips(o,n),0===a.unreadCount)return i;var l=this._getLocalMessageMaxSequence(a);try{yield this._setTopicMessageRead(o,n,l)}catch(e){let{errorCode:t,errorInfo:s}=e;throw new r({functionName:"setMessageRead",code:t,message:s,moreMessage:u})}return Object.assign(Object.assign({},i),{successLog:{message:u+" lastMessageSequence:"+l}})})}_deleteTopicAtTips(n,o){return I(this,void 0,void 0,function*(){this._core.ssoLog.debug("_deleteTopicAtTips",this._name+`._deleteTopicAtTips groupID:${n} topicID:`+o);let e=L.getTopic(n,o);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 i=[...r];0===(i=r.filter(e=>!e.atTypeArray.includes(s))).length?L.clearGroupAtInfoList(n,o):(yield function(t,s){return I(this,void 0,void 0,function*(){var e=t["messageListToDelete"];return s.common.buildAndSendPacket({servcmd:"openim.deletemsg",data:{DelMsgList:e}})})}({messageListToDelete:i.map(e=>({From_Account:e.from,To_Account:t(),MsgSeq:e.__sequence,MsgRandom:e.__random,GroupId:e.groupID}))},this._core),this._core.ssoLog.debug(this._name+"._deleteTopicAtTips ok. count:"+r.length),L.clearGroupAtInfoList(n,o))}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 i=(null==(r=null==e?void 0:e.lastMessage)?void 0:r.lastSequence)||0;return s>i&&(console.log(`${this._name}._getLocalMessageMaxSequence update lastMessageSequence from ${i} to `+s),i=s),i}_setTopicMessageRead(e,t,s){return I(this,void 0,void 0,function*(){try{yield function(r,i){return I(this,void 0,void 0,function*(){var{groupID:e,topicID:t,lastMessageSequence:s}=r;return i.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),L.updateSelfInfo({groupID:e,topicID:t,selfInfo:{readedSequence:s}}),L.markMessageAsRead(t,s),L.updateUnreadCount(e,t)}catch(e){throw console.error(this._name+"._setTopicMessageRead fail:",e),e}})}},_l=new class{init(e){e.ssoLog.debug("TopicAction.init"),ll.init(e),cl.init(e),dl.init(e),pl.init(e),hl.init(e),gl.init(e)}};let ml={required:!0,rules:["string"],allowEmpty:!1},vl={createTopicInCommunity:{groupID:ml,topicName:ml},deleteTopicFromCommunity:{groupID:ml,topicIDList:{required:!1,rules:["array"],allowEmpty:!0}},getTopicList:{groupID:ml,topicIDList:{required:!1,rules:["array"],allowEmpty:!0}},updateTopicProfile:{groupID:ml,topicID:ml}},fl={getJoinedCommunityList:!0,createTopicInCommunity:!0,deleteTopicFromCommunity:!0,getTopicList:!0,updateTopicProfile:!0},Il=new class{constructor(){this.name="Topic"}install(e){el.init(e),L.init(e),al.init(e),ul.init(e),_l.init(e),e.helper.registerValidateConfig({auth:fl,params:vl})}};function El(e,t){return Math.round(Number(e)*Math.pow(10,t))/Math.pow(10,t)}let Cl="qualityStat",Sl="im-ssolog-quality-stat",Ml=(ol=ol||{},ol[ol.ONLINE=8]="ONLINE","networkRTT"),yl="messageE2EDelay",Tl="sendMessageC2C",Al="sendMessageGroup",Ol="sendMessageGroupAV",Dl="sendMessageRichMedia",Rl="cosUpload",Ll="messageReceivedGroup",Nl="messageReceivedGroupAVPush",bl="messageReceivedGroupAVPull",Gl={networkRTT:2,messageE2EDelay:3,sendMessageC2C:4,sendMessageGroup:5,sendMessageGroupAV:6,sendMessageRichMedia:7,messageReceivedGroup:8,messageReceivedGroupAVPush:9,messageReceivedGroupAVPull:10,cosUpload:11},Pl=[Tl,Al,Ol,Dl,Rl],wl=[Ll,Nl,bl],Ul=[Ml,yl,Tl,Al,Ol,Dl,Rl,Ll,Nl,bl],kl={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},Fl="quality_stat";var ql=new class{constructor(){this._messageStatsMap=new Map,this._userSideErrorCodes=new Set(Object.values(kl))}init(e){this._core=e,Object.values(Pl).forEach(e=>{this._messageStatsMap.set(e,{totalCount:0,successCount:0,failedCountOfUserSide:0,costSum:0,costCount:0,fileSizeSum:0})})}dispatchSendStats(e){var{name:e,message:t,error:s,startTs:r}=e,i=this._core.constants["SEND_MESSAGE_STAT"];switch(e){case i.TOTAL_COUNT:this._handleTotalCount(t);break;case i.SUCCESS_COUNT:this._handleSuccessCount(t);break;case i.FAILED_COUNT:this._handleFailedCount(t,s);break;case i.SEND_COST:this._handleSendCost(t,r)}}getStatResult(e){var t,s,r,i,n,o=this._messageStatsMap.get(e);return o&&0!==o.totalCount?({totalCount:t,successCount:s,failedCountOfUserSide:i}=o,r=El(s/t*100,2),n=El((i=s+i)/t*100,2),o=this._calcAverageValue(o,e),this._resetStat(e),{total_count:t,success_count_business:s,percent_business:r,success_count_platform:i,percent_platform:n,average_value:o}):null}_handleTotalCount(e){e=this._getSendMessageSpecifiedKey(e),e=e&&this._messageStatsMap.get(e);e&&e.totalCount++}_handleSuccessCount(e){e=this._getSendMessageSpecifiedKey(e),e=e&&this._messageStatsMap.get(e);e&&e.successCount++}_handleFailedCount(s,e){var t=null!=(t=null==e?void 0:e.code)?t:null==e?void 0:e.errorCode;if(this._isUserSideError(t)){let e=this._getSendMessageSpecifiedKey(s),t=e&&this._messageStatsMap.get(e);t&&t.failedCountOfUserSide++}}_handleSendCost(e,t){e=this._getSendMessageSpecifiedKey(e),e=e&&this._messageStatsMap.get(e);e&&(e.costSum+=Date.now()-t,e.costCount++)}_isUserSideError(e){return this._userSideErrorCodes.has(e)||120001<=e&&e<=13e4||10100<=e&&e<=10200}_getSendMessageSpecifiedKey(s){let{MSG_IMAGE:e,MSG_AUDIO:t,MSG_VIDEO:r,MSG_FILE:i,CONV_C2C:n,CONV_GROUP:o,GRP_AVCHATROOM:a}=this._core.OuterConstant;if([e,t,r,i].includes(s.type))return Dl;if(s.conversationType===n)return Tl;if(s.conversationType===o){let e=this._core.appStore["groupStore"],t=e.getGroup(s.to);if(t){let e=t["type"];return e===a?Ol:Al}}}_calcAverageValue(e,t){return 0===e.costCount?0:t===Rl?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)}},xl=new class{constructor(){this._lastCycleStats=new Map,this._currentCycleStats=new Map}init(e){var{OuterEvent:e,notificationCenter:t}=this._core=e;this._initStatsMap(),t.subscribeOuterEvent(e.MESSAGE_RECEIVED,this._onMessageReceived,this)}addMessageSequence(e){var t=this._getReceivedMessageSpecifiedKey(e),{utils:{isUndefined:s},OuterConstant:{CONV_GROUP:r},ssoLog:i}=this._core;s(t)||!this._currentCycleStats.has(t)?i.warn("addMessageSequence",Cl+".addMessageSequence invalid key:"+t):({conversationID:s,sequence:i}=e,e=s.replace(r,""),0!==(s=this._lastCycleStats.get(t)).size&&s.has(e)&&i>(r=s.get(e)).minSeq&&i<r.maxSeq?this._insertToLastCycle(i,r):this._addToCurrentCycle(t,e,i))}getStatResult(e){var t=this._lastCycleStats.get(e);if(!t||0===t.size)return this._transferCycleDataOptimized(e),null;let r=0,i=0;return t.forEach(e=>{var{sortedSequences:e,minSeq:t,maxSeq:s}=e;0<e.length&&(i+=e.length,r+=s-t+1)}),0===r?null:(this._transferCycleDataOptimized(e),{total_count:r,success_count_business:i,percent_business:El(i/r*100,2)})}reset(){this._lastCycleStats.clear(),this._currentCycleStats.clear()}dispose(){var{notificationCenter:e,OuterEvent:{MESSAGE_RECEIVED:t}}=this._core;e.unSubscribeOuterEvent(t,this._onMessageReceived,this),this.reset()}_initStatsMap(){Object.values(wl).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?bl:Ll):null}}_insertToLastCycle(e,t){t.dirty&&(t.sortedSequences.sort((e,t)=>e-t),t.dirty=!1);var s=this._findInsertPos(t.sortedSequences,e);t.sortedSequences.splice(s,0,e),t.minSeq=Math.min(t.minSeq,e),t.maxSeq=Math.max(t.maxSeq,e)}_findInsertPos(e,t){let s=0,r=e.length-1;for(;s<=r;){var i=Math.floor((s+r)/2);if(e[i]===t)return i;e[i]<t?s=i+1:r=i-1}return s}_addToCurrentCycle(e,t,s){let r=this._currentCycleStats.get(e).get(t);r?(r.sortedSequences.push(s),r.minSeq=Math.min(r.minSeq,s),r.maxSeq=Math.max(r.maxSeq,s),r.dirty=!0):(r={sortedSequences:[s],minSeq:s,maxSeq:s,dirty:!1},this._currentCycleStats.get(e).set(t,r))}},Vl=new class{constructor(){this._totalDelay=0,this._totalCount=0,this._countLessThan1s=0,this._countLessThan3s=0}init(e){var{OuterEvent:{MESSAGE_RECEIVED:e},notificationCenter:t}=this._core=e;t.subscribeOuterEvent(e,this._onMessageReceived,this)}addMessageDelay(e){var t=this._core.common["timeManager"],t=t.getServerTimeSeconds()-e;0<t&&(this._totalDelay+=t,this._totalCount++,t<=1?this._countLessThan1s++:t<=3&&this._countLessThan3s++)}getStatResult(){var e;return 0===this._totalCount?null:(e={total_count:this._totalCount,success_count_business:this._countLessThan1s,success_count_platform:this._countLessThan3s,percent_business:this._calculatePercentage(this._countLessThan1s,this._totalCount),percent_platform:this._calculatePercentage(this._countLessThan3s,this._totalCount),average_value:this._calculateAverageDelay(this._totalCount)},this.reset(),e)}reset(){this._totalDelay=0,this._totalCount=0,this._countLessThan1s=0,this._countLessThan3s=0}dispose(){var{notificationCenter:e,OuterEvent:{MESSAGE_RECEIVED:t}}=this._core;e.unSubscribeOuterEvent(t,this._onMessageReceived,this),this.reset()}_onMessageReceived(e){let{data:t=[]}=e,{MSG_GRP_TIP:s,MSG_GRP_SYS_NOTICE:r}=this._core["OuterConstant"],i=[s,r];t.forEach(e=>{!i.includes(e.type)&&0<e.clientTime&&this.addMessageDelay(e.clientTime)})}_calculateAverageDelay(e){return 0===e?0:El(this._totalDelay/e,1)}_calculatePercentage(e,t){return El(e/t*100,2)}},Bl=new class{init(e){this.core=e}},n=new class{constructor(){this.name="MessageQualityStat",this._reportIndex=0,this._wholePeriod=!1,this._pendingReports=[],this._failedLogsCache=new Map}install(e){var{helper:t,notificationCenter:s,InnerEvent:{QUALITY_STAT:r,LOGOUT:i,DESTROY:n},constants:{WORKFLOW_NAME:o,WORKFLOW_STEP:a}}=this._core=e;Bl.init(e),ql.init(e),xl.init(e),Vl.init(e),t.registerWorkflowStep(o.SYNC_SERVER_INFO_AFTER_LOGIN,a.QUALITY_REPORT,this.handleLoginSuccess,this),s.subscribeInnerEvent(r,this._handleQualityStat,this),s.subscribeInnerEvent(i,this._reset,this),s.subscribeInnerEvent(n,this._dispose,this)}handleLoginSuccess(){var{store:e,helper:t,utils:{isUndefined:s}}=this._core,e=(e.get("cloudConfig")||{})["q_rpt_interval"],s=s(e)?12e4:Number(e);t.taskScheduler.addTask({id:Fl,intervalMs:s,callback:this.report,context:this})}report(){this._wholePeriod=!0;var e=[...Ul.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&&ql.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:Gl[e],timestamp:Date.now(),network_type:ol.ONLINE,extension:""},Object.assign(Object.assign({},e),t))}_getStatResultByKey(e){switch(e){case yl:return Vl.getStatResult();case Tl:case Al:case Ol:case Dl:case Rl:return ql.getStatResult(e);case Ll:case Nl:case bl:return xl.getStatResult(e);default:return null}}_uploadQualityReports(t){return I(this,void 0,void 0,function*(){try{var r={header:this._core.common.getCommonHead(),quality:t};yield function(){var{common:e,channel:t}=Bl.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=Cl+"._cacheFailedLogs";let s=[...this._failedLogsCache.get(Sl)||[],...e];10<s.length&&(s=s.slice(s.length-10),console.log(t+" logs overflow, keeping last 10 items")),this._failedLogsCache.set(Sl,s),console.log(t+" count: "+s.length),this._pendingReports=[]}_reset(){var e=this._core["helper"];e.taskScheduler.removeTask(Fl)}_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(),Vl.dispose(),xl.dispose()}};let jl=new class{constructor(){this.name="OfflineMessageSynchronizer",this._lastMessageSequenceMapOnDisconnect=new Map}install(e){var{common:{workflowManager:t},constants:{WORKFLOW_NAME:s,WORKFLOW_STEP:r,InnerEvent:i}}=this._core=e;t.registerWorkflowStep(s.SYNC_SERVER_INFO_AFTER_RE_ONLINE,r.HISTORY_MESSAGE_RECOVER,this._syncOfflineMessage,this),e.notificationCenter.subscribeInnerEvent(i.SOCKET_DISCONNECTED,this._updateLastMessageSequenceMapOnDisconnect,this)}_syncOfflineMessage(e){let t=((null==e?void 0:e.result)||{})["conversationList"],{OuterConstant:s,utils:{isArray:r}}=this._core;if(r(t)){let e=t.filter(e=>e.type===s.CONV_GROUP&&e.groupProfile.type!==s.GRP_AVCHATROOM);return this._recoverGroupHistoryMessage(e)}}_recoverGroupHistoryMessage(e){return I(this,void 0,void 0,function*(){let i=this._core["OuterConstant"],n=[],o=[];return yield Promise.all(null==e?void 0:e.map(r=>I(this,void 0,void 0,function*(){var{groupProfile:{groupID:e}={},lastMessage:{lastSequence:t}={}}=r,e=""+i.CONV_GROUP+e,s=this._getLocalLastMessageSequence(e);this._shouldRecoverHistory({localLastMessageSequence:s,serverLastMessageSequence:t})&&(yield this._recoverHistoryForConversation({conversationID:e,localLastMessageSequence:s,serverLastMessageSequence:t,groupTipList:o})),n.push(e.replace(i.CONV_GROUP,""))}))),{recoverRevokeNoticeGroupIDList:n,groupTipList:o}})}_recoverHistoryForConversation(e){return I(this,arguments,void 0,function*({conversationID:I,localLastMessageSequence:E,serverLastMessageSequence:C,groupTipList:S}){try{let{utils:{isArray:e,isObject:t,isEmpty:s},OuterEvent:r,OuterConstant:i,notificationCenter:n,message:o,appStore:a,common:{getMessagePreviewText:u}}=this._core,l=C-E,c=Math.min(20,l),d={},p=yield o.messageHistory.getGroupRoamingMessagesByAnchor({conversationID:I,sequence:E+c,direction:i.Direction.FORWARD,count:c}),{nextReqMessageIDFromServer:h,hasNoMoreHistoryMessage:g,messageList:_,serverGroupTipList:m}=p,v=(e(m)&&S.push(...m),g&&h<0),f=[];if(e(_)&&(_.forEach(e=>{o.messageReceiver.groupMessageReceiver.updateMessageProfile(e),e.from===i.CONV_SYSTEM&&(e.isSystemMessage=!1),o.messageDataHandler.storeConversationMessage(e)&&!s(e.payload)&&(f.push(e),e._isExcludedFromLastMessage||(d.lastMessage=Object.assign({},e)))}),0<f.length)&&n.emitOuterEvent(r.MESSAGE_RECEIVED,{name:r.MESSAGE_RECEIVED,data:f}),!v&&0<_.length){let e=_[_.length-1].sequence;yield this._recoverHistoryForConversation({conversationID:I,localLastMessageSequence:e,serverLastMessageSequence:C,groupTipList:S})}t(d.lastMessage)&&(d.lastMessage.messageForShow=u(d.lastMessage.type,d.lastMessage.payload),a.conversationStore.updateConversation(I,d))}catch(E){this._core.ssoLog.error("_recoverHistoryForConversation","Recovery failed for conversation:"+I,{error:E})}})}_updateLastMessageSequenceMapOnDisconnect(){let e=this._core["message"],r=e.messageDataHandler.getContinuousMessagesByConversation();for(let[t,s]of r)if(!t.startsWith("C2C")){let e=Array.from(s.values());var i;0<(null==e?void 0:e.length)&&(i=e[e.length-1].sequence,this._lastMessageSequenceMapOnDisconnect.set(t,i))}}_getLocalLastMessageSequence(e){var t=this._core["message"];return this._lastMessageSequenceMapOnDisconnect.has(e)?this._lastMessageSequenceMapOnDisconnect.get(e):null==(e=(t=t.messageDataHandler.getLocalMessageList(e))[t.length-1])?void 0:e.sequence}_shouldRecoverHistory(e){var t,{localLastMessageSequence:e,serverLastMessageSequence:s}=e;return"number"==typeof e&&"number"==typeof s&&(t=s-e,0!==s)&&0<e&&1<=t&&t<300}},Kl,Wl;Kl=us.PROFESSIONAL,Wl=[t,dr,e,_,Er,n,jl,yi,_n,Bn,ua,ba,Gu,Ur,nu,vu,Zu,Il];var Hl=Object.freeze({__proto__:null,ChatError:m,WorkflowManager:h,buildAndSendPacket:Ks,get builtInPlugins(){return Wl},checkBusinessCapabilityBits:Fs,deepMerge:zs,getCurrentUserID:g,getErrorMessage:Ds,getMessagePreviewText:Js,isC2CConv:e=>X(e)&&e.slice(0,3)===es.CONV_C2C,isCommunity:xs,isGroupConv:e=>X(e)&&e.slice(0,5)===es.CONV_GROUP,isTopic:Vs,isUnlimitedAVChatRoom:function(){var e;return!(null==(e=k.store.get("instance"))||!e.unlimitedAVChatRoom)},liteChatInstanceMap:qs,registerInterceptor:Us,registerValidateConfig:ks,requireAuth:Rs,get sdkEdition(){return Kl},updateGroupAtInfo:(t,s)=>{var{CONV_AT_ME:r,CONV_AT_ALL:i,CONV_AT_ALL_AT_ME:n}=S;if(!function(t,e){let{CONV_AT_ME:s,CONV_AT_ALL:r,CONV_AT_ALL_AT_ME:i}=S,{groupID:n,sequence:o}=t,a=!1;return xs({groupID:n})&&e.forEach(e=>{e.messageSequence===o&&(e.atTypeArray.includes(s)&&t.groupAtType.includes(r)&&(e.atTypeArray=[i]),e.atTypeArray.includes(r)&&t.groupAtType.includes(s)&&(e.atTypeArray=[i],e.__random=t.__random,e.__sequence=t.__sequence),a=!0)}),a}(t,s)){let e=[...t.groupAtType];e.includes(r)&&e.includes(i)&&(e=[n]);r={from:t.from,groupID:t.groupID,topicID:t.topicID,messageSequence:t.sequence,atTypeArray:e,__random:t.__random,__sequence:t.__sequence};s.push(r)}},validateAndExecute:ws,validateParameters:Ls});class Yl{constructor(){this._builtInPlugins=new Set,this._externalPlugins=new Set}static getInstance(){return Yl._instance||(Yl._instance=new Yl),Yl._instance}static setInstance(e){Yl._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=ee(e)?e:[e]).findIndex(e=>"AVChatRoom"===(null==e?void 0:e.name)),i=-1<r?s.splice(r,1):[];s.forEach(e=>{this._isPluginInstalled(e.name)||(e&&Vt(e.install)?(t.add(e.name),Vt(e.getInstalledSubPlugins)?e.install(G.getInstance().exposeApiForPlugin(),i):e.install(G.getInstance().exposeApiForPlugin()),Vt(e.handleLoginSuccess)&&this._isLoggedIn()&&e.handleLoginSuccess()):Vt(e)?(t.add(e.name),e(G.getInstance().exposeApiForPlugin()),Vt(e.handleLoginSuccess)&&this._isLoggedIn()&&e.handleLoginSuccess()):console.warn('A plugin must either be a function or an object with an "install" function.'))})}_isPluginInstalled(e){return this._builtInPlugins.has(e)||this._externalPlugins.has(e)}_isLoggedIn(){var e;return!0===(null==(e=k.store.get("login"))?void 0:e.isLoggedIn)}}var F,$l,zl,N,b,Jl,Ql=new class{constructor(){this._conversationMap=new Map}getConversationMap(){return this._conversationMap}getConversation(e){return this._conversationMap.get(e)}updateConversation(e,t,s={emit:!0,needSort:!1}){let{emit:r,needSort:i}=s,n=this._conversationMap.get(e);n&&!ze(t)&&(Object.keys(t).forEach(e=>{n[e]=t[e]}),r)&&k.notificationCenter.emitInnerEvent(d.CONVERSATION_UPDATED,{needSort:i})}deleteConversation(e){this._conversationMap.has(e)&&(this._conversationMap.delete(e),k.notificationCenter.emitInnerEvent(d.CONVERSATION_UPDATED))}},Xl=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&&!ze(t)&&Object.keys(t).forEach(e=>{s[e]=t[e]})}},Zl=new class{constructor(){this._messagesByConversation=new Map}updateMessage(s,t,e){let r,{operation:i,updateUnreadCount:n=!0}=e,o=f(e,["operation","updateUnreadCount"]),a=[];for(let e of t){let t=null==(r=this._messagesByConversation.get(s))?void 0:r.get(e);if(!t)return!1;Object.keys(o).forEach(e=>{t[e]=o[e]}),a.push(t)}return this._emitMessageStoreOperationEvent(i,{conversationID:s,messageList:a,updateUnreadCount:n}),a}getMessagesByConversation(e){return[...(null==(e=this._messagesByConversation.get(e))?void 0:e.values())||[]]}getMessages(){return this._messagesByConversation}_emitMessageStoreOperationEvent(e,t){var s=t["conversationID"];Vs(s)?k.notificationCenter.emitInnerEvent(Qt[e],t):k.notificationCenter.emitInnerEvent(e,t)}},ec=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)}},tc=Object.freeze({__proto__:null,conversationStore:Ql,groupStore:Xl,messageStore:Zl,userStore:ec});class G{static getInstance(){return G._instance||(G._instance=new G),G._instance}static setInstance(e){G._instance=e}constructor(){this._experimentalApiMap={statTUIKeyFeatures:this.statKeyFeatureUsage.bind(this)},this._apiHandlersMap={},this._apiMap={on:k.notificationCenter.subscribeOuterEvent.bind(k.notificationCenter),off:k.notificationCenter.unSubscribeOuterEvent.bind(k.notificationCenter),destroy:this.destroy.bind(this),callExperimentalAPI:this.callExperimentalAPI.bind(this),use:Yl.getInstance().installExternalPlugin.bind(Yl.getInstance()),registerPlugin:this.registerPlugin.bind(this),setLogLevel:this.setLogLevel.bind(this)}}registerPlugin(e){k.ssoLog.debug("registerPlugin",e)}statKeyFeatureUsage(e){k.ssoLog.debug("statTUIKeyFeatures",e)}setLogLevel(e){k.ssoLog.debug("setLogLevel",e),k.ssoLog.setLogLevel(e)}getApiMap(){return this._apiMap}setApiMap(e){this._apiMap=e}registerApi(e){let{common:{timeManager:n},utils:{safeStringify:t}}=k,{apiName:o,context:s,methodName:a=o,matcher:r}=e;this._apiHandlersMap[o]||(this._apiHandlersMap[o]=[]),this._apiHandlersMap[o].push({context:s,methodName:a,matcher:r}),this._apiMap[o]&&1!==this._apiHandlersMap[o].length||(this._apiMap[o]=(...s)=>{let r=n.getServerTimeMs(),i=0;"login"===o&&(i=4),ps.includes(o)&&k.ssoLog.debug(o,o+" start params: "+t(s)),ws(a,s);for(let t of this._apiHandlersMap[o])if(!t.matcher||t.matcher(s))try{let e=t.context[t.methodName].bind(t.context)(...s);return this._isPromiseLike(e)?this._handleAsyncResult(e,o,i,r):(this._reportApiSuccessLog({result:e,apiName:o,eventType:i,startTime:r}),e)}catch(s){throw k.ssoLog.error(o,`${o} fail ${null==s?void 0:s.message})`,{error:s,costTime:n.getServerTimeMs()-r,eventType:i,method:o}),s}})}registerExperimentalAPI(e,t,s){this._experimentalApiMap[e]=t[s||e].bind(t)}destroy(){return I(this,void 0,void 0,function*(){var e,t;try{null!=(e=k.store.get("login"))&&e.isLogin&&(yield this._apiMap.logout()),k.notificationCenter.emitInnerEvent(d.DESTROY)}catch(e){console.debug("destroy error: ",e)}finally{k.notificationCenter.emitOuterEvent(jt.SDK_DESTROY,{SDKAppID:null==(t=k.store.get("instance"))?void 0:t.sdkAppId}),qs.clear(),Yl.getInstance().clear(),h.getInstance().destroy(),k.destroy()}})}exposeApiForClient(){return this._apiMap}exposeApiForPlugin(){return Object.assign(Object.assign({InnerEvent:d,InnerEventSubType:k.notificationCenter.InnerEventSubType,OuterEvent:jt,OuterConstant:S,SignalingEvent:Ht,helper:Object.assign(Object.assign(Object.assign({},k.utils),k.common),{registerApi:this.registerApi.bind(this),registerExperimentalAPI:this.registerExperimentalAPI.bind(this),registerInterceptor:Us,registerValidateConfig:ks,checkBusinessCapabilityBits:Fs,registerWorkflowStep:h.getInstance().registerWorkflowStep.bind(h.getInstance()),ChatError:m}),apiMap:this._apiMap},k),{constants:Object.assign(Object.assign({},_s),k.constants),common:Object.assign(Object.assign(Object.assign({},Hl),k.common),{workflowManager:h.getInstance()}),utils:k.utils,appStore:tc})}callExperimentalAPI(e,t){return this._experimentalApiMap[e]?this._experimentalApiMap[e](t):Promise.reject(new m({code:as.INVALID_OPERATION}))}_isPromiseLike(e){return null!==e&&"object"==typeof e&&"function"==typeof e.then}_handleAsyncResult(e,t,s,r){return e.then(e=>(this._reportApiSuccessLog({result:e,apiName:t,eventType:s,startTime:r}),e)).catch(e=>{throw k.ssoLog.error(t,`${t} fail ${null==e?void 0:e.message})`,{error:e,costTime:k.common.timeManager.getServerTimeMs()-r,eventType:s,method:t}),e})}_reportApiSuccessLog(e){let{result:t,apiName:s,startTime:r,eventType:i}=e;var e=k.common["timeManager"],{successLog:{message:n,moreMessage:o}={message:"",moreMessage:""}}=t||{},a=e.getServerTimeMs();"login"===s&&(r+=e.getTimeOffsetWithServer()),ps.includes(s)&&k.ssoLog.info(s,s+` success ${n} `+o,{costTime:a-r,eventType:i,message:n,moreMessage:o}),null!=t&&t.successLog&&delete t.successLog}}class sc{constructor(){this._latestLoginAt=0,this._latestSendOnlinePresenceRequestTime=0,this._helloInterval=120}init(){var{notificationCenter:e,store:t}=k;t.set("login",{isReady:!1}),G.getInstance().registerApi({apiName:"login",context:this}),G.getInstance().registerApi({apiName:"logout",context:this}),G.getInstance().registerApi({apiName:"getLoginUser",context:this}),G.getInstance().registerApi({apiName:"isReady",context:this}),e.subscribeInnerEvent(d.RECONNECTED,this._reLogin,this),k.notificationCenter.subscribeInnerEvent(d.DESTROY,this._dispose,this)}login(u){return I(this,void 0,void 0,function*(){var e,t=(k.store.get("instance")||{})["sdkEdition"];try{if(this._isLoginIn())return this._createRepeatLoginResponse();if(this._isLoginFrequencyExceeded())throw new m({functionName:"login",code:as.REPEAT_LOGIN});var s=yield this._performLogin(u),r=(this._validateAfterLogin(s),this._handleLoginSuccess(s),yield this._ensureAsyncComplete(),this._updateAndEmitSDKReady(),this._latestLoginAt=0,null==(e=k.channel.getSocketAdapter())?void 0:e.getId()),{appId:i,href:n}=k.store.get("instance")||{},{instanceID:o,customStatus:a}=s||{};return{code:0,data:s,successLog:{message:t,moreMessage:`socketID:${r} instanceID:${o} customStatus:${a} href: ${n} appId: `+i}}}catch(e){let t=e["errorCode"];throw t!==as.REPEAT_LOGIN&&(this._latestLoginAt=0),new m({functionName:"login",code:t})}})}_reLogin(){return I(this,void 0,void 0,function*(){var e,t,s,r,i;try{this._isLoginIn()&&(t=yield Os())&&({instanceID:s,customStatus:r}=t,k.store.set("login",{statusInstanceId:s}),h.getInstance().executeWorkflow(p.SYNC_SERVER_INFO_AFTER_RE_ONLINE,{customStatus:r,statusType:Xt.USER_STATUS_ONLINE}),i=null==(e=k.channel.getSocketAdapter())?void 0:e.getId(),k.ssoLog.info("reLogin",`socketId:${i} instanceId:`+s))}catch(e){console.warn(e)}})}logout(){return I(this,arguments,void 0,function*(t=hs.USER_INITIATED){let e=k["ssoLog"];e.debug("logout","logout start logoutReason: "+t);try{yield this._performLogout(t),e.info("logout","logout success"),k.ssoLog.uploadSSOLogData()}catch(t){let e=t["errorCode"];throw new m({functionName:"logout",code:e})}finally{this._handleLogoutCompleted()}return{code:0,data:{}}})}getLoginUser(){return this._isLoginIn()?g():""}isReady(){var e;return null==(e=k.store.get("login"))?void 0:e.isReady}_updateAndEmitSDKReady(){k.store.set("login",{isReady:!0}),setTimeout(()=>{k.notificationCenter.emitOuterEvent(jt.SDK_READY,{name:jt.SDK_READY})},1)}_updateAndEmitSDKNotReady(){k.store.set("login",{isReady:!1}),k.notificationCenter.emitOuterEvent(jt.SDK_NOT_READY,{name:jt.SDK_NOT_READY})}_validateAfterLogin(e){if(!e)throw new m({functionName:"login",message:"login response is empty"});var{tinyID:e,a2Key:t}=e||{};if(!e)throw new m({functionName:"login",code:as.NO_TINYID});if(!t)throw new m({functionName:"login",code:as.NO_A2KEY})}_createRepeatLoginResponse(){var e;return{code:0,data:{actionStatus:"OK",errorCode:0,errorInfo:Ds({code:"RepeatLogin",replacement1:null==(e=k.store.get("login"))?void 0:e.userId}),repeatLogin:!0}}}_performLogin(s){return I(this,void 0,void 0,function*(){var{userID:e,userSig:t}=s;return k.store.set("login",{userId:e,userSig:t}),this._latestLoginAt=Date.now(),Os()})}_ensureAsyncComplete(){return I(this,void 0,void 0,function*(){yield new Promise(e=>{setTimeout(()=>e(null),1)})})}_handleLoginSuccess(e){var t=k.common["timeManager"],{helloInterval:s,timeStamp:r,customStatus:i,purchaseBits:n}=e;t.calculateTimeOffsetWithServer(this._latestLoginAt,1e3*r),this._helloInterval=s||120,this._updateLoginStore(e),k.user.userStatus.setCustomStatus(i),h.getInstance().executeWorkflow(p.SYNC_SERVER_INFO_AFTER_LOGIN,{purchaseBits:n}),k.common.taskScheduler.addTask({id:vs,intervalMs:1e3*this._helloInterval,callback:this._sendOnlinePresenceRequest,context:this})}_performLogout(e){return function(s){return I(this,void 0,void 0,function*(){var e=s["logoutReason"],t="im_open_status.wslogout",e=k.common.generateProtocolData({servcmd:t,data:{wslogout_type:e,isWebUniapp:0}}),t=e.head.seq+t;return yield k.channel.sendPacket(e,{requestId:t})})}({logoutReason:e})}_handleLogoutCompleted(){this._updateAndEmitSDKNotReady(),this._reset(),h.getInstance().reset(),k.notificationCenter.emitInnerEvent("logout")}_updateLoginStore(e){var{a2Key:e,tinyID:t,instanceID:s,authKey:r}=e;k.store.set("login",{a2Key:e,tinyID:t,statusInstanceId:s,authKey:r,isLoggedIn:!0})}_sendOnlinePresenceRequest(){return I(this,void 0,void 0,function*(){this._latestSendOnlinePresenceRequestTime=Date.now();try{e="im_open_status.wshello",t=k.common.generateProtocolData({servcmd:e,data:{isWebUniapp:0}}),e=t.head.seq+e,yield k.channel.sendPacket(t,{requestId:e})}catch(e){k.ssoLog.warn("_sendOnlinePresenceRequest"," error:"+e.message)}var e,t})}_isLoginIn(){var e;return!0===(null==(e=k.store.get("login"))?void 0:e.isLoggedIn)}_isLoginFrequencyExceeded(){return Date.now()-this._latestLoginAt<=15e3}_reset(){console.log("Login reset"),k.common.taskScheduler.removeTask(vs),this._helloInterval=120,this._latestSendOnlinePresenceRequestTime=0,this._latestLoginAt=0,k.store.clear("login"),k.store.set("login",{isReady:!1})}_dispose(){console.log("Login dispose"),this._reset();var e=k["notificationCenter"];e.unSubscribeInnerEvent(d.RECONNECTED,this._reLogin,this),e.unSubscribeInnerEvent(d.DESTROY,this._dispose,this)}}let rc={login:{userID:{required:!0,rules:["string"],allowEmpty:!1},userSig:{required:!0,rules:["string"],allowEmpty:!1}}},ic={logout:!0};class nc{constructor(){this.loginAction=new sc,this.kickedOutHandler=new As,this.loginAction.init(),this.kickedOutHandler.init(),ks({auth:ic,params:rc})}}(b=F=F||{}).CONV_C2C="C2C",b.CONV_GROUP="GROUP",b.CONV_TOPIC="TOPIC",b.CONV_SYSTEM="@TIM#SYSTEM",(N=$l=$l||{}).MSG_PRIORITY_HIGH="High",N.MSG_PRIORITY_NORMAL="Normal",N.MSG_PRIORITY_LOW="Low",N.MSG_PRIORITY_LOWEST="Lowest",(t=zl=zl||{}).MSG_TEXT="TIMTextElem",t.MSG_CUSTOM="TIMCustomElem",t.MSG_LOCATION="TIMLocationElem",t.MSG_FACE="TIMFaceElem",t.MSG_IMAGE="TIMImageElem",t.MSG_AUDIO="TIMSoundElem",t.MSG_FILE="TIMFileElem",t.MSG_VIDEO="TIMVideoFileElem",t.MSG_GRP_TIP="TIMGroupTipElem",t.MSG_GRP_SYS_NOTICE="TIMGroupSystemNoticeElem",t.MSG_MERGER="TIMRelayElem";let oc={1:$l.MSG_PRIORITY_HIGH,2:$l.MSG_PRIORITY_NORMAL,3:$l.MSG_PRIORITY_LOW,4:$l.MSG_PRIORITY_LOWEST},ac=((dr=Jl=Jl||{}).IN="in",dr.OUT="out",{});function uc(e){var t,s,r;return e?(void 0===ac[e]?(t=("3"+(r=new Date).getHours()).slice(-2),s=("0"+r.getMinutes()).slice(-2),r=("0"+r.getSeconds()).slice(-2),ac[e]=parseInt([t,s,r,"0001"].join(""),10),console.log("autoIncrementIndex start index:"+ac[e])):ac[e]+=1,ac[e]):0}class lc{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=$l.MSG_PRIORITY_NORMAL,this._relayFlag=!1;var t,{clientTime:s=k.common.timeManager.getServerTimeSeconds()||0,senderTinyID:r,currentUser:i,needReadReceipt:n,isSupportExtension:o,customModerationConfigurationId:a,to:u,from:l,nick:c="",avatar:d="",time:p,messageControlInfo:h,tinyID:g,cloudCustomData:_="",messageLifeTime:m,messageVersion:v=0,conversationType:f,sequence:I,checkResult:E=0,isPlaceMessage:C=0,messageFlagBits:S,receiverList:M,isSystemMessage:y=!1,status:T=Kt.SUCCESS,revokeReason:A="",conversationSubType:O,clientSequence:D,protocol:R="JSON",revokerInfo:L={userID:"",nick:"",avatar:""},readReceiptInfo:N={readCount:void 0,unreadCount:void 0,isPeerRead:void 0,timestamp:0},random:b,groupProfile:G,atUserList:P,flow:w,isRead:U=!1}=e;this.clientTime=s,this.senderTinyID=r||g,this.needReadReceipt=!0===n||1===n,this.isSupportExtension=!0===o||1===o,this._cmConfigID=a,this.to=u,this.nick=c,this.avatar=d,this.protocol=R,this.random=void 0===b?(t=t||99999999,Math.round(Math.random()*t)):b,this.time=p||Math.ceil(Date.now()/1e3),this._isExcludedFromLastMessage=!(null==h||!h.excludedFromLastMessage),this._isExcludedFromUnreadCount=!(null==h||!h.excludedFromUnreadCount),this.isModified=!!v,this.cloudCustomData=_,this.messageLifeTime=m,this.from=l||null,this.sequence=I||0,this.conversationType=f||F.CONV_C2C,this.hasRiskContent=1<E,this.version=v,this.isPlaceMessage=C,this.isRevoked=2===C||8===S,this.isSystemMessage=y,this.readReceiptInfo=N,this.revokeReason=A,this.revokerInfo=L,this._receiverList=M,this.conversationSubType=O,this.revoker=(null==L?void 0:L.revoker)||"",this.clientSequence=D||I||0,this.status=T,this.atUserList=P||[],this.flow=w,this.isRead=U,this.reInitialize(i),this._initC2CReadReceiptInfo(e),this._extractGroupInfo(G)}getElements(){return this._elements}isOnlineMessage(){return 0===this.messageLifeTime}setElement(e){Array.isArray(e)?this._elements=e:this._elements=[e],this._updatePayloadAndType()}transformElementsToServerFormat(){return this._elements?Array.isArray(this._elements)?this._elements.map(e=>e.transformToServerFormat()):this._elements.transformToServerFormat():null}setRelayFlag(e){this._relayFlag=e}validateBeforeSend(){var e,t;return this._relayFlag?{isValid:!0}:0<(null==(e=this._elements)?void 0:e.length)?null==(t=null==(e=this._elements[0])?void 0:e.validateBeforeSend)?void 0:t.call(e):{isValid:!1}}_updatePayloadAndType(){this._elements[0]&&(this.payload=this._elements[0].content,this.type=this._elements[0].type)}_initC2CReadReceiptInfo(e){var{readReceiptSentByPeer:e,timestamp:t=0}=e;this.conversationType===F.CONV_C2C&&!0===this.needReadReceipt&&(this.readReceiptInfo.isPeerRead=1===e,this.readReceiptInfo.timestamp=t)}_extractGroupInfo(e){var t,s;e&&({From_AccountNick:e,From_AccountHeadurl:t,MsgFrom_AccountExtraInfo:s}=e,s=(s||{})["NameCard"],"string"==typeof e&&(this.nick=e),"string"==typeof t&&(this.avatar=t),"string"==typeof s)&&(this.nameCard=s)}reInitialize(e){e===this.from&&(this.isRead=!0),this._initSequence(e),this._concatConversationID(e),this.generateMessageID()}_concatConversationID(e){var t=this.conversationType;t!==F.CONV_SYSTEM?(e=t!==F.CONV_C2C||e===this.from?this.to:this.from,this.conversationID=e?""+t+e:null):this.conversationID=F.CONV_SYSTEM}_initSequence(e){0===this.clientSequence&&e&&(this.clientSequence=uc(e)),0===this.sequence&&this.conversationType===F.CONV_C2C&&(this.sequence=this.clientSequence)}generateMessageID(){this.from===F.CONV_SYSTEM&&(this.senderTinyID="144115198244471703"),this.ID=`${this.senderTinyID}-${this.clientTime}-`+this.random}setIsRead(e){this.isRead=e}}class cc{static parseServerPushElement(e){var{MsgContent:e={}}=e,{Data:e,Ext:t,Desc:s}=e;return new cc({data:e,description:s,extension:t})}constructor(e){this.type=zl.MSG_CUSTOM;var{data:e="",description:t="",extension:s=""}=e;this.content={data:e,description:t,extension:s}}transformToServerFormat(e){var{isMergerMessage:e=!1}=e||{},{data:e,description:t,extension:s}=e?this.payload:this.content;return{MsgType:this.type,MsgContent:{Data:e,Ext:s,Desc:t}}}validateBeforeSend(){let t=k.utils["isEmpty"],e=[this.content.data,this.content.description,this.content.extension].some(e=>!t(e));return{isValid:e,error:e?null:{message:"content can not be empty"}}}}class dc{static parseServerPushElement(e){var{MsgContent:e={Text:""}}=e,e=e["Text"];return new dc({text:e})}constructor(e){this.type=$t.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 pc=new class{constructor(){this._elementClassMap={[zl.MSG_CUSTOM]:cc,[zl.MSG_TEXT]:dc}}init(){G.getInstance().registerApi({apiName:"createCustomMessage",context:this}),G.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=Jl.OUT}=e,r=(k.store.get("login")||{})["userId"],t=(this._isSendByCurrentInstance({from:t,flow:s,currentUser:r})?this._updateWithSenderInfo(e):this._isMultiEndpointSyncMessage({from:t,flow:s,currentUser:r})&&(e.flow=Jl.OUT),Object.assign(Object.assign({},e),{currentUser:r}));return new lc(t)}createCustomMessage(t){let e=g(),s=this.createMessage(Object.assign(Object.assign({},t),{from:e})),r=this._elementClassMap[zl.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 dc({text:t}),s=g(),(e=k.message.messageFactory.createMessage(Object.assign(Object.assign({},e),{from:s}))).setElement(t),e):null}_updateWithSenderInfo(e){var{nick:t,avatar:s}=e,{userId:r,tinyID:i}=k.store.get("login")||{},n=ec.getUserProfile(r);return e.nick=t||(null==n?void 0:n.nick)||"",e.avatar=s||(null==n?void 0:n.avatar)||"",e.tinyID=e.tinyID||i||"",e.from=r,e.status=Kt.UNSENT,e.flow=Jl.OUT,e}_isMultiEndpointSyncMessage(e){var{from:e,flow:t,currentUser:s}=e;return e===s&&t===Jl.IN}_isSendByCurrentInstance(e){var{from:e,flow:t,currentUser:s}=e;return e===s&&t===Jl.OUT}};let hc={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}},gc={HonorImportance:{range:["LOW","NORMAL"],defaultValue:void 0},MeizuNotifyType:{range:[0,1],defaultValue:void 0}},_c={enableIOSBackgroundNotification:{range:[!0,!1],defaultValue:!1},interruptionLevel:{range:["passive","active","time-sensitive","critical"],defaultValue:"active"}};function mc(r,i){return Object.keys(i).forEach(e=>{var{range:t,defaultValue:s}=i[e];r[e]=t.includes(r[e])?r[e]:s}),r}function vc(e){return k.utils.isPlainObject(e)?{PushFlag:!0===e.disablePush?1:0,Title:e.title||"",Desc:e.description||"",Ext:e.extension||"",ApnsInfo:function(e){var{apnsInfo:e={},ignoreIOSBadge:t=!1,disableVoipPush:s}=e,{ignoreIOSBadge:r,disableVoipPush:i,enableIOSBackgroundNotification:n}=e=mc(e,_c),e=f(e,["ignoreIOSBadge","disableVoipPush","enableIOSBackgroundNotification"]),r=!0===r||!0===t?1:0;let o;return Q(s)||(o=!1===s?1:0),Q(i)||(o=!1===i?1:0),Object.assign(Object.assign({},e),{BadgeMode:r,IsVoipPush:o,ContentAvailable:n?1:0})}(e),AndroidInfo:function(e){var{androidInfo:e={},androidOPPOChannelID:t=""}=e,t=e.OPPOChannelID||t,{sound:s="",FCMChannelID:r=""}=e=mc(e,gc),e=f(e,["sound","FCMChannelID"]);return Object.assign(Object.assign({},e),{Sound:-1===(s=(e=s).lastIndexOf("."))?e:e.slice(0,s),OPPOChannelID:t,GoogleChannelID:r})}(e)}:hc}function fc(e){let{From_AccountHeadurl:t,From_AccountNick:s,IsNeedReadReceipt:r,IsPeerRead:i,IsSyncMsg:n,MsgBody:o,MsgClientTime:a,MsgLifeTime:u,MsgRandom:l,MsgSeq:c,MsgTimeStamp:d,SendMsgControl:p,SupportMessageExtension:h,TinyId:g,MsgCheckResult:_,CloudCustomData:m,MsgVersion:v,MsgFlagBits:f,RevokerInfo:I}=e,E,{From_Account:C,To_Account:S}=e;if(1===n){let e=S;S=C,C=e}if(I){let{Reason:e,Revoker_Account:t,Revoker_FromUin:s}=I;E={reason:e,revoker:t,revokerFromUin:s,userID:t}}return{from:C,avatar:t,nick:s,needReadReceipt:1===r,isSyncMessage:n,clientTime:a,messageLifeTime:u,random:l,sequence:c,time:d,messageControlInfo:{excludedFromLastMessage:1===(null==p?void 0:p.NoLastMsg),excludedFromUnreadCount:1===(null==p?void 0:p.NoUnread)},isSupportExtension:h,to:S,tinyID:g,checkResult:_,cloudCustomData:m,revokerInfo:E,messageVersion:v,messageFlagBits:f,readReceiptSentByPeer:i,elements:Cc(o)}}function Ic(e){var{From_Account:e,MsgBody:t,MsgClientTime:s,MsgRandom:r,MsgSeq:i,MsgTimeStamp:n,To_Account:o,MsgVersion:a,CloudCustomData:u}=e;return{from:e,clientTime:s,random:r,sequence:i,time:n,to:o,elements:Cc(t),messageVersion:a,cloudCustomData:u}}function Ec(e){let{ClientSeq:t,From_Account:s,GroupInfo:r,MsgBody:i,MsgClientTime:n,MsgRandom:o,MsgSeq:a,MsgTimeStamp:u,SendMsgControl:l,SupportMessageExtension:c,TinyId:d,CloudCustomData:p,MsgVersion:h,MsgCheckResult:g,NeedReadReceipt:_,IsPlaceMsg:m,RevokerInfo:v,GroupAtInfo:f}=e,I,E=$l.MSG_PRIORITY_NORMAL;if(Object.keys(oc).includes(String(e.MsgPriority))&&(E=oc[e.MsgPriority]),v){let{Reason:e,Revoker_Account:t,Revoker_FromUin:s}=v;I={reason:e,revoker:t,revokerFromUin:s,userID:t}}var C=function(e){let t=[];return Array.isArray(e)&&e.forEach(e=>{0===e.GroupAtAllFlag?t.push(e.GroupAt_Account):1===e.GroupAtAllFlag&&t.push(S.MSG_AT_ALL)}),t}(f);return{clientSequence:t,from:s,groupProfile:r,clientTime:n,priority:E,random:o,sequence:a,time:u,messageControlInfo:{excludedFromLastMessage:1===(null==l?void 0:l.NoLastMsg),excludedFromUnreadCount:1===(null==l?void 0:l.NoUnread)},isSupportExtension:c,tinyID:d,cloudCustomData:p,messageVersion:h,messageCheckResult:g,needReadReceipt:_,isPlaceMessage:m,revokerInfo:I,atUserList:C,elements:Cc(i),to:function(e){var{utils:{isEmpty:t},constants:{IS_TOPIC_MESSAGE:s}}=k,{ToGroupId:e,GroupInfo:{MillionGroupFlag:r=0,TopicId:i}={}}=e;return r!==s||t(i)?e:i}(e)}}function Cc(e){var t;return e?Array.isArray(e)?e.map(e=>{var t=k.message.messageFactory.getElementClass(e.MsgType);return null==t?void 0:t.parseServerPushElement(e)}):null==(t=k.message.messageFactory.getElementClass(e.MsgType))?void 0:t.parseServerPushElement(e):null}function Sc(e){var{From_Account:e,MsgBody:t,MsgClientTime:s,MsgRandom:r,MsgSeq:i,MsgTimeStamp:n,GroupId:o,TopicId:a,MsgVersion:u,CloudCustomData:l}=e;return{from:e,clientTime:s,random:r,sequence:i,time:n,groupID:o,topicID:a,elements:Cc(t),messageVersion:u,cloudCustomData:l}}function Mc({conversationUpdateFields:e,message:t}){var{conversationID:s,conversationType:r,conversationSubType:i,flow:n,_isExcludedFromUnreadCount:o,_isExcludedFromLastMessage:a}=t,a=a?"":t,t=!o&&n===Jl.IN;e.has(s)?(e.get(s).lastMessage=a,t&&e.get(s).unreadCount++):e.set(s,{conversationID:s,type:r,subType:i,unreadCount:t?1:0,lastMessage:a})}function yc(e){return e.filter(e=>{var t=!ze(null==e?void 0:e.getElements()),s=1===(null==e?void 0:e.isPlaceMessage);return t||k.ssoLog.error("emptyMessageBody",`from:${e.from} to:${e.to} sequence:`+e.sequence),t&&!s})}function Tc(e){var t=k.message["messageDataHandler"];return!t.isInMessageList(e)&&!t.isMessageSentByCurrentInstance(e)}var Ac=Object.freeze({__proto__:null,autoIncrementIndex:uc,filterValidMessages:yc,parseServerGroupMessage:Ec,parseServerPushC2CModifyMessage:Ic,parseServerPushGroupModifyMessage:Sc,parseServerPushMessage:fc,parseServerPushMessageElement:Cc,shouldStoreMessage:Tc,updateConversationFields:Mc});let Oc=k.utils["isPlainObject"];function Dc(e,t={}){let{onlineUserOnly:s,messageControlInfo:r}=t,i=t["offlinePushInfo"],n=(e.conversationType===F.CONV_C2C&&!0===s&&(i?i.disablePush=!0:i={disablePush:!0}),"");"string"==typeof e.cloudCustomData&&0<e.cloudCustomData.length&&(n=e.cloudCustomData);var o=[];if(r&&Oc(r)){let{excludedFromUnreadCount:e,excludedFromLastMessage:t,excludedFromContentModeration:s}=r;!0===e&&o.push("NoUnread"),!0===t&&o.push("NoLastMsg"),!0===s&&o.push("NoMsgCheck")}return{onlineUserOnly:s,cloudCustomData:n,messageControlInfo:o,offlinePushInfo:i}}function Rc(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 Lc(t,s){return I(this,void 0,void 0,function*(){var e=yield Ks((t.conversationType===F.CONV_GROUP?function(e,t){var s,{onlineUserOnly:r,cloudCustomData:i,messageControlInfo:n,offlinePushInfo:o}=Dc(e,t),a=JSON.parse(JSON.stringify(e.transformElementsToServerFormat()));let u;return ee(e._receiverList)&&0<e._receiverList.length&&(u=e._receiverList,50<e._receiverList.length)&&(u=e._receiverList.slice(0,50),console.warn("ReceiverListLimit")),{servcmd:"group_open_http_svc.send_group_msg",data:{From_Account:null==(s=k.store.get("login"))?void 0:s.userId,GroupId:e.to,MsgBody:a,CloudCustomData:i,Random:e.random,MsgPriority:e.priority,ClientSeq:e.clientSequence,GroupAtInfo:e._groupAtInfoList,OnlineOnlyFlag:r?1:0,MsgClientTime:e.clientTime,OfflinePushInfo:vc(o),SendMsgControl:r?void 0:n,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:Rc(t)}}}:function(e,t){var s,{onlineUserOnly:r,cloudCustomData:i,messageControlInfo:n,offlinePushInfo:o}=Dc(e,t),r=!0===r?0:void 0,a=JSON.parse(JSON.stringify(e.transformElementsToServerFormat()));return{servcmd:"openim.sendmsg",data:{From_Account:null==(s=k.store.get("login"))?void 0:s.userId,To_Account:e.to,MsgBody:a,CloudCustomData:i,MsgSeq:e.sequence,MsgRandom:e.random,MsgLifeTime:r,From_AccountNick:e.nick,From_AccountHeadurl:e.avatar,SendMsgControl:0!==r?n:void 0,MsgClientTime:e.clientTime,IsNeedReadReceipt:!0===e.needReadReceipt?1:0,SupportMessageExtension:!0===e.isSupportExtension?1:0,IsRelayMsg:!0===e._relayFlag?1:0,CustomModerationConfigID:e._cmConfigID,OfflinePushInfo:vc(o),forbidCallbackControl:Rc(t)}}})(t,s));return e?{time:e.MsgTime,messageDropReason:e.MsgDropReason,sequence:e.MsgSeq}:null})}let Nc=k.utils["isPlainObject"],{MSG_AUDIO:bc,MSG_FILE:Gc,MSG_IMAGE:Pc,MSG_VIDEO:wc,MSG_MERGER:Uc}=S;class kc{init(){G.getInstance().registerApi({apiName:"sendMessage",context:this,matcher:e=>![bc,Gc,Pc,wc,Uc].includes(e[0].type)})}sendMessage(c,d){return I(this,void 0,void 0,function*(){let{TOTAL_COUNT:e,SEND_COST:o,SUCCESS_COUNT:a,FAILED_COUNT:t}=ds;if(!(c instanceof lc))throw new m({code:as.MSG_INSTANCE_REQUIRED});let s=c.validateBeforeSend();if(!s.isValid){let{code:e,message:t=""}=s.error||{};throw new m({code:e,message:t})}this._reportMessageSendQuality({name:e,message:c});let u=!1;var l=(k.message||{})["messageDataHandler"];try{let r=(d||{})["messageControlInfo"],i=null,n=(l.addRandomOfSentMessage(c.random),Date.now());if(c.conversationType===F.CONV_C2C?(u=!0===(null==d?void 0:d.onlineUserOnly),i=yield Lc(c,d)):c.conversationType===F.CONV_GROUP&&(yield this._validateBeforeSendGroupMessage(c),i=yield Lc(c,d)),i){let{messageDropReason:e,sequence:t,time:s}=i;if(this._updateNickAndAvatarOfSentMessageByMe(c),e&&this._logRateLimitInfo(c,t,e),this._reportMessageSendQuality({name:a,message:c}),this._reportMessageSendQuality({name:o,message:c,startTs:n}),!0===c.isResend){let e=l.findMessage(c.ID);e&&(k.ssoLog.debug("sendMessage","sendMessage resend ok. ID:"+e.ID),l.deleteConversationMessage(e))}return c.status=Kt.SUCCESS,c.time=s,c.conversationType===F.CONV_GROUP&&(c.sequence=t),u?c._onlineOnlyFlag=!0:(l.storeConversationMessage(c),this._applySentMessageControlInfo(c,r),this._emitOnlineMessageSent(c)),{code:0,data:{message:c}}}}catch(e){c.status=Kt.FAIL,l.removeRandomOfSentMessage(c.random);var{errorCode:r,errorMessage:i="",errorInfo:i=i}=e||{};throw this._hasRiskContent(r)&&(c.hasRiskContent=!0),u||this._isRejectedByRestApi(r)||l.storeConversationMessage(c),this._reportMessageSendQuality({name:t,message:c,error:e}),i=`head.seq: type:${c.type} from:${c.from} to:${c.to} `+i,new m({code:r,message:i,data:{message:c}})}})}_hasRiskContent(e){return 80001===e||80004===e}_isRejectedByRestApi(e){return 10100<=e&&e<=10200||120001<=e&&e<=13e4}_emitOnlineMessageSent(e){var t=e._isExcludedFromLastMessage?"":e,{conversationID:s,conversationType:r}=e,i=Vs(s)?d.TOPIC_NEW_MESSAGE:d.NEW_MESSAGE;k.notificationCenter.emitInnerEvent(i,{result:{conversationUpdateFieldList:[{conversationID:s,type:r,message:e,lastMessage:t,unreadCount:0}]}})}_applySentMessageControlInfo(e,t){t&&Nc(t)&&(!0===t.excludedFromLastMessage&&(e._isExcludedFromLastMessage=!0),!0===t.excludedFromUnreadCount)&&(e._isExcludedFromUnreadCount=!0)}_logRateLimitInfo(e,t,s){e=`from:${e.from} to:${e.to} sequence:${t} messageDropReason:`+s;k.ssoLog.warn("messageDropReason",e)}_updateNickAndAvatarOfSentMessageByMe(e){var t=(k.message||{})["messageDataHandler"];let s=!1;var r,i=e["conversationID"],n=t.getLatestMsgSentByMe(i);n&&({nick:n,avatar:r}=n,s=n!==e.nick||r!==e.avatar||s)&&t.updateNickAndAvatarOfSentMessage({conversationID:i,latestNick:e.nick,latestAvatar:e.avatar,isSentByMe:!0})}_validateBeforeSendGroupMessage(i){return I(this,void 0,void 0,function*(){var{to:t,from:s}=i;let r=t,e=Xl.getGroup(r);if(xs({groupID:r})&&null!=e&&e.isSupportTopic)throw new m({code:as.MSG_SEND_GRP_WITH_TOPIC_FAIL});if(Vs(t)&&([r]=t.split(is.TOPIC),e=Xl.getGroup(r)),!e&&"function"==typeof(null==(t=G.getInstance().getApiMap())?void 0:t.getGroupProfile)){let e=yield G.getInstance().getApiMap().getGroupProfile({groupID:r});if((null==(t=null==(t=null==e?void 0:e.data)?void 0:t.group)?void 0:t.type)===S.GRP_AVCHATROOM){let e=Ds({code:as.MSG_SEND_FAIL_NOT_IN_AV,replacement1:s,replacement2:r});throw new m({code:as.MSG_SEND_FAIL_NOT_IN_AV,message:e})}}return!0})}_reportMessageSendQuality(e){k.notificationCenter.emitInnerEvent(d.QUALITY_STAT,{label:cs.MESSAGE_SEND_SUCCESS_RATE,data:e})}}class Fc{constructor(e){this.value=e,this.next=null}}class qc{constructor(e){this.head=null,this.tail=null,this.size=0,this.capacity=e}append(e){this.size>=this.capacity&&this.removeHead();e=new Fc(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 xc=new class{constructor(){this._sparseMessagesByConversation=new Map,this._latestMessageSentByPeerMap=new Map,this._latestMessageSentByMeMap=new Map,this._randomOfSentMessageList=new qc(100)}init(){k.notificationCenter.subscribeInnerEvent(d.LOGOUT,this._reset,this),k.notificationCenter.subscribeInnerEvent(d.DESTROY,this._dispose,this)}get _messagesByConversation(){return Zl.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 u;if(this._messagesByConversation.has(a)||this._sparseMessagesByConversation.has(a)){let e=this._getUniqueIdOfMessage(t),o=this._getMessageFromLocalMessage(a,e);if(o){let{messageVersion:s,elements:r,cloudCustomData:i,checkResult:e=0}=t,n=1<e;if(console.log(`conversationToMessageMap modifyConversationMessage localVersion:${o.version} remoteVersion:`+s),o.version<s){let e=this._getUniqueIdOfMessage(o),t=Je(r);return null!=(u=this._messagesByConversation.get(a))&&u.has(e)?Zl.updateMessage(a,[e],{isModified:!0,version:s,_elements:t,payload:t[0].content,type:t[0].type,cloudCustomData:i,hasRiskContent:n,operation:zt.modify}):(o.version=s,o._elements=t,o.payload=o._elements[0].content,o.type=o._elements[0].type,o.cloudCustomData=i,o.isModified=!0,o.hasRiskContent=n),{isUpdated:!0,message:o}}return{isUpdated:!1,message:o}}}return{isUpdated:!1,message:null}}_getMessageFromLocalMessage(e,s){var t;if(this._messagesByConversation.has(e))return null==(t=this._messagesByConversation.get(e))?void 0:t.get(s);if(this._sparseMessagesByConversation.has(e)){let t=[...this._sparseMessagesByConversation.get(e).values()];for(let e=0;e<t.length;e++)if(this._getUniqueIdOfMessage(t[e])===s)return t[e]}return null}findMessage(t){let s=null,e=Array.from(this._messagesByConversation.values());for(var r of e)if(s=Array.from(r.values()).find(e=>e.ID===t)||null)break;if(!s){let e=Array.from(this._sparseMessagesByConversation.values());for(var i of e)if(s=i.get(t)||null,s)break}return s}deleteConversationMessageList(e){this._messagesByConversation.has(e)&&(this._messagesByConversation.delete(e),this._latestMessageSentByMeMap.delete(e),this._latestMessageSentByPeerMap.delete(e)),this._sparseMessagesByConversation.has(e)&&this._sparseMessagesByConversation.delete(e)}revokeMessage({conversationID:t,sequence:s,random:r,revoker:i}){let e=this._messagesByConversation.get(t),n=null;if(e){var o=Array.from(e.values());if(n=this._findMessageBySequenceAndRandom({messageList:o,random:r,sequence:s})){let e=this._getUniqueIdOfMessage(n);return Zl.updateMessage(t,[e],{isRevoked:!0,revoker:i,operation:zt.revoke}),n}}if(this._sparseMessagesByConversation.has(t)){let e=Array.from(this._sparseMessagesByConversation.get(t).values());if(n=this._findMessageBySequenceAndRandom({messageList:e,random:r,sequence:s}))return n.isRevoked=!0,n.revoker=i,n}}_findMessageBySequenceAndRandom({messageList:t,sequence:s,random:r}){for(let e=0;e<t.length;e+=1){var i=t[e];if(i.sequence===s&&(Q(r)||i.random===r))return i}return null}prependLocalMessageList(e){let{messageList:s,conversationID:t}=e;if(0===s.length)return[];var r=[],i=[],n=this._messagesByConversation.get(t)||new Map;for(let t of s){let e=this._getUniqueIdOfMessage(t);n.has(e)||(r.push(t),i.push([e,t]))}if(0<i.length){let e=new Map([...i,...n.entries()]);this._messagesByConversation.set(t,e),this._updateLatestMessageSentByMe(t),this._updateLatestMessageSentByPeer(t)}return r}storeSparseMessageList(r){if(0!==r.length){let e=r[0]["conversationID"],s=r.length;this._sparseMessagesByConversation.has(e)||this._sparseMessagesByConversation.set(e,new Map);var i=this._sparseMessagesByConversation.get(e);for(let t=0;t<s;t++){let e=r[t];i.has(e.ID)||i.set(e.ID,e)}}}_updateLatestMessageSentByMe(t){var e,s=Array.from((null==(e=this._messagesByConversation.get(t))?void 0:e.values())||[]);if(0!==s.length)for(let e=s.length-1;0<=e;e--)if("out"===s[e].flow){this._setLatestMsgSentByMe(t,s[e]);break}}_updateLatestMessageSentByPeer(t){var e,s=Array.from((null==(e=this._messagesByConversation.get(t))?void 0:e.values())||[]);if(0!==s.length&&t.startsWith("C2C"))for(let e=s.length-1;0<=e;e--)if("in"===s[e].flow){this._setLatestMsgSentByPeer(t,s[e]);break}}_getUniqueIdOfMessage(e){var{from:e,to:t,random:s,sequence:r,time:i}=e;return e+`-${t}-${s}-${r}-`+i}_setLatestMsgSentByPeer(e,t){this._latestMessageSentByPeerMap.set(e,t)}_setLatestMsgSentByMe(e,t){this._latestMessageSentByMeMap.set(e,t)}getLatestMsgSentByPeer(e){return this._latestMessageSentByPeerMap.get(e)}getLatestMsgSentByMe(e){return this._latestMessageSentByMeMap.get(e)}addRandomOfSentMessage(e){this._randomOfSentMessageList.append(e)}removeRandomOfSentMessage(e){this._randomOfSentMessageList.delete(e)}updateNickAndAvatarOfSentMessage(e){let{conversationID:t="",latestAvatar:n,latestNick:o,isSentByMe:s=!0}=e,r=this._messagesByConversation.get(t);if(r){let e=Array.from(r.values()),i=s?"out":"in";e.forEach(e=>{var{nick:t,avatar:s,flow:r}=e;r===i&&(t!==o&&(e.nick=o),s!==n)&&(e.avatar=n)})}}isInMessageList(e){var t=e["conversationID"];return!!t&&!!this._messagesByConversation.has(t)&&(e=this._getUniqueIdOfMessage(e),null==(t=this._messagesByConversation.get(t))?void 0:t.has(e))}isMessageSentByCurrentInstance(e){e=e.random;return this._randomOfSentMessageList.has(e)}getContinuousMessagesByConversation(){return this._messagesByConversation}getLocalMessageList(e){e=this._messagesByConversation.get(e);return e?[...e.values()]:[]}getSparseMessageList(e){e=this._sparseMessagesByConversation.get(e);return e?[...e.values()]:[]}_reset(){this._messagesByConversation.clear(),this._latestMessageSentByPeerMap.clear(),this._latestMessageSentByMeMap.clear(),this._randomOfSentMessageList.clear()}_dispose(){this._reset(),k.notificationCenter.unSubscribeInnerEvent(d.LOGOUT,this._reset,this),k.notificationCenter.unSubscribeInnerEvent(d.DESTROY,this._dispose,this)}};function Vc(e,t){var s,r,i,n,o,a,u,l=Ql.getConversation(e);null!=l&&l.lastMessage&&(l=l["lastMessage"],{lastTime:s,lastSequence:r,version:i}=l,{time:t,sequence:n,messageVersion:o,elements:a,cloudCustomData:u}=t,s===t)&&r===n&&i!==o&&(l.type=a[0].type,l.payload=a[0].content,l.messageForShow=Js(l.type,l.payload),l.cloudCustomData=u,l.version=o,Ql.updateConversation(e,{lastMessage:l}))}class Bc{init(){G.getInstance().registerApi({apiName:"modifyMessage",context:this})}modifyMessage(l){return I(this,void 0,void 0,function*(){let{to:r,payload:t,sequence:i,conversationType:n,random:o,time:a,from:u,type:s}=l;if(this._canModifyMessageElement(s)){let e=l.getElements();1<e.length&&(e[0].type=s,e[0].content=t)}try{let t=null,s;if(n===F.CONV_C2C?t=yield function(c){return I(this,void 0,void 0,function*(){let{from:e,to:t,version:s=0,sequence:r,random:i,time:n,type:o,cloudCustomData:a}=c,u={From_Account:e,To_Account:t,MsgVersion:s,MsgSeq:r,MsgRandom:i,MsgTime:n,MsgType:o,MsgBody:c.transformElementsToServerFormat(),CloudCustomData:a},l=yield Ks({servcmd:"openim.modify_c2c_msg",data:u});if(l){let{MsgBody:e,MsgVersion:t,CloudCustomData:s}=l;return{elements:Cc(e),messageVersion:t,cloudCustomData:s}}})}(l):n===F.CONV_GROUP&&(t=yield function(o){return I(this,void 0,void 0,function*(){let{to:e,version:t=0,sequence:s,cloudCustomData:r}=o,i={GroupId:e,MsgVersion:t,MsgSeq:s,MsgBody:o.transformElementsToServerFormat(),CloudCustomData:r},n=yield Ks({servcmd:"openim.modify_group_msg",data:i});if(n){let{MsgBody:e,MsgVersion:t,CloudCustomData:s}=n;return{elements:Cc(e),messageVersion:t,cloudCustomData:s}}})}(l)),t){let e=""+n+r;return r===g()&&n===F.CONV_C2C&&(e=""+n+u),s={conversationType:n,from:u,to:r,time:a,random:o,sequence:i,elements:null==t?void 0:t.elements,cloudCustomData:null==t?void 0:t.cloudCustomData,messageVersion:null==t?void 0:t.messageVersion,conversationID:e},this._handleModifyMessageSuccess(s),{code:0,data:{message:l},successLog:{message:"to:"+r}}}}catch(e){let t=(e||{})["errorCode"];throw new m({functionName:"modifyMessage",code:t})}})}_handleModifyMessageSuccess(e){var t=e["conversationID"],{isUpdated:s,message:r}=k.message.messageDataHandler.modifyConversationMessage(t,e);!0===s&&k.notificationCenter.emitOuterEvent(jt.MESSAGE_MODIFIED,{name:jt.MESSAGE_MODIFIED,data:[r]}),k.notificationCenter.emitInnerEvent(d.MESSAGE_MODIFIED,{conversationID:t,message:r}),Vc(t,e)}_canModifyMessageElement(e){return[zl.MSG_TEXT,zl.MSG_CUSTOM,zl.MSG_LOCATION,zl.MSG_FACE].includes(e)}}class jc{init(){var e=k["notificationCenter"],t=e["InnerEventSubType"];h.getInstance().registerWorkflowStep(p.RECEIVE_C2C_NEW_MESSAGE,o.HANDLE_C2C_NEW_MESSAGE,this._handleC2CMessagePush,this),h.getInstance().registerWorkflowStep(p.RECEIVE_C2C_NEW_MESSAGE,o.EMIT_C2C_MESSAGE_EVENT,this._emitMessageEventsAfterReceiveNewMessage,this),h.getInstance().registerWorkflowStep(p.SYNC_SERVER_INFO_AFTER_RE_ONLINE,o.EMIT_C2C_MESSAGE_EVENT,this._emitMessageEventsAfterSyncUnreadMessage,this),e.subscribeInnerEvent(d.MESSAGE_PUSH,t.C2C_REALTIME_MESSAGE,this._executeReceiverNewMessageWorkFlow,this),e.subscribeInnerEvent(d.MESSAGE_PUSH,t.C2C_MESSAGE_MODIFIED,this._handleC2CMessageModify,this),e.subscribeInnerEvent(d.DESTROY,this._dispose,this)}_executeReceiverNewMessageWorkFlow(e){h.getInstance().executeWorkflow(p.RECEIVE_C2C_NEW_MESSAGE,e)}_handleC2CMessagePush(e){let t=e.data||{},s=(k.message||{})["messageDataHandler"],r=[],i=new Map;return t.C2cMsgArray.forEach(e=>{e=this._generateC2CMessage(e);this._updateMessageProfile(e);let t=1===e.isModified;s.isMessageSentByCurrentInstance(e)?e.isModified=t:t=!1,e.isOnlineMessage()?(e._onlineOnlyFlag=!0,s.isMessageSentByCurrentInstance(e)||r.push(e)):Tc(e)&&(s.storeConversationMessage(e)&&Mc({conversationUpdateFields:i,message:e}),s.isMessageSentByCurrentInstance(e)&&!t||r.push(e))}),{conversationUpdateFieldList:[...i.values()],messages:r}}_emitMessageEventsAfterReceiveNewMessage(e){var{messages:e=[]}=(null==(e=e.result)?void 0:e[o.HANDLE_C2C_NEW_MESSAGE])||{};this._emitMessageEvents(e)}_emitMessageEventsAfterSyncUnreadMessage(e){var{messages:e=[]}=(null==(e=e.result)?void 0:e[o.UNREAD_MESSAGE_SYNC])||{};this._emitMessageEvents(e)}_emitMessageEvents(e){var t=(null==e?void 0:e.filter(e=>!0===(null==e?void 0:e.isModified)))||[],t=(0<t.length&&k.notificationCenter.emitOuterEvent("onMessageModified",{name:"onMessageModified",data:t}),null==e?void 0:e.filter(e=>!(null!=e&&e.isModified)));0<t.length&&k.notificationCenter.emitOuterEvent("onMessageReceived",{name:"onMessageReceived",data:t})}_generateC2CMessage(e){var t=F.CONV_C2C,e=fc(e),t=k.message.messageFactory.createMessage(Object.assign(Object.assign({},e),{conversationType:t,flow:Jl.IN})),e=e["elements"];return t.setElement(e),t}_updateMessageProfile(r){var e;let i=(k.message||{})["messageDataHandler"],t=null==(e=k.store.get("login"))?void 0:e.userId,{from:s,nick:n,avatar:o,conversationID:a=""}=r;if(s!==t){let s=i.getLatestMsgSentByPeer(a);if(s){let{nick:e,avatar:t}=s;Q(n)||Q(o)?(r.nick=X(e)?e:r.nick,r.avatar=X(t)?t:r.avatar):n===e&&o===t||(i.updateNickAndAvatarOfSentMessage({conversationID:a,latestNick:n,latestAvatar:o,isSentByMe:!1}),this._updateConversationUserProfile({conversationID:a,nick:n,avatar:o}))}}else{let e=i.getLatestMsgSentByMe(a);!e||n===e.nick&&o===e.avatar||i.updateNickAndAvatarOfSentMessage({conversationID:a,latestNick:n,latestAvatar:o,isSentByMe:!0})}}_updateConversationUserProfile(e){var{conversationID:e,nick:t,avatar:s}=e,{userProfile:r={}}=Ql.getConversation(e)||{};r.avatar===s&&r.nick===t||Ql.updateConversation(e,{userProfile:Object.assign(Object.assign({},r),{nick:t,avatar:s})})}_updateMessageListDueToModify(e){var t=e["conversationID"],{isUpdated:s,message:r}=k.message.messageDataHandler.modifyConversationMessage(t,e);!0===s&&k.notificationCenter.emitOuterEvent("onMessageModified",{name:"onMessageModified",data:[r]}),k.notificationCenter.emitInnerEvent("ModifyMessageSuccess",e),Vc(t,e)}_handleC2CMessageModify(e){e.C2cMsgModNotifys.forEach(e=>{var t=F.CONV_C2C,e=Ic(e),{to:s,from:r}=e;let i=""+t+s;s===(null==(s=k.store.get("login"))?void 0:s.userId)&&(i=""+t+r),e=Object.assign({conversationType:t,conversationID:i},e),this._updateMessageListDueToModify(e)})}_dispose(){var e=k["notificationCenter"],e=e["InnerEventSubType"];k.notificationCenter.unSubscribeInnerEvent(d.MESSAGE_PUSH,e.C2C_REALTIME_MESSAGE,this._handleC2CMessagePush,this),k.notificationCenter.unSubscribeInnerEvent(d.MESSAGE_PUSH,e.C2C_MESSAGE_MODIFIED,this._handleC2CMessageModify,this),k.notificationCenter.unSubscribeInnerEvent(d.DESTROY,this._dispose,this)}}class Kc{init(){var e=k["notificationCenter"],t=e["InnerEventSubType"];h.getInstance().registerWorkflowStep(p.RECEIVE_GROUP_NEW_MESSAGE,o.HANDLE_GROUP_NEW_MESSAGE,this._handleGroupMessagePush,this),h.getInstance().registerWorkflowStep(p.RECEIVE_GROUP_NEW_MESSAGE,o.EMIT_GROUP_MESSAGE_EVENT,this._emitMessageEvents,this),e.subscribeInnerEvent(d.MESSAGE_PUSH,t.GROUP_REALTIME_MESSAGE,this._executeReceiverNewMessageWorkFlow,this),e.subscribeInnerEvent(d.MESSAGE_PUSH,t.GROUP_MESSAGE_MODIFIED,this._handleGroupMessageModify,this),e.subscribeInnerEvent(d.DESTROY,this._dispose,this)}_executeReceiverNewMessageWorkFlow(e){this._canExecuteReceiverNewMessageWorkFlow(e)&&h.getInstance().executeWorkflow(p.RECEIVE_GROUP_NEW_MESSAGE,e)}_handleGroupMessagePush(e){let t=e.data||{},s=k.message["messageDataHandler"],r=[],i=new Map,n=null==t?void 0:t.GroupMsgArray;return null!=n&&n.forEach(e=>{var t;1!==e.GroupInfo.NotVisible&&(e=this._generateGroupMessage(e),this.updateMessageProfile(e),t=1===e.isModified,s.isMessageSentByCurrentInstance(e)&&(e.isModified=t),e.isOnlineMessage()?(e._onlineOnlyFlag=!0,s.isMessageSentByCurrentInstance(e)||r.push(e)):Tc(e)&&s.storeConversationMessage(e)&&(r.push(e),Mc({conversationUpdateFields:i,message:e})))}),{conversationUpdateFieldList:[...i.values()],messages:r}}_emitMessageEvents(e){var e=((null==(e=e.result)?void 0:e[o.HANDLE_GROUP_NEW_MESSAGE])||{})["messages"],t=(null==e?void 0:e.filter(e=>!0===(null==e?void 0:e.isModified)))||[],t=(0<t.length&&k.notificationCenter.emitOuterEvent("onMessageModified",{name:"onMessageModified",data:t}),(null==e?void 0:e.filter(e=>!(null!=e&&e.isModified)))||[]);0<t.length&&k.notificationCenter.emitOuterEvent("onMessageReceived",{name:"onMessageReceived",data:t})}_generateGroupMessage(e){var t=F.CONV_GROUP,e=Ec(e),t=k.message.messageFactory.createMessage(Object.assign(Object.assign({},e),{conversationType:t,flow:Jl.IN})),e=e["elements"];return t.setElement(e),t}updateMessageProfile(i){var e;let t=(k.message||{})["messageDataHandler"],s=null==(e=k.store.get("login"))?void 0:e.userId,{from:r,nick:n,avatar:o,conversationID:a="",_elements:u}=i;if(r===s){let e=t.getLatestMsgSentByMe(a);!e||n===e.nick&&o===e.avatar||t.updateNickAndAvatarOfSentMessage({conversationID:a,latestNick:n,latestAvatar:o,isSentByMe:!0})}else if(r===S.CONV_SYSTEM){let{operationType:e,memberInfoList:t,operatorInfo:s}=u,r={};if(ze(t)?ze(s)||(r=s):[ns.JOINED,ns.KICKED,ns.ADMIN_SET,ns.ADMIN_CANCELED].includes(e)&&(r=Object.assign({},t[0])),!ze(r)){let{nick:e="",avatar:t=""}=r;i.nick=e,i.avatar=t}}}_updateMessageListDueToModify(e){var t=e["conversationID"],{isUpdated:s,message:r}=k.message.messageDataHandler.modifyConversationMessage(t,e);!0===s&&k.notificationCenter.emitOuterEvent("onMessageModified",{name:"onMessageModified",data:[r]}),Vc(t,e)}_handleGroupMessageModify(e){e.GroupMsgModNotifys.forEach(e=>{var t=F.CONV_GROUP,{topicID:s,groupID:r}=e=Sc(e),s=s||r,e=Object.assign({conversationType:t,conversationID:""+t+s,to:s},e);this._updateMessageListDueToModify(e)})}_dispose(){var e=k["notificationCenter"],{GROUP_REALTIME_MESSAGE:t,GROUP_MESSAGE_MODIFIED:s}=e["InnerEventSubType"];e.unSubscribeInnerEvent(d.MESSAGE_PUSH,t,this._handleGroupMessagePush,this),e.unSubscribeInnerEvent(d.MESSAGE_PUSH,s,this._handleGroupMessageModify,this),e.unSubscribeInnerEvent(d.DESTROY,this._dispose,this)}_canExecuteReceiverNewMessageWorkFlow(e){var{GroupId:e,GroupType:t}=(null==(e=null==(e=null==e?void 0:e.GroupMsgArray)?void 0:e[0])?void 0:e.GroupInfo)||{},t=t===rs.GRP_AVCHATROOM;return!(!Xl.getGroup(e)&&t)}}var Wc=new class{constructor(){this.c2cMessageReceiver=new jc,this.groupMessageReceiver=new Kc}init(){this.c2cMessageReceiver.init(),this.groupMessageReceiver.init()}};let Hc={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."}}}},Yc={createCustomMessage:!0,sendMessage:!0,modifyMessage:!0};var $c=new class{getGroupRoamingMessagesByAnchor(i){return I(this,void 0,void 0,function*(){try{var{conversationID:t,count:s,direction:u,sequence:l,messageSequenceList:e,getType:r}=i,c=t.replace(es.CONV_GROUP,""),d=[];let a=l;if(u===Wt.BACKWARD){if("number"!=typeof l)return{messageList:[],hasNoMoreHistoryMessage:!1,nextReqMessageIDFromServer:""};a=l+s-1}var p=yield function(n){return I(this,void 0,void 0,function*(){var{groupID:e,count:t,messageSequence:s,messageSequenceList:r,getType:i}=n;return yield Ks({servcmd:"group_open_http_svc.group_msg_get",data:{GroupId:e,ReqMsgNumber:t,WithRecalledMsg:1,Version:1,ReqMsgSeq:s,ReqMsgSeqList:r,GetType:i}})})}({groupID:c,count:s,messageSequence:a,messageSequenceList:e,getType:r});if(p){let{RspMsgList:t=[],NextReqMsgSeq:e=0,IsFinished:s,InvisibleMsgSeq:r}=p,i=`groupID:${c} sequence:${l} reqSeq:${a} direction:${u} complete:${s} nextSequence:${e} remoteMsgCount:${t.length} invisibleSequenceList:`+r,n=[];for(let e=0;e<t.length;e++){var h=t[e],g=(h.From_Account===S.CONV_SYSTEM&&d.push(h),this._parseMessage(h));n.push(g)}n.reverse();let o=2===s;u===Wt.BACKWARD&&(o=n[n.length-1].sequence>=l);var _=yc(n);return k.ssoLog.info("getGroupRoamingMessagesByAnchor",i),{messageList:_,invisibleSequenceList:r,nextReqMessageIDFromServer:e,hasNoMoreHistoryMessage:o,serverGroupTipList:d}}}catch(e){var{errorCode:t,errorInfo:s}=e||{};throw new m({code:t,message:s})}})}_parseMessage(e){var t=es.CONV_GROUP,e=(4===e.Event&&(e.MsgBody.MsgType=S.MSG_GRP_TIP),Ec(e)),t=pc.createMessage(Object.assign(Object.assign({},e),{conversationType:t,flow:"in"}));return t.setElement(e.elements),t}};class zc{constructor(){this.messageHelper=Ac,this.messageFactory=pc,this.messageSender=new kc,this.messageAction=new Bc,this.messageReceiver=Wc,this.messageDataHandler=xc,this.messageHistory=$c,this.messageSender.init(),this.messageFactory.init(),this.messageAction.init(),this.messageReceiver.init(),this.messageDataHandler.init(),ks({auth:Yc,params:Hc})}}let Jc="Tag_Profile_IM_",Qc={NICK:Jc+"Nick",GENDER:Jc+"Gender",BIRTHDAY:Jc+"BirthDay",LOCATION:Jc+"Location",SELFSIGNATURE:Jc+"SelfSignature",ALLOWTYPE:Jc+"AllowType",LANGUAGE:Jc+"Language",AVATAR:Jc+"Image",MESSAGESETTINGS:Jc+"MsgSettings",ADMINFORBIDTYPE:Jc+"AdminForbidType",LEVEL:Jc+"Level",ROLE:Jc+"Role"},Xc="Tag_Profile_Custom",Zc="profileCustomField",ed={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:[]},td=new Map([[Qc.NICK,"nick"],[Qc.GENDER,"gender"],[Qc.BIRTHDAY,"birthday"],[Qc.LOCATION,"location"],[Qc.SELFSIGNATURE,"selfSignature"],[Qc.ALLOWTYPE,"allowType"],[Qc.LANGUAGE,"language"],[Qc.AVATAR,"avatar"],[Qc.MESSAGESETTINGS,"messageSettings"],[Qc.ADMINFORBIDTYPE,"adminForbidType"],[Qc.LEVEL,"level"],[Qc.ROLE,"role"]]);var sd=new class{createProfile(e,t){let s={userID:e,profileCustomField:[]};return t.forEach(e=>{var{tag:e,value:t}=e;e&&-1<e.indexOf(Xc)?s.profileCustomField.push({key:e,value:t}):td.has(e)&&(s[td.get(e)]=t)}),Object.assign(Object.assign({},ed),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!==Zc&&s.push({tag:Qc[e.toUpperCase()],value:t[e]})}),t.profileCustomField&&ee(t.profileCustomField)&&t.profileCustomField.forEach(e=>{s.push({tag:e.key,value:e.value})}),s}normalizeProfileFields(e){let r={},i=[];return e.forEach(e=>{var{tag:t,value:s}=e;if(t&&-1<t.indexOf(Xc)&&i.push({key:t,value:s}),td.has(t)&&void 0!==s){let e=td.get(t);r[e]=s}}),0<i.length&&(r.profileCustomField=i),r}};let rd=k.common["generateProtocolData"];function id(r){return I(this,void 0,void 0,function*(){let e="profile.portrait_get_all",t={From_Account:g(),UserItem:[]};r.forEach(e=>{t.UserItem.push({CustomSequence:0,StandardSequence:0,To_Account:e})});var n=rd({servcmd:e,data:t}),s=n.head.seq+e,n=yield k.channel.sendPacket(n,{requestId:s});if(n){let{ActionStatus:e,ErrorCode:t,ErrorDisplay:s,ErrorInfo:r,UserProfileItem:i}=n,o=[];return i.map(e=>{var{To_Account:e,CustomSequence:t,ResultCode:s,ResultInfo:r,StandardSequence:i,ProfileItem:n}=e,n=sd.parseProfileItem(n);o.push({userId:e,customSequence:t,resultCode:s,resultInfo:r,standardSequence:i,profileItem:n})}),{actionStatus:e,errorCode:t,errorDisplay:s,errorInfo:r,userProfile:o}}})}function nd(e){return ec.getFriendMap().has(e)}let od=k.utils["isEmpty"];class ad{constructor(){this._strangerProfileMap=new Map}init(){G.getInstance().registerApi({apiName:"getMyProfile",context:this}),G.getInstance().registerApi({apiName:"getUserProfile",context:this}),G.getInstance().registerApi({apiName:"updateMyProfile",context:this}),this.createProfile=sd.createProfile.bind(sd);var e=k["notificationCenter"];h.getInstance().registerWorkflowStep(p.SYNC_SERVER_INFO_AFTER_LOGIN,o.USER_PROFILE_SYNC,this.getMyProfileCacheThenServer,this),e.subscribeInnerEvent(d.MESSAGE_PUSH,e.InnerEventSubType.PROFILE_MODIFIED,this._onProfileDataModify,this),e.subscribeInnerEvent(d.LOGOUT,this._reset,this),e.subscribeInnerEvent(d.DESTROY,this._dispose,this)}getMyProfile(){return I(this,void 0,void 0,function*(){try{var e,t=g(),s=yield id([t]);if(s)return e=this._handleProfileFormResponse(s)[0],ec.getUserProfileMap().set(t,e),{code:0,data:e}}catch(e){var{errorCode:s,errorInfo:t}=e;throw new m({functionName:"getMyProfile",code:s,message:t})}})}getUserProfile(u){return I(this,void 0,void 0,function*(){try{var t=u["userIDList"],{userIdListToRequest:e,profileFromCache:s}=this._filterRequestAndCacheUsers(t);if(0===e.length)return{code:0,data:s,successLog:{message:"userIDList.length:"+t.length}};1e3<e.length&&(k.ssoLog.warn("getUserProfile","userIdListToRequest.length > 1000"),e.length=1e3);var{data:r,error:i}=yield this._batchFetchUserProfiles(e),n=e.length,o=r.length,a=n-o;if(0===s.length&&n===a&&!od(i))throw i;if(ee(r)){r.forEach(e=>{(nd(e.userID)?ec.getUserProfileMap():this._strangerProfileMap).set(e.userID,e)});let e=r.concat(s);return{code:0,data:e,successLog:{message:`getUserProfile query:${n} success:${o} fail:${a} from cache:`+s.length}}}}catch(e){t=e["errorCode"];throw new m({functionName:"getUserProfile",code:t})}})}getMyProfileCacheThenServer(){return I(this,void 0,void 0,function*(){var e=g(),e=ec.getUserProfileMap().has(e);return e?{code:0,data:e}:this.getMyProfile()})}updateMyProfile(a){return I(this,void 0,void 0,function*(){let t=g(),s={};for(let e in a)void 0!==a[e]&&(s[e]=a[e]);var r=sd.convertParamsToProfile(s);try{let e={From_Account:t,ProfileItem:r};yield function(r){return I(this,void 0,void 0,function*(){let e="profile.portrait_set",t=rd({servcmd:e,data:r}),s=""+t.head.seq+e,i=yield k.channel.sendPacket(t,{requestId:s});if(i){let{ActionStatus:e,ErrorCode:t,ErrorDisplay:s,ErrorInfo:r}=i;return{actionStatus:e,errorCode:t,errorDisplay:s,errorInfo:r}}})}(e);var i=ec.getUserProfile(t),n=i?Object.assign(Object.assign({},i),s):sd.createProfile(t,r),o=!Bt(i,n,["lastUpdatedTime"]);return n.lastUpdatedTime=Date.now(),ec.getUserProfileMap().set(t,n),o&&this._emitProfileUpdated(n),{code:0,data:n,successLog:{message:"profileArray: "+k.utils.safeStringify(r)}}}catch(e){let{errorCode:t,errorInfo:s}=e;throw new m({functionName:"updateMyProfile",code:t,message:s})}})}updateMyNickAndAvatar(i){return I(this,void 0,void 0,function*(){var e=g(),t=Date.now(),s=ec.getUserProfile(e),r={};(r=s?Object.assign(s,i):sd.createProfile(e,i)).lastUpdatedTime=t,ec.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:sd.parseProfileList(s)}}();od(t)||({isProfileUpdated:t,profile:e}=this._handleProfileModified(t),t&&this._emitProfileUpdated(e))}_emitProfileUpdated(e){k.notificationCenter.emitInnerEvent(d.PROFILE_UPDATE,{name:d.PROFILE_UPDATE,data:[e]}),k.notificationCenter.emitOuterEvent(jt.PROFILE_UPDATED,{name:jt.PROFILE_UPDATED,data:[e]}),Ql.updateConversation("C2C"+(null==e?void 0:e.userID),{userProfile:e})}_dispose(){var e=k["notificationCenter"];e.unSubscribeInnerEvent(d.LOGOUT,this._reset,this),e.unSubscribeInnerEvent(d.MESSAGE_PUSH,e.InnerEventSubType.PROFILE_MODIFIED,this._onProfileDataModify,this),e.unSubscribeInnerEvent(d.DESTROY,this._dispose,this),this._reset()}_handleProfileModified(e){let{userId:t,profileList:s}=e,r=ec.getUserProfile(t);if(!(g()===t||nd(t)&&r))return{isProfileUpdated:!1,profile:null};let i=sd.normalizeProfileFields(s),n=Object.keys(i).some(e=>e===Zc?!Bt(r.profileCustomField,i.profileCustomField):r[e]!==i[e]);return n?(e=Date.now(),e=Object.assign(Object.assign(Object.assign({},r),i),{lastUpdatedTime:e}),ec.getUserProfileMap().set(t,e),{isProfileUpdated:n,profile:e}):{isProfileUpdated:!1,profile:r}}_filterRequestAndCacheUsers(e){let s=[],r=[];return e.forEach(e=>{var t=ec.getUserProfileMap().has(e);nd(e)&&t?r.push(ec.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&&!od(e.profileItem)),s=Date.now();return t.map(e=>{e=sd.createProfile(e.userId,e.profileItem);return e.lastUpdatedTime=s,e})}_isStrangerAndProfileValid(e){var t;return!nd(e)&&({lastUpdatedTime:e=0}=this._strangerProfileMap.get(e)||{},t=(null==(t=k.store.get("cloudConfig"))?void 0:t.stranger_profile_expiration_time)||6e5,Date.now()-e<=t)}_chunkUserIDList(s,r){return Array.from({length:Math.ceil(s.length/r)},(e,t)=>s.slice(t*r,(t+1)*r))}_batchFetchUserProfiles(e){return I(this,void 0,void 0,function*(){let t=[],r=[],i={};return this._chunkUserIDList(e,100).forEach(e=>{t.push(id(e))}),(yield Promise.allSettled(t)).forEach(s=>{if("fulfilled"===s.status){let e=s.value,t=this._handleProfileFormResponse(e);ee(t)&&r.push(...t)}else if("rejected"===s.status){let{code:e,message:t}=s.reason||{};i={errorCode:e,message:t}}}),{data:r,error:i}})}_reset(){ec.getUserProfileMap().clear(),this._strangerProfileMap.clear()}}var ud,ld,cd,dd=new Map,pd=["0","1","2","3","4","5","6","7","8","9","A","B","C","D","E","F"];for(let e=0,t=pd.length;e<t;e++)dd.set(e,pd[e]);function hd(e){if(!e)return"";var i=String(e).replace(/[=]+$/,"");let n="";if(i.length%4==1)return"";for(let e,t,s=0,r=0;t=i.charAt(r++);~t&&(e=s%4?64*e+t:t,s++%4)&&(n+=String.fromCharCode(255&e>>(-2*s&6))))t="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=".indexOf(t);try{return decodeURIComponent(escape(n))}catch(e){return console.warn(e),""}}let gd=k.utils["isEmpty"],_d=k.common["generateProtocolData"];function md(i){return I(this,void 0,void 0,function*(){var e,t,s="im_open_status.ws_get_user_status",r=_d({servcmd:s,data:{To_Account:i}}),s=r.head.seq+s,r=yield k.channel.sendPacket(r,{requestId:s});if(r)return{ErrorCode:s,ErrorInfo:r,ErrorList:e=[],UserStatusList:t=[]}=r,{errorCode:s,errorInfo:r,successUserList:t.map(e=>{var{To_Account:e,Status:t,CustomStatus:s}=e;return{userID:e,statusType:t,customStatus:hd(s)}}),failureUserList:e.map(e=>{var{To_Account:e,Invalid_Account:t,ErrorCode:s,ErrorInfo:r}=e;return{userID:gd(t)?e:t,code:s,message:r}})}})}class vd{constructor(){this._customStatus=""}init(){var e=k["notificationCenter"];G.getInstance().registerApi({apiName:"getUserStatus",context:this}),G.getInstance().registerApi({apiName:"setSelfStatus",context:this}),G.getInstance().registerApi({apiName:"subscribeUserStatus",context:this}),G.getInstance().registerApi({apiName:"unsubscribeUserStatus",context:this}),h.getInstance().registerWorkflowStep(p.SYNC_SERVER_INFO_AFTER_RE_ONLINE,o.USER_STATUS_UPDATE,this._onReOnline,this),e.subscribeInnerEvent(d.MESSAGE_PUSH,e.InnerEventSubType.USER_STATUS_UPDATE,this._onUserStatusUpdate,this),e.subscribeInnerEvent(d.LOGOUT,this._reset,this),e.subscribeInnerEvent(d.DESTROY,this._dispose,this)}setSelfStatus(s){return I(this,void 0,void 0,function*(){let e=g(),t=s["customStatus"];try{return yield function(i){return I(this,void 0,void 0,function*(){let e="im_open_status.ws_set_custom_status",t=_d({servcmd:e,data:{CustomStatus:i}}),s=""+t.head.seq+e,r=yield k.channel.sendPacket(t,{requestId:s});if(r){let{ErrorCode:e,ErrorInfo:t}=r;return{errorCode:e,errorInfo:t}}})}(t),this._customStatus=t,{code:0,data:{userID:e,statusType:1,customStatus:t},successLog:{message:"customStatus: "+t}}}catch(e){let{errorCode:t,errorInfo:s}=e;throw new m({functionName:"setSelfStatus",code:t,message:s})}})}getUserStatus(s){return I(this,void 0,void 0,function*(){var{userIDList:e=[]}=s;let t={};return this._isOnlyMeInArray(e)&&(t=this._getMyStatus()),t=yield this._getUserStatus(e),Object.assign(Object.assign({},t),{successLog:{message:"userIDList length: "+e.length}})})}setCustomStatus(e){e=hd(e);this._customStatus=e}subscribeUserStatus(i){return I(this,void 0,void 0,function*(){try{var{userIDList:e=[]}=i,t=(this._checkBusinessCapabilityBits("subscribeUserStatus"),this._getMaxUserCount("subscribe")),s=yield function(r){return I(this,void 0,void 0,function*(){var e=k["channel"],t="im_open_status.ws_status_subscribe",s=_d({servcmd:t,data:{To_Account:r}}),t=s.head.seq+t;return yield e.sendPacket(s,{requestId:t})})}(this._sliceUserIDList(e,t)),r=this._parseResponse(s);return{code:0,data:{failureUserList:r},successLog:{message:`userID length:${e.length} failCount: `+r.length}}}catch(e){t=e["errorCode"];throw new m({functionName:"subscribeUserStatus",code:t})}})}unsubscribeUserStatus(i){return I(this,void 0,void 0,function*(){try{this._checkBusinessCapabilityBits("unsubscribeUserStatus");var{userIDList:e=[]}=i,t=this._getMaxUserCount("unsubscribe"),s=yield function(r){return I(this,void 0,void 0,function*(){var e=k["channel"],t="im_open_status.ws_status_unsubscribe",s=0===r.length?{UnsubscribeAll:1}:{To_Account:r},s=_d({servcmd:t,data:s}),t=s.head.seq+t;return yield e.sendPacket(s,{requestId:t})})}(this._sliceUserIDList(e,t)),r=this._parseResponse(s);return{code:0,data:{failureUserList:r},successLog:{message:`userID length:${e.length} failCount: `+r.length}}}catch(e){t=e["errorCode"];throw new m({functionName:"unsubscribeUserStatus",code:t})}})}_onUserStatusUpdate(e){var{UserStatusList:e=[]}=e||{},e=e.map(e=>{var{To_Account:e,Status:t,CustomStatus:s}=e;return{userID:e,statusType:t,customStatus:hd(s)}});this._emitUserStatusUpdatedEvent(e)}_onReOnline(e){var e=hd(e.data.customStatus);this._customStatus!==e&&(this._customStatus=e,e={userID:g(),statusType:1,customStatus:e},this._emitUserStatusUpdatedEvent(e))}_emitUserStatusUpdatedEvent(e){k.notificationCenter.emitOuterEvent(jt.USER_STATUS_UPDATED,{name:jt.USER_STATUS_UPDATED,data:e})}_sliceUserIDList(e,t){return e.slice(0,t)}_parseResponse(e){var{ErrorList:e=[]}=e;return e.map(e=>{var{To_Account:e,Invalid_Account:t,ErrorCode:s,ErrorInfo:r}=e;return{userID:k.utils.isEmpty(t)?e:t,code:s,message:r}})}_checkBusinessCapabilityBits(e){if(!k.store.get("commercialConfig").get("USER_STATUS"))throw new m({functionName:e,code:as.NO_USE,replacement1:e})}_getMaxUserCount(e){var t=k.store.get("cloudConfig")||{},{key:e,default:s}={query:{key:"status_query_count",default:500},subscribe:{key:"status_sub_count",default:100},unsubscribe:{key:"status_unsub_count",default:100}}[e],t=t[e]||s;return parseInt(t,10)}_getMyStatus(){return{code:0,data:{successUserList:[{userID:g(),statusType:1,customStatus:this._customStatus}],failureUserList:[]}}}_getUserStatus(r){return I(this,void 0,void 0,function*(){try{this._checkBusinessCapabilityBits("getUserStatus");var t=this._getMaxUserCount("query"),{successUserList:e,failureUserList:s}=(yield md(this._sliceUserIDList(r,t)))||{};return{code:0,data:{successUserList:e,failureUserList:s}}}catch(e){t=e["errorCode"];throw new m({functionName:"getUserStatus",code:t})}})}_isOnlyMeInArray(e){var t=g();return 1===e.length&&-1<e.indexOf(t)}_dispose(){var e=k["notificationCenter"];e.unSubscribeInnerEvent(d.MESSAGE_PUSH,e.InnerEventSubType.USER_STATUS_UPDATE,this._onUserStatusUpdate,this),e.unSubscribeInnerEvent(d.DESTROY,this._dispose,this),e.unSubscribeInnerEvent(d.LOGOUT,this._reset,this),this._reset()}_reset(){this._customStatus=""}}let fd={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(Xc))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}}},Id={getMyProfile:!0,getUserProfile:!0,updateMyProfile:!0,setSelfStatus:!0,getUserStatus:!0,subscribeUserStatus:!0,unsubscribeUserStatus:!0};class Ed{constructor(){this.userProfile=new ad,this.userStatus=new vd,this.userProfile.init(),this.userStatus.init(),ks({auth:Id,params:fd})}}function Cd(t){var s=[];if(X(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}(e=ud=ud||{}).NOT_START="notStart",e.PENDING="pending",e.RESOLVED="resolved",e.REJECTED="rejected",(_=ld=ld||{})[_.C2C=1]="C2C",_[_.GROUP=2]="GROUP",(n=cd=cd||{})[n.C2C=8]="C2C",n[n.GROUP=2]="GROUP";class Sd{constructor(){this._name="SyncConversationHandler",this._pagingStatus=ud.NOT_START,this._pagingTimeStamp=0,this._pagingStartIndex=0,this._pagingPinnedTimeStamp=0,this._pagingPinnedStartIndex=0}init(){var e=k["notificationCenter"];h.getInstance().registerWorkflowStep(p.SYNC_SERVER_INFO_AFTER_RE_ONLINE,o.CONVERSATION_RECOVER,this._syncConversationList,this),h.getInstance().registerWorkflowStep(p.SYNC_SERVER_INFO_AFTER_LOGIN,o.CONVERSATION_LIST_SYNC,this._syncConversationListAfterLogin,this),e.subscribeInnerEvent(d.LOGOUT,this._reset,this),e.subscribeInnerEvent(d.DESTROY,this._dispose,this),k.ssoLog.debug(this._name+".init")}isSyncCompleted(){return this._pagingStatus===ud.RESOLVED}_syncConversationListAfterLogin(){return I(this,void 0,void 0,function*(){return this._pagingStatus=ud.NOT_START,this._pagingTimeStamp=0,this._pagingStartIndex=0,this._pagingPinnedTimeStamp=0,this._pagingPinnedStartIndex=0,this._syncConversationList()})}_syncConversationList(){return I(this,void 0,void 0,function*(){let{ssoLog:t,utils:{safeStringify:s}}=k;t.debug("_syncConversationList","start");try{let e=yield this._pagingGetConversationList(!0);this._pagingStatus=ud.RESOLVED;var{conversationList:r=[]}=e||{};return t.info("_syncConversationList","success count:"+r.length),e}catch(e){var{errorCode:r,errorInfo:i}=e,r=new m({code:r,message:i});t.error("_syncConversationList","fail "+s(e),{error:r})}})}_pagingGetConversationList(c){return I(this,void 0,void 0,function*(){try{var e,t=[],s=(this._pagingStatus=ud.PENDING,yield function(n){return I(this,void 0,void 0,function*(){var{fromAccount:e,pagingTimeStamp:t,pagingStartIndex:s,pagingPinnedTimeStamp:r,pagingPinnedStartIndex:i}=n;return Ks({servcmd:"recentcontact.page_get",data:{AssistFlags:31,MsgAssistFlags:15,OrderType:1,From_Account:e,StartIndex:s,TimeStamp:t,TopStartIndex:i,TopTimeStamp:r}})})}({fromAccount:g(),pagingTimeStamp:c?this._pagingTimeStamp:0,pagingStartIndex:c?this._pagingStartIndex:0,pagingPinnedTimeStamp:c?this._pagingPinnedTimeStamp:0,pagingPinnedStartIndex:c?this._pagingPinnedStartIndex:0})),{CompleteFlag:r,SessionItem:i=[],TimeStamp:n,StartIndex:o,TopTimeStamp:a,TopStartIndex:u}=s||{};if(0<i.length){let e=this._getConversationOptions(i);t.push(...e);var l=k["notificationCenter"];l.emitInnerEvent(d.SYNC_CONVERSATION_LIST,{conversationUpdateFieldList:e})}return this._pagingTimeStamp=n,this._pagingStartIndex=o,this._pagingPinnedTimeStamp=a,this._pagingPinnedStartIndex=u,1!==r&&(e=(yield this._pagingGetConversationList(c))["conversationList"],t.push(...e)),{conversationList:t}}catch(e){throw e}})}_getConversationOptions(e){let{isUndefined:t}=k["utils"],s=this._convertConversationKey(e);return this._filterValidConversations(s).map(e=>(t(e.lastMsg)&&(e.lastMsg={elements:[]}),e.type===ld.C2C?this._assembleC2COption(e):this._assembleGroupOption(e)))}_filterValidConversations(e){return e.filter(({type:e,userID:t})=>e===ld.C2C&&!function(e){let t;return"@TLS#ERROR"===(t=e.startsWith(S.CONV_C2C)?e.replace(S.CONV_C2C,""):t)||"@TLS#NOT_FOUND"===t}(t)||2===e)}_assembleC2COption(e){var t,s=this._createUserprofile(e);return{conversationID:""+S.CONV_C2C+e.userID,type:S.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===cd.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:Cd(e.standardMark),conversationGroupList:[],remark:e.friendRemark||"",messageRemindType:this._transMsgRemindType(e.messageRemindType)}}_createUserprofile(e){var{userID:e,nick:t,peerAvatar:s}=e,t=[{tag:"Tag_Profile_IM_Nick",value:t},{tag:"Tag_Profile_IM_Image",value:s}];return null==(s=k.user.userProfile)?void 0:s.createProfile(e,t)}_computeIsPeerRead(e){var{lastC2CMsgFromAccount:e,time:t,c2cPeerReadTime:s}=e;return e===g()&&t<=s}_assembleGroupOption(e){var t;return{conversationID:""+S.CONV_GROUP+e.groupID,type:S.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===cd.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:Cd(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(s){var e,t,r=k["utils"]["isEmpty"];if(r(s))return null;let i="",n=null;if(!r(s.GroupTips)){let{From_Account:e,GroupName:t}=(null==(r=s.GroupTips)?void 0:r.GroupInfo)||{};i=S.MSG_GRP_TIP,n=Object.assign(Object.assign({},this._parseContent(i,s.GroupTips.MsgBody)),{groupProfile:{from:e,groupName:t}})}return s.MsgBody&&(i=null==(e=s.MsgBody[0])?void 0:e.MsgType,n=this._parseContent(i,s.MsgBody[0])),{event:s.Event,elements:[{type:i,content:n,cloudCustomData:s.CloudCustomData}],revokerInfo:{revoker:null==(t=s.RevokerInfo)?void 0:t.revoker}}}_parseContent(e,t){return t&&((e=k.message.messageFactory.getElementClass(e))?null==(e=e.parseServerPushElement(t))?void 0:e.content:t)}_amendLayersOverLimitProp(e){var t=e["LayersOverLimit"];return f(e,["LayersOverLimit"]).layersOverLimit=1===t,e}_transMsgRemindType(e){let t="";return 0===e?t=S.MSG_REMIND_ACPT_AND_NOTE:1===e?t=S.MSG_REMIND_DISCARD:2===e?t=S.MSG_REMIND_ACPT_NOT_NOTE:3===e&&(t=S.NOT_RECEIVE_OFFLINE_PUSH_EXCEPT_AT),t}_patchTypeAndPayload(e){var t=k["utils"]["isUndefined"],{event:e,elements:s=[]}=e.lastMsg||{};return t(e)?{type:s[0]?s[0].type:null,payload:s[0]?this._amendLayersOverLimitProp(s[0].content):null}:{type:S.MSG_GRP_TIP,payload:(null==(t=null==s?void 0:s[0])?void 0:t.content)||{}}}_computeGroupUnreadCount(e){var{unreadCount:e=0,noUnreadCount:t=0}=e,e=e-t;return 0<e?e:0}_reset(){this._pagingStatus=ud.NOT_START,this._pagingTimeStamp=0,this._pagingStartIndex=0,this._pagingPinnedTimeStamp=0,this._pagingPinnedStartIndex=0}_dispose(){this._reset();var e=k["notificationCenter"];e.unSubscribeInnerEvent(d.LOGOUT,this._reset,this),e.unSubscribeInnerEvent(d.DESTROY,this._dispose,this)}}class Md{constructor(){this.syncConversationHandler=new Sd,this.syncConversationHandler.init()}}return console.log("TencentCloudLiteChat.VERSION:1.6.0"),{create:function(e){var{SDKAppID:e,testEnv:t=!1,devMode:s=!1,unlimitedAVChatRoom:r=!1,scene:i="",oversea:n=!1,instance:o,disableIndependentDomain:a=!1}=e,u=e;if("number"!=typeof u&&(e=Number(u),Number.isNaN(e)))return console.error("Create SDK instance failed. Failed to parse the SDKAppID, please check the arguments"),null;if(u=Number(u),qs.has(u))return qs.get(u);let l=null;if(o)(l=o)._workflowManager&&h.setInstance(l._workflowManager),l._pluginManager&&l._pluginManager.installBuiltInPlugin(Wl),!o.isReady()||null!=(o=(e=h.getInstance()).executeWorkflow)&&o.call(e,p.SYNC_SERVER_INFO_AFTER_LOGIN);else{let e=""+(c()+c())+c()+c()+c()+c()+c()+c();k.init({sdkAppId:u,instanceId:e,testEnv:t,devMode:s,unlimitedAVChatRoom:r,disableIndependentDomain:a,scene:i,oversea:n,sdkEdition:Kl}),h.getInstance().init(),k.message=new zc,k.user=new Ed,k.login=new nc,k.conversation=new Md,Yl.getInstance().installBuiltInPlugin(Wl),(l=G.getInstance().exposeApiForClient())._workflowManager=h.getInstance(),l._pluginManager=Yl.getInstance()}function c(){return(65536*(1+Math.random())|0).toString(16).substring(1)}return qs.set(u,l),l},TSignaling:Ht,EVENT:jt,VERSION:lt,TYPES:S}});
1
+ !function(e,t){"object"==typeof exports&&"undefined"!=typeof module?module.exports=t():"function"==typeof define&&define.amd?define(t):(e="undefined"!=typeof globalThis?globalThis:e||self).TencentCloudChat=t()}(this,function(){class P{constructor(){this.listeners={}}on(e,t,s){this.listeners[e]||(this.listeners[e]=[]),this.listeners[e].push({fn:t,context:s})}off(e,s,r){s&&(this.listeners[e]=null==(e=this.listeners[e])?void 0:e.filter(e=>{var t=e.fn===s,e=!r||e.context===r;return!(t&&e)}))}emit(e,...s){e=this.listeners[e];e&&e.forEach(e=>{var{fn:e,context:t}=e;e.apply(t,s)})}once(t,s,r){let i=(...e)=>{s.apply(r,e),this.off(t,i)};this.on(t,i)}}let w={ANDROID:2,IOS:3,MAC:4,WEB:7,WX_MP:8,QQ_MP:9,TT_MP:10,BAIDU_MP:11,ALI_MP:12,IPAD:13,UNI_NATIVE_APP:15,DONUT_NATIVE_APP:19,NS_NATIVE_APP:20,RN_NATIVE_APP:21},U=["heartbeat.alive","im_open_status.wslogin","im_open_status.wslogout","group_open_long_polling_http_svc.get_msg","group_open_long_polling_http_noauth_svc.get_msg"];var i,q;(e=i=i||{})[e.DEBUG=0]="DEBUG",e[e.INFO=1]="INFO",e[e.WARN=2]="WARN",e[e.ERROR=3]="ERROR",e[e.NONE=4]="NONE";let x="LiteChat",V={[i.DEBUG]:console.debug,[i.INFO]:console.info,[i.WARN]:console.warn,[i.ERROR]:console.error},B={[i.INFO]:4,[i.WARN]:5,[i.ERROR]:6};(e=q=q||{})[e.CONV_DELETED=1]="CONV_DELETED",e[e.CONV_PINED=2]="CONV_PINED",e[e.CONV_UNPINED=3]="CONV_UNPINED",e[e.CONV_MARK_UPDATED=4]="CONV_MARK_UPDATED",e[e.CONV_GROUP_ADDED=5]="CONV_GROUP_ADDED",e[e.CONV_GROUP_DELETED=6]="CONV_GROUP_DELETED",e[e.CONV_GROUP_UPDATED=7]="CONV_GROUP_UPDATED";var r,j,K,e=Object.freeze({__proto__:null,CONSOLE_METHOD:V,CloudConfigReportLevelMap:B,get ConvModifyPushType(){return q},DEFAULT_GLOBAL_MAX_TOTAL_COUNT:50,DEFAULT_GLOBAL_THROTTLE_TIME:5e3,DEFAULT_SINGLE_MAX_TOTAL_COUNT:2,DEFAULT_SINGLE_THROTTLE_TIME:1e3,ENUM_PLATFORM:w,IS_TOPIC_MESSAGE:2,get LogLevel(){return i},NOT_NEED_CRC_SERVCMD:U,SDK_NAME:x});(t=r=r||{}).BUSINESS_COMMAND="business_command",t.C2C_REALTIME_MESSAGE="c2c_realtime_message",t.C2C_MESSAGE_MODIFIED="c2c_message_modified",t.C2C_REVOKED_MESSAGE="c2c_message_revoked",t.GROUP_REALTIME_MESSAGE="group_realtime_message",t.GROUP_MESSAGE_MODIFIED="group_message_modified",t.GROUP_MESSAGE_REVOKED="group_message_revoked",t.C2C_MESSAGE_READ_RECEIPT="c2c_message_read_receipt",t.MESSAGE_REACTION_UPDATED="message_reaction_updated",t.MESSAGE_REACTION_UPDATED_SYNC="message_reaction_updated_sync",t.GROUP_AT_TIPS="group_at_tips",t.USER_STATUS_UPDATE="user_status_update",t.FRIEND_LIST_MODIFIED="friend_list_modified",t.PROFILE_MODIFIED="profile_modified",t.CONV_MODIFIED="conversation_modified",t.GROUP_TIPS_NOTIFICATION="group_tips_notification",t.GROUP_MESSAGE_READ_RECEIPT="group_message_read_receipt",t.GROUP_MESSAGE_READ_SYNC="group_message_read_sync",t.GROUP_SYSTEM_NOTIFICATION="group_system_notification",t.C2C_MESSAGE_PEER_READ="c2c_message_peer_read",t.C2C_MESSAGE_READ_SYNC="c2c_message_read_sync",t.C2C_REMIND_TYPE_SYNC="c2c_remind_type_sync",t.FOLLOW_LIST_UPDATED="follow_list_updated",t.MESSAGE_EXTENSIONS_UPDATED="message_extensions_updated",t.ALL_MESSAGE_READ="all_message_read",t.CONVERSATION_MARK_UPDATED="conversation_mark_updated",t.CONVERSATION_GROUP_ADD="conversation_group_add",t.CONVERSATION_GROUP_DELETED="conversation_group_deleted",t.CONVERSATION_GROUP_UPDATED="conversation_group_updated",t.ALL_RECEIVE_MESSAGE_OPTION="all_receive_message_option",t.TOPIC_AT_TIPS="topic_at_tips",t.TOPIC_TIPS_NOTIFICATION="topic_tips_notification",t.TOPIC_SYSTEM_NOTIFICATION="topic_system_notification",t.TOPIC_MESSAGE_READ_SYNC="topic_message_read_sync",t.TOPIC_LATEST_MESSAGE="topic_latest_message",t.GROUP_MESSAGE_PINNED="group_message_pinned";let W=[16,17];function H(e){let t,s=[];return null!=(t=null==e?void 0:e.GroupTips)&&t.forEach(e=>{2===e.GroupInfo.MillionGroupFlag?s.push(r.TOPIC_TIPS_NOTIFICATION):W.includes(null==(e=null==e?void 0:e.MsgBody)?void 0:e.OpType)?s.push(r.GROUP_MESSAGE_PINNED):s.push(r.GROUP_TIPS_NOTIFICATION)}),s}let Y=[{conditions:[{type:"event",value:100}],subType:r.BUSINESS_COMMAND},{conditions:[{type:"event",value:24}],subType:r.ALL_RECEIVE_MESSAGE_OPTION},{conditions:[{type:"event",value:26}],subType:r.TOPIC_LATEST_MESSAGE},{conditions:[{type:"hasKey",value:"C2cMsgArray"}],subType:r.C2C_REALTIME_MESSAGE},{conditions:[{type:"hasKey",value:"C2cMsgModNotifys"}],subType:r.C2C_MESSAGE_MODIFIED},{conditions:[{type:"hasKey",value:"ProfileDataMod"}],subType:r.PROFILE_MODIFIED},{conditions:[{type:"hasKey",value:"UserStatusList"}],subType:r.USER_STATUS_UPDATE},{conditions:[{type:"hasKey",value:"FriendListMod"}],subType:r.FRIEND_LIST_MODIFIED},{conditions:[{type:"hasKey",value:"GroupMsgArray"}],subType:r.GROUP_REALTIME_MESSAGE},{conditions:[{type:"hasKey",value:"GroupMsgModNotifys"}],subType:r.GROUP_MESSAGE_MODIFIED},{conditions:[{type:"hasKey",value:"C2cNotifyMsgArray"}],subTypeParser:function(e){let t,s=[];return null!=(t=null==e?void 0:e.C2cNotifyMsgArray)&&t.forEach(e=>{e.WithdrawC2cMsgNotify&&s.push(r.C2C_REVOKED_MESSAGE),e.C2cReadedReceipt&&s.push(r.C2C_MESSAGE_PEER_READ),e.ReadC2cMsgNotify&&s.push(r.C2C_MESSAGE_READ_SYNC),e.MuteNotificationsSync&&s.push(r.C2C_REMIND_TYPE_SYNC)}),s}},{conditions:[{type:"hasKey",value:"GroupTips"},{type:"event",value:4}],subTypeParser:H},{conditions:[{type:"hasKey",value:"GroupTips"},{type:"event",value:5}],subTypeParser:function(e){let t,s=[];return null!=(t=null==e?void 0:e.GroupTips)&&t.forEach(e=>{Array.isArray(e.MsgBody.GroupWithdrawInfoArray)?s.push(r.GROUP_MESSAGE_REVOKED):Array.isArray(e.MsgBody.GroupMsgReceiptList)?s.push(r.GROUP_MESSAGE_READ_RECEIPT):Array.isArray(e.MsgBody.GroupReadInfoArray)?e.MsgBody.GroupReadInfoArray[0].TopicId?s.push(r.TOPIC_MESSAGE_READ_SYNC):s.push(r.GROUP_MESSAGE_READ_SYNC):2===e.GroupInfo.MillionGroupFlag?s.push(r.TOPIC_SYSTEM_NOTIFICATION):s.push(r.GROUP_SYSTEM_NOTIFICATION)}),s}},{conditions:[{type:"hasKey",value:"GroupTips"},{type:"event",value:6}],subTypeParser:H},{conditions:[{type:"hasKey",value:"GroupTips"},{type:"event",value:12}],subTypeParser:function(e){let t,s=[];return null!=(t=null==e?void 0:e.GroupTips)&&t.forEach(e=>{var e=e["GroupAtTips"]["TopicId"];e?s.push(r.TOPIC_AT_TIPS):s.push(r.GROUP_AT_TIPS)}),s}},{conditions:[{type:"hasKey",value:"RecentContactMod"}],subTypeParser:function(e){let t,s=[];return null!=(t=null==e?void 0:e.RecentContactMod)&&t.forEach(e=>{switch(e.PushType){case q.CONV_MARK_UPDATED:s.push(r.CONVERSATION_MARK_UPDATED);break;case q.CONV_GROUP_ADDED:s.push(r.CONVERSATION_GROUP_ADD);break;case q.CONV_GROUP_DELETED:s.push(r.CONVERSATION_GROUP_DELETED);break;case q.CONV_GROUP_UPDATED:s.push(r.CONVERSATION_GROUP_UPDATED);break;default:s.push(r.CONV_MODIFIED)}}),s}},{conditions:[{type:"hasKey",value:"MsgReactionNotifyList"}],subType:r.MESSAGE_REACTION_UPDATED},{conditions:[{type:"hasKey",value:"MsgReactionNotify"}],subType:r.MESSAGE_REACTION_UPDATED_SYNC},{conditions:[{type:"hasKey",value:"C2cMsgInfo"}],subType:r.C2C_MESSAGE_READ_RECEIPT},{conditions:[{type:"hasKey",value:"FollowChangeList"}],subType:r.FOLLOW_LIST_UPDATED},{conditions:[{type:"hasKey",value:"MsgExtensionNotify"}],subType:r.MESSAGE_EXTENSIONS_UPDATED},{conditions:[{type:"hasKey",value:"C2CReadAllMsg"}],subType:r.ALL_MESSAGE_READ}];function $(r){let e,t=Array.isArray(null==(e=null==r?void 0:r.body)?void 0:e.EventArray)?r.body.EventArray:[],i=[];return t.forEach(t=>{t.Flag=r.body.Flag;var e=Y.find(e=>e.conditions.every(e=>{switch(e.type){case"event":return t.Event===e.value;case"hasKey":return Object.prototype.hasOwnProperty.call(t,e.value);default:return!1}}));if(!e)return null;let s=[];"function"==typeof e.subTypeParser?s=e.subTypeParser(t):e.subType&&(s=e.subType),Array.isArray(s)?s.forEach(e=>{i.push({type:j.SERVER_PUSH_MESSAGE+":"+e,data:t})}):i.push({type:j.SERVER_PUSH_MESSAGE+":"+s,data:t})}),i}(t=j=j||{}).SERVER_PUSH_MESSAGE="im_open_push.msg_push",t.SERVER_PUSH_MESSAGE_MULTIPLE="im_open_push.multi_msg_push_ws",t.ERROR="error";let z={[j.SERVER_PUSH_MESSAGE]:$,[j.SERVER_PUSH_MESSAGE_MULTIPLE]:$,[j.ERROR]:function(e){var t=e["errorCode"];return[{type:"error:"+t,data:e}]}},J=new class{constructor(){this._outerEventEmitter=null,this._innerEventEmitter=null,this._outerEventEmitter=new P,this._innerEventEmitter=new P,this.InnerEventSubType=r}subscribeInnerEvent(s,r,i,n){var o,t;if(["string","number"].includes(typeof r)){let e=r,t=i;null!=(o=this._innerEventEmitter)&&o.on(s+":"+e,t,n)}else{let e=r;null!=(t=this._innerEventEmitter)&&t.on(s,e,i)}}emitInnerEvent(t,s){var e;if(null!=(e=this._innerEventEmitter)&&e.emit(t,s),Object.keys(z).includes(t)){let e=null==(t=z[t])?void 0:t.call(z,s);null!=e&&e.forEach(e=>{var t;e&&null!=(t=this._innerEventEmitter)&&t.emit(e.type,e.data)})}}unSubscribeInnerEvent(s,r,i,n){var o,t;if(["string","number"].includes(typeof r)){let e=r,t=i;null!=(o=this._innerEventEmitter)&&o.off(s+":"+e,t,n)}else{let e=r;null!=(t=this._innerEventEmitter)&&t.off(s,e,i)}}subscribeOuterEvent(e,t,s){var r;null!=(r=this._outerEventEmitter)&&r.on(e,t,s)}unSubscribeOuterEvent(e,t,s){var r;null!=(r=this._outerEventEmitter)&&r.off(e,t,s)}emitOuterEvent(e,t){var s;null!=(s=this._outerEventEmitter)&&s.emit(e,t)}getOuterEventEmitter(){return this._outerEventEmitter}rest(){this._outerEventEmitter=null,this._innerEventEmitter=null}};function f(e,t){var s={};for(i in e)Object.prototype.hasOwnProperty.call(e,i)&&t.indexOf(i)<0&&(s[i]=e[i]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols)for(var r=0,i=Object.getOwnPropertySymbols(e);r<i.length;r++)t.indexOf(i[r])<0&&Object.prototype.propertyIsEnumerable.call(e,i[r])&&(s[i[r]]=e[i[r]]);return s}function I(e,o,a,u){return new(a=a||Promise)(function(s,t){function r(e){try{n(u.next(e))}catch(e){t(e)}}function i(e){try{n(u.throw(e))}catch(e){t(e)}}function n(e){var t;e.done?s(e.value):((t=e.value)instanceof a?t:new a(function(e){e(t)})).then(r,i)}n((u=u.apply(e,o||[])).next())})}let Q=e=>void 0===e,X=e=>"string"==typeof e,Z=e=>{return null==(e=Object.prototype.toString.call(e).match(/^\[object (.*)\]$/))?void 0:e[1].toLowerCase()},ee=e=>"function"==typeof Array.isArray?Array.isArray(e):"array"===Z(e),te=e=>null!==e&&"object"==typeof e,se=e=>ee(e)||te(e),re=e=>{return"string"==typeof e&&(e=e[0],!/[^a-zA-Z0-9]/.test(e))},ie=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 ne(e=99999999){return Math.round(Math.random()*e)}let oe=(s,r,i,n)=>{if(!se(s)||!se(r))return 0;let o=0;var a,u=Object.keys(r);for(let e=0,t=u.length;e<t;e++)if(a=u[e],!(Q(r[a])||i&&i.includes(a)))if(se(s[a])&&se(r[a]))o+=oe(s[a],r[a],i,n);else{if(n&&n.includes(r[a]))continue;s[a]!==r[a]&&(s[a]=r[a],o+=1)}return o};function ae(s){let r,i,n=s,o="";for(let e=0,t=(n=s.length%8!=0?"0".repeat(8-s.length%8)+s:n)["length"];e<t;e+=8)r=parseInt(n.slice(e,e+4),2),i=parseInt(n.slice(e+4,e+8),2),o+=base16Map.get(r)+base16Map.get(i);return o}let ue="undefined"!=typeof wx&&"function"==typeof wx.getSystemInfoSync&&("mac"===wx.getSystemInfoSync().platform||"windows"===wx.getSystemInfoSync().platform),le="undefined"!=typeof wx&&"function"==typeof wx.getSystemInfoSync&&Boolean(wx.getSystemInfoSync().fontSizeSetting)||ue,ce=le&&"function"==typeof wx.createGamePortal,de="undefined"!=typeof qq&&"function"==typeof qq.getSystemInfoSync&&Boolean(qq.getSystemInfoSync().fontSizeSetting),pe="undefined"!=typeof tt&&"function"==typeof tt.getSystemInfoSync&&Boolean(tt.getSystemInfoSync().fontSizeSetting),he="undefined"!=typeof swan&&"function"==typeof swan.getSystemInfoSync&&Boolean(swan.getSystemInfoSync().fontSizeSetting),ge="undefined"!=typeof my&&"function"==typeof my.getSystemInfoSync&&Boolean(my.getSystemInfoSync().fontSizeSetting),_e="undefined"!=typeof jd&&"function"==typeof jd.getSystemInfoSync,me="undefined"!=typeof uni&&"undefined"==typeof window&&"function"==typeof uni.requireNativePlugin,ve=le&&"object"==typeof wx.miniapp,fe="undefined"!=typeof uni,Ie=le||de||pe||he||ge||me||_e,Ee="undefined"==typeof window&&!Ie&&"undefined"!=typeof global&&void 0!==global.NativeScriptGlobals,Ce="undefined"!=typeof global&&(void 0!==global.nativeModuleProxy||void 0!==global.ReactNative),Se="undefined"!=typeof wx&&"function"==typeof wx.getAccountInfoSync&&Boolean(wx.getAccountInfoSync().plugin),Me="undefined"!=typeof uni?!Ie:"undefined"!=typeof window&&!Ie&&!Ce,ye=de?qq:pe?tt:he?swan:ge?my:le?wx:me?uni:_e?jd:{},s=Me&&window&&window.navigator&&window.navigator.userAgent||"",Te=/(micromessenger|webbrowser)/i.test(s),Ae=function(){let e="WEB";return Te?e="WEB":de?e="QQ_MP":pe?e="TT_MP":he?e="BAIDU_MP":ge?e="ALI_MP":le?e=ve?"DONUT_NATIVE_APP":"WX_MP":me?e="UNI_NATIVE_APP":Ee?e="NS_NATIVE_APP":Ce&&(e="RN_NATIVE_APP"),w[e]}(),Oe=/iPad/i.test(s),De=/iPhone/i.test(s)&&!Oe,Re=/iPod/i.test(s),Le=De||Oe||Re,Ne=(t=s.match(/OS (\d+)_/i))&&t[1]?t[1]:null,be=/Android/i.test(s),Ge=(t=s.match(/Android (\d+)(?:\.(\d+))?(?:\.(\d+))*/i))?(it=t[1]&&parseFloat(t[1]),K=t[2]&&parseFloat(t[2]),it&&K?parseFloat(t[1]+"."+t[2]):it||null):null,Pe=/Firefox/i.test(s),we=/Edge/i.test(s),Ue=!we&&/Chrome/i.test(s),ke=/MSIE/.test(s)||-1<s.indexOf("Trident")&&-1<s.indexOf("rv:11.0"),Fe=function(){var e=/MSIE\s(\d+)\.\d/.exec(s);let t=e&&parseFloat(e[1]);return t=!t&&/Trident\/7.0/i.test(s)&&/rv:11.0/.test(s)?11:t}(),qe=/Safari/i.test(s)&&!Ue&&!be&&!we,xe=/Windows/i.test(s),Ve=/MAC OS X/i.test(s),Be=Me&&"undefined"!=typeof Worker&&!ke,je=be||Le,Ke=Me&&void 0!==window.tencent_cloud_im_csig_flutter_for_web_25F_cy,We="undefined"!=typeof window&&void 0!==window.navigator&&(K=window.navigator["standalone"],!(!Le||K||qe));function He(){let e="unknown";if(Ve&&(e="mac"),xe&&(e="windows"),Le&&(e="ios"),be&&(e="android"),Ie)try{var t=ye.getSystemInfoSync()["platform"];void 0!==t&&(e=t)}catch(e){console.error(e)}return e}let Ye="application/x-www-form-urlencoded;charset=UTF-8";function $e(e){return I(this,arguments,void 0,function*({method:i,url:n,data:o,timeout:a=3e3}){return new Promise(Ie?(t,e)=>{ye.request({url:n,data:o,method:i,timeout:a,header:{"content-type":Ye},success:e=>t(e.data),fail:()=>e(new Error('{"message":"Network error","code":2800}'))})}:(t,e)=>{let s=new XMLHttpRequest,r=setTimeout(()=>{s.abort(),e(new Error('{"message":"Request timeout","code":2801}'))},a);s.onreadystatechange=function(){if(4===s.readyState)if(clearTimeout(r),200===s.status||304===s.status)try{t(s.responseText?JSON.parse(s.responseText):null)}catch(e){t(s.responseText)}else e(new Error('{"message":"Network error","code":2800}'))},s.open(i,n,!0),s.setRequestHeader("Content-type",Ye),s.send(o||null)})})}function ze(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(ie(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 Je(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(Je(t),Je(e))}),s}if(r instanceof Set){let t=new Set;return r.forEach(e=>{t.add(Je(e))}),t}if(Array.isArray(r))return r.map(e=>Je(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]=Je(r[e]))}),s}function Qe(e,s,t){let r=new WeakSet;try{return JSON.stringify(e,(e,t)=>{if(void 0===(t=s?s(e,t):t))return"undefined";if(null===t)return null;if(Number.isNaN(t))return"NaN";if(t===1/0)return"Infinity";if(t===-1/0)return"-Infinity";if("function"==typeof t)return`[Function: ${t.name||"anonymous"}]`;if("symbol"==typeof t)return t.toString();if("bigint"==typeof t)return t.toString()+"n";if("object"==typeof t&&null!==t){if(r.has(t))return"[Circular]";r.add(t)}return t instanceof Date?t.toISOString():t instanceof Error?{name:t.name,message:t.message,stack:t.stack}:t instanceof Map?{dataType:"Map",value:Array.from(t.entries())}:t instanceof Set?{dataType:"Set",value:Array.from(t.values())}:t},t)}catch(e){return console.error("Failed to stringify:",e),""}}function Xe(){let s,r;return{promise:new Promise((e,t)=>{s=e,r=t}),resolve:s,reject:r}}var t=Object.freeze({__proto__:null,ANDROID_VERSION:Ge,IE_VERSION:Fe,IN_ALIPAY_MINI_APP:ge,IN_BAIDU_MINI_APP:he,IN_BROWSER:Me,IN_DONUT_NATIVE_APP:ve,IN_JD_MINI_APP:_e,IN_MINI_APP:Ie,IN_NS_NATIVE_APP:Ee,IN_QQ_MINI_APP:de,IN_RN_APP:Ce,IN_TT_MINI_APP:pe,IN_UNI_APP:fe,IN_UNI_NATIVE_APP:me,IN_WX_MINI_APP:le,IN_WX_MINI_APP_DESK:ue,IN_WX_MINI_GAME:ce,IN_WX_MINI_PLUGIN:Se,IOS_VERSION:Ne,IS_ANDROID:be,IS_CHROME:Ue,IS_EDGE:we,IS_FIREFOX:Pe,IS_IE:ke,IS_IOS:Le,IS_IPAD:Oe,IS_IPHONE:De,IS_IPOD:Re,IS_MAC:Ve,IS_SAFARI:qe,IS_WECHAT:Te,IS_WIN:xe,IS_WORKER_AVAILABLE:Be,MINI_APP_NAMESPACE:ye,USER_AGENT:s,base16EncodeBinaryString:ae,deepCopyWithMethods:Je,deepMerge:oe,generatePromise:Xe,getPlatformType:He,getType:Z,httpRequest:$e,isArray:ee,isArrayOrObject:se,isEmpty:ze,isFlutterWeb:Ke,isH5:je,isIOSWebView:We,isNumber:e=>null!==e&&("number"==typeof e&&!Number.isNaN(+e)||"object"==typeof e&&e.constructor===Number),isObject:te,isPlainObject:ie,isString:X,isUndefined:Q,isValidRequestKey:re,platform:Ae,randomInt:ne,randomString:function(){let t="";for(let e=32;0<e;--e)t+="0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"[Math.floor(62*Math.random())];return t},safeStringify:Qe});class Ze{constructor(){this._socket=null}connectSocket(e){return this._socket=new WebSocket(e),this._socket}send(e){var t;try{null!=(t=this._socket)&&t.send(e)}catch(e){null!=(t=this._onSendFail)&&t.call(this,e)}}bindSocketHandlers(e){var{onOpen:e,onMessage:t,onClose:s,onError:r,onSendFail:i}=e;this._socket&&(this._socket.binaryType="arraybuffer",this._socket.onopen=e,this._socket.onmessage=t,this._socket.onclose=s,this._socket.onerror=r,this._onSendFail=i)}unbindSocketHandlers(){this._socket&&(this._socket.onopen=null,this._socket.onmessage=null,this._socket.onclose=null,this._socket.onerror=null)}disconnect(){this._socket&&(this._socket.close(),this._socket=null)}}class et{connectSocket(e){return this._socket=ye.connectSocket({url:e,header:{"content-type":"application/json"},complete:()=>{}}),this._socket}send(e){var t;null!=(t=this._socket)&&t.send({data:e,fail:this._onSendFail})}bindSocketHandlers(e){var{onOpen:e,onMessage:t,onClose:s,onError:r,onSendFail:i}=e;this._socket.onClose(s),this._socket.onOpen(e),this._socket.onMessage(t),this._socket.onError(r),this._onSendFail=i}unbindSocketHandlers(){this._socket&&(this._socket.onClose(()=>{}),this._socket.onOpen(()=>{}),this._socket.onMessage(()=>{}),this._socket.onError(()=>{}))}disconnect(){this._socket&&(this._socket.close(),this._socket=null)}}class st{constructor(){this._worker=null,this._blobUrl=null}connectSocket(e){var t=new Blob(["\n let _socket = null;\n\n self.onmessage = (event) => {\n const { type, url, data } = event.data;\n\n switch (type) {\n case 'CONNECT':\n connectSocket(url);\n break;\n case 'SEND':\n send(data);\n break;\n case 'DISCONNECT':\n disconnect();\n break;\n }\n };\n\n function connectSocket(url) {\n _socket = new WebSocket(url);\n _socket.binaryType = 'arraybuffer';\n bindSocketHandlers();\n return _socket;\n }\n\n function send(packet) {\n try {\n _socket?.send(packet);\n } catch (error) {\n self.postMessage({\n type: 'SEND_FAIL', \n error: {\n message: error.message,\n name: error.name,\n },\n });\n }\n }\n\n function bindSocketHandlers() {\n if (_socket) {\n _socket.onopen = (event) => {\n self.postMessage({\n type: 'OPEN',\n data: {\n type: event.type,\n timeStamp: event.timeStamp,\n },\n });\n };\n\n _socket.onmessage = (event) => {\n self.postMessage({ \n type: 'MESSAGE',\n data: event.data,\n });\n };\n\n _socket.onclose = (event) => {\n self.postMessage({ \n type: 'CLOSE', \n data: { \n code: event.code,\n reason: event.reason,\n timeStamp: event.timeStamp,\n },\n });\n };\n\n _socket.onerror = (error) => {\n self.postMessage({\n type: 'ERROR',\n data: {\n message: error.message,\n name: error.name\n },\n });\n };\n }\n }\n\n function unbindSocketHandlers() {\n if (_socket) {\n _socket.onopen = null;\n _socket.onmessage = null;\n _socket.onclose = null;\n _socket.onerror = null;\n }\n }\n\n function disconnect() {\n if (_socket) {\n _socket.close();\n _socket = null;\n }\n }\n"],{type:"application/javascript"});this._worker=new Worker(URL.createObjectURL(t)),this._worker.postMessage({type:"CONNECT",url:e})}send(e){var t;try{null!=(t=this._worker)&&t.postMessage({type:"SEND",data:e})}catch(e){null!=(t=this._onSendFail)&&t.call(this,e)}}bindSocketHandlers(e){var{onOpen:t,onMessage:r,onClose:i,onError:n,onSendFail:o}=e;if(this._worker){let s={OPEN:t,MESSAGE:r,CLOSE:i,ERROR:n,SEND_FAIL:o};this._onSendFail=o,this._worker.onmessage=e=>{var t=((null==e?void 0:e.data)||{})["type"];"function"==typeof s[t]&&null!=(t=s[t])&&t.call(s,null==e?void 0:e.data)}}}unbindSocketHandlers(){this._worker&&(this._worker.onmessage=null)}disconnect(){this._worker&&(this._worker.postMessage({type:"DISCONNECT"}),this._worker.terminate(),this._worker=null),this._blobUrl&&(URL.revokeObjectURL(this._blobUrl),this._blobUrl=null)}}var rt,it,c=new class{constructor(){this._store=new Map}get(e){return this._store.get(e)}getStorage(e){return Ie?ge?my.getStorageSync({key:e}).data:ye.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){Ie?ge?my.setStorageSync({key:e,data:JSON.stringify(t)}):ye.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}};(it=rt=rt||{})[it.CONNECTED=0]="CONNECTED",it[it.CONNECTING=1]="CONNECTING",it[it.DISCONNECTED=2]="DISCONNECTED";class nt{constructor(e){this._url="",this._readyState=rt.DISCONNECTED,this._url=e,this._id=ne(),this._emitter=new P,le||me?this._socket=new et:this._canUseWebWorker()?this._socket=new st:this._socket=new Ze,this.connect()}connect(){this.doOpen(),this._bindSocketHandlers()}doOpen(){[rt.CONNECTED,rt.CONNECTING].includes(this._readyState)||(this._readyState=rt.CONNECTING,this._ws=this._socket.connectSocket(this._url))}send(e){this._readyState!==rt.CONNECTED?this.reconnect():this._socket.send(e)}reconnect(){[rt.CONNECTED,rt.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===rt.CONNECTED}disconnect(){this._readyState=rt.DISCONNECTED,this._unbindSocketHandlers(),this._socket.disconnect()}_onOpen(e){this._readyState===rt.CONNECTING&&(this._readyState=rt.CONNECTED,this._emitter.emit("connect",{socketId:this._id,event:e}))}_onMessage(e){this._emitter.emit("message",e)}_onClose(e){this._readyState=rt.DISCONNECTED,this._emitter.emit("close",{socketId:this._id,event:e})}_onError(e){this._readyState=rt.DISCONNECTED,this._emitter.emit("error",{socketId:this._id,error:e})}_onSendFail(e){this._readyState=rt.DISCONNECTED,this._emitter.emit("sendFail",{socketId:this._id,error:e})}_bindSocketHandlers(){this._socket.bindSocketHandlers({onOpen:this._onOpen.bind(this),onMessage:this._onMessage.bind(this),onClose:this._onClose.bind(this),onError:this._onError.bind(this),onSendFail:this._onSendFail.bind(this)})}_unbindSocketHandlers(){this._socket.unbindSocketHandlers()}_canUseWebWorker(){var e=c.get("cloudConfig")||{};return(Q(e.isWorkerEnabled)||"1"===e.isWorkerEnabled)&&Be}}let ot={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"}}},at={SINGAPORE:[[2e7,3e7],[172e7,173e7]],KOREA:[[3e7,4e7],[173e7,174e7]],GERMANY:[[4e7,5e7],[174e7,175e7]],IND:[[5e7,6e7],[175e7,176e7]],JPN:[[6e7,7e7],[176e7,177e7]],USA:[[7e7,8e7],[177e7,178e7]],INDONESIA:[[8e7,9e7],[178e7,179e7]]};function ut(t){var e;if(null!=(e=c.get("instance"))&&e.oversea)return"OVERSEA";for(let e of Object.keys(at))for(var[s,r]of at[e])if(t>=s&&t<r)return e;return"CHINA"}var a,lt="1.6.2-beta.0";(n=a=a||{}).INITIAL="INITIAL",n.DEFAULT="DEFAULT",n.BACKUP="BACKUP",n.BACKUP_WEB_ONLY="BACKUP_WEB_ONLY",n.BACKUP_CN="BACKUP_CN",n.ANYCAST="ANYCAST",n.IPV6="IPV6";let ct=a.INITIAL;function dt(e,t){var s,{isBinary:t=!1}=t||{},{sdkAppId:r,instanceId:i}=c.get("instance"),n=function e(){var t=Math.random();return 0===t?e():t}(),o=He(),a=function(){var e=He();let t=-1;return"ios"===e?t=Ne||-1:"android"===e&&(t=Ge||-1),t}(),r=(s={sdkappid:r,instanceid:i,random:n,platform:Ae,host:o,version:a,sdkversion:lt},Object.keys(s).map(e=>e+"="+s[e]).join("&"));return t?e+`/binfo?${r}&compress=gzip`:e+"/info?"+r}function pt(e){var{sdkAppId:t,testEnv:s}=c.get("instance"),t=ut(t);if(s)return dt(ot.TEST[t].DEFAULT,{isBinary:e});let r=ot.PRODUCTION[t],i=Me&&r.ANYCAST,n=Me,o=!!r.BACKUP_CN;return dt({[a.INITIAL]:()=>(ct=a.DEFAULT,r.DEFAULT),[a.DEFAULT]:()=>(ct=a.IPV6,r.IPV6),[a.IPV6]:()=>(ct=a.BACKUP,r.BACKUP),[a.BACKUP]:()=>{return n?(ct=a.BACKUP_WEB_ONLY,e=r.BACKUP_WEB_ONLY,t=Math.floor(10001*Math.random())+1e4,e.replace("*",String(t))):o?(ct=a.BACKUP_CN,r.BACKUP_CN):i?(ct=a.ANYCAST,r.ANYCAST):r.DEFAULT;var e,t},[a.BACKUP_WEB_ONLY]:()=>o?(ct=a.BACKUP_CN,r.BACKUP_CN):i?(ct=a.ANYCAST,r.ANYCAST):r.DEFAULT,[a.BACKUP_CN]:()=>(ct=i?a.ANYCAST:a.DEFAULT,r[ct]),[a.ANYCAST]:()=>(ct=a.DEFAULT,r.ANYCAST="",r.DEFAULT)}[ct](),{isBinary:e})}var ht=new class{constructor(){this._timeOffsetWithServer=0}getServerTimeMs(){return Date.now()+this._timeOffsetWithServer}getServerTimeSeconds(){return Math.floor(this.getServerTimeMs()/1e3)}getTimeOffsetWithServer(){return this._timeOffsetWithServer}calculateTimeOffsetWithServer(e,t){var s=Date.now();this._timeOffsetWithServer=t+(s-e)-s}};var gt=new class{constructor(){this._tasks=[],this._timer=null,this._taskMap=new Map}_addTaskToScheduler(e){var t=e["id"];this.removeTask(t),this._tasks.push(e),this._taskMap.set(t,e),this._sort(),this._scheduleNextTask()}_createTask(e){var{id:e,callback:t,context:s,isOnce:r=!1,intervalMs:i=16}=e,n=Math.max(i,16);return{id:e,nextExecuteTime:Date.now()+n,intervalMs:i,callback:t,context:s,isOnce:r}}addTask(e){e=this._createTask(e);this._addTaskToScheduler(e)}addOnceTask(e){e=this._createTask(Object.assign(Object.assign({},e),{isOnce:!0}));this._addTaskToScheduler(e)}removeTask(t){var e=this._tasks.findIndex(e=>e.id===t);-1<e&&(this._tasks.splice(e,1),this._taskMap.delete(t),this._scheduleNextTask())}updateTaskInterval(e,t){e=this._taskMap.get(e);e&&(e.intervalMs=t,e.nextExecuteTime=Date.now()+t,this._sort(),this._scheduleNextTask())}clearAllTasks(){this._tasks=[],this._taskMap.clear(),this._timer&&(clearTimeout(this._timer),this._timer=null)}dispose(){this.clearAllTasks()}_sort(){this._tasks.sort((e,t)=>e.nextExecuteTime-t.nextExecuteTime)}_scheduleNextTask(){this._timer&&(clearTimeout(this._timer),this._timer=null);var e=this._tasks[0];e&&(e=Math.max(0,e.nextExecuteTime-Date.now()),this._timer=setTimeout(()=>this._execute(),e))}_execute(){for(var e=Date.now();this._tasks.length&&this._tasks[0].nextExecuteTime<=e;){var t=this._tasks[0];try{t.context?t.callback.call(t.context):t.callback(),t.isOnce?this.removeTask(t.id):(t.nextExecuteTime=e+t.intervalMs,this._sort())}catch(e){console.warn(`Task ${t.id} execution failed:`,e),t.isOnce&&this.removeTask(t.id)}}this._scheduleNextTask()}};function _t(t){var s=[];for(let e=0;e<t.length;e+=1){var r,i=t.charCodeAt(e);55296<=i&&i<=56319?(r=t.charCodeAt(++e)-56320+(i-55296<<10)+65536,s.push(240|r>>18,128|r>>12&63,128|r>>6&63,128|63&r)):i<=127?s.push(i):i<=2047?s.push(192|i>>6,128|63&i):s.push(224|i>>12,128|i>>6&63,128|63&i)}return new Uint8Array(s)}function mt(e){var t,s=Array.isArray(e)?[]:Object.create(null);for(t in e)Object.prototype.hasOwnProperty.call(e,t)&&re(t)&&null!=e[t]&&(null===e[t]||"object"!=typeof e[t]?s[t]=e[t]:s[t]=mt(e[t]));return s}function vt(e,t){if(U.includes(e))return 0;var s=_t(JSON.stringify(t));let r=4294967295;var i=s["length"];for(let e=0;e<i;e++){r^=s[e];for(let e=0;e<8;e++)1&~r?r>>>=1:r=r>>>1^3988292384}return(4294967295^r)>>>0}function ft(e){var t,{servcmd:e,data:s}=e,r=(r=e,i=c.get("login")||{},t=c.get("instance")||{},{servcmd:r,ver:"v4",platform:Ae,websdkappid:537048168,websdkversion:"1.7.3",a2:i.a2Key||void 0,tinyid:i.tinyID||void 0,status_instid:i.statusInstanceId||0,sdkappid:t.sdkAppId,contenttype:"json",reqtime:Math.floor(Date.now()/1e3),identifier:i.a2Key?void 0:i.userId,usersig:i.a2Key?void 0:i.userSig,sdkability:75689843,sdkability_ext:ae(""),cappid:t.applicationID||0,tjgID:"",seq:Ct(),cs:0}),i=mt(s);return r.cs=vt(e,i),{head:r,body:i}}function It(e){var t,{servcmd:e,data:s}=e,r=(r=e,i=c.get("login")||{},t=c.get("instance")||{},{servcmd:r,ver:"v4",platform:Ae,websdkappid:537048168,websdkversion:"1.7.3",sdkappid:t.sdkAppId,contenttype:"",reqtime:Math.floor(Date.now()/1e3),identifier:"",usersig:"",status_instid:i.statusInstanceId||0,sdkability:75689843,sdkability_ext:ae(""),cappid:t.applicationID||0,seq:Ct(),cs:0}),i=mt(s);return r.cs=vt(e,i),{head:r,body:i}}let Et=ne();function Ct(){return Et=Et<2415919103?Et+1:ne()}function St(){var e=c.get("login")||{},t=c.get("instance")||{};return{sdk_type:30,sdk_app_id:t.sdkAppId,sdk_version:"1.6.2-beta.0",tiny_id:Number(e.tinyID),user_id:e.userId,platform:Ae,instance_id:t.instanceId,trace_id:(new Date).getTime()}}var Mt,n=Object.freeze({__proto__:null,generateCosSpecifiedData:function(e){var t,{servcmd:e,data:s}=e,r=(r=e,i=c.get("login")||{},t=c.get("instance")||{},{servcmd:r,ver:"v4",platform:Ae,websdkappid:537048168,websdkversion:"1.7.3",sdkappid:t.sdkAppId,contenttype:"json",reqtime:Math.floor(Date.now()/1e3),identifier:i.userId,usersig:i.userSig,status_instid:i.statusInstanceId||0,sdkability:75689843,sdkability_ext:ae(""),cappid:t.applicationID||0,seq:Ct(),cs:0}),i=mt(s);return r.cs=vt(e,i),{head:r,body:i}},generateProtocolData:ft,generateSSOLogProtocolData:It,generateSequence:Ct,getCommonHead:St,taskScheduler:gt,timeManager:ht});(_=Mt=Mt||{})[_.info=4]="info",_[_.warning=5]="warning",_[_.error=6]="error";let yt={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 Tt{constructor(e){this.level=Mt.info,this._canSendLog=!0,this._logCreatedAt=ht.getServerTimeMs(),this.timestamp=0,this.networkType=8,this.code=0,this.moreMessage="",this.method="",this.message="",this.costTime=0,this.duplicate=!1,this.eventType=0,this.uiPlatform=this._getUiPlatform(),this._sdkEdition=this._getSDKEdition();var{method:e,eventType:t=0,message:s="",costTime:r=0,error:i,moreMessage:n=""}=e||{};this.eventType=t,this.method=e,this.message=s,this.costTime=r,this.moreMessage=n,i&&this.setError(i)}setMoreMessage(e){this.moreMessage=this.moreMessage+" "+e}updateLogCreatedAtByTimeOffset(){this._logCreatedAt+=ht.getTimeOffsetWithServer()}end(){this._canSendLog&&(this._canSendLog=!1,this.timestamp=ht.getServerTimeMs(),this._ssoLogModule.pushToLogQueue(this._convertSSOLogDataKeyToServe()))}setError(e){var t;return e instanceof Error?this._canSendLog&&(null!=(t=c.get("netWorkMonitor"))&&t.isNetworkOnline&&(e.errorCode&&(this.code=e.errorCode),e.errorMessage)&&this.setMoreMessage(e.errorMessage),this.level=Mt.error):console.warn("SSOLogData.setError value not instanceof Error, please check!"),this}setLogInfo(t){return Object.keys(t).forEach(e=>{Object.keys(yt).includes(e)&&(this[e]=t[e])}),this}setSSOLogModule(e){this._ssoLogModule=e}_convertSSOLogDataKeyToServe(){let t={};return Object.keys(this).forEach(e=>{yt[e]&&(t[yt[e]]=this[e])}),t}_getUiPlatform(){var e,t=null==(e=c.get("instance"))?void 0:e.scene;if("string"==typeof t){let e=Number(t);return isNaN(e)?void 0:e}}_getSDKEdition(){var e;return null==(e=c.get("instance"))?void 0:e.sdkEdition}}(_=N=N||{}).RECONNECTED="reconnected",_.CLOUD_CONFIG_UPDATE="cloud_config_update",_.SOCKET_DISCONNECTED="socket_disconnected";var At=N;let Ot=[4,5,6],Dt=[],Rt=[],Lt="report-logger";var Nt=new class{constructor(){this._sdkAppIdBlackList=[],this._tinyIdWhiteList=[],this._reportLevel=[4,5,6],this._minThreshold=20,this._maxThreshold=100,this._waitingTime=6e4,this._lastReportAt=Date.now(),this._ssoLogMap=new Map,this._logLevel=i.DEBUG,this._throttleConfig={global:{throttleTime:5e3,maxCount:50},single:{throttleTime:1e3,maxCount:2}},this._globalThrottle={count:0,startTime:Date.now()},this._singleThrottleMap=new Map,J.subscribeInnerEvent(At.CLOUD_CONFIG_UPDATE,this._handleCloudConfigUpdate,this),gt.addTask({id:Lt,intervalMs:1e3,callback:this._checkAndReportIfDue,context:this}),this._logQueue=[],this._savePlatFormInfo()}_handleCloudConfigUpdate(e){var{evt_rpt_threshold:e=20,evt_rpt_waiting:t=6e4,evt_rpt_level:s=Ot,evt_rpt_sdkappid_bl:r=Dt,evt_rpt_tinyid_wl:i=Rt,evt_rpt_global_throttle_time:n=5e3,evt_rpt_global_throttle_count:o=50,evt_rpt_single_throttle_time:a=1e3,evt_rpt_single_throttle_count:u=2}=e||{};this._sdkAppIdBlackList=r,this._waitingTime=t,this._minThreshold=e,this._reportLevel=s,this._tinyIdWhiteList=i,this._throttleConfig={global:{throttleTime:n,maxCount:o},single:{throttleTime:a,maxCount:u}}}createSSOLogData(e){var t=new Tt(e);return t.setSSOLogModule(this),this._ssoLogMap.set(e.method,t),t}getSSOLogData(e){return this._ssoLogMap.get(e)||{}}pushToLogQueue(e){e&&(this._logQueue.push(e),this._shouldUploadImmediately())&&this.uploadSSOLogData()}setLogLevel(e){[i.DEBUG,i.ERROR,i.INFO,i.NONE,i.WARN].includes(e)&&(this._logLevel=e)}debug(e,t="",s){this._log(i.DEBUG,e,t,s)}info(e,t="",s){this._log(i.INFO,e,t,s)}warn(e,t="",s){this._log(i.WARN,e,t,s)}error(e,t="",s){this._log(i.ERROR,e,t,s)}_shouldUploadImmediately(){return this._logQueue.length>=this._minThreshold}_isReportDue(){return Date.now()>=this._lastReportAt+this._waitingTime}_checkAndReportIfDue(){this._isReportDue()&&0<this._logQueue.length&&this.uploadSSOLogData()}uploadSSOLogData(){return I(this,void 0,void 0,function*(){var e,t;0!==this._logQueue.length&&(t=this._logQueue.slice(),t=this._filterLogs(t),this._logQueue=[],0===t.length||ze((t={Header:St(),Event:t}).Header.user_id)||(e=(t=It({servcmd:e="imopenstat.tim_web_report_v2",data:t})).head.seq+e,yield void xt.sendPacket(t,{requestId:e})),this._lastReportAt=Date.now())})}_savePlatFormInfo(){var e,t;if(le){var s=null==(t=null==(e=wx.getAccountInfoSync)?void 0:e.call(wx))?void 0:t.miniProgram;if(s){let{appId:e,envVersion:t}=s;c.set("instance",{appId:e,envVersion:t})}}else Me&&c.set("instance",{href:window.location.href})}_filterLogs(e){var t=(c.get("login")||{})["tinyID"],s=(c.get("instance")||{})["sdkAppId"];return this._sdkAppIdBlackList.includes(s)&&!this._tinyIdWhiteList.includes(t)?[]:e.filter(e=>this._reportLevel.includes(e.level))}_checkThrottle(e){return!!this._checkGlobalThrottle()||this._checkSingleThrottle(e)}_checkGlobalThrottle(){var e=Date.now();if(e-this._globalThrottle.startTime>=this._throttleConfig.global.throttleTime)this._globalThrottle.count=1,this._globalThrottle.startTime=e;else if(this._globalThrottle.count++,this._globalThrottle.count>this._throttleConfig.global.maxCount)return!0;return!1}_checkSingleThrottle(e){var t=Date.now(),s=this._singleThrottleMap.get(e);return s?t-s.startTime>=this._throttleConfig.single.throttleTime?(s.count=1,s.startTime=t,!1):s.count>=this._throttleConfig.single.maxCount||(s.count++,!1):(this._singleThrottleMap.set(e,{count:1,startTime:t}),!1)}_shouldLog(e){return e>=this._logLevel&&this._logLevel!==i.NONE}_shouldReport(e){return this._reportLevel.includes(B[e])}_formatLog(e,t,s){var r=new Date,r=`${r.getHours()}:${r.getMinutes()}:${r.getSeconds()}:`+r.getMilliseconds(),e=`<${i[e]}>`;return ke||Ie?[x+` [${r}] ${e} [${t}] `+s]:["%c%s%c%s","background:#0abf5b; padding:1px; border-radius:3px; color: #fff",x,"",`[${r}] ${e} [${t}] `+s]}_log(e,t,s,r){if(this._shouldLog(e)){var i=this._formatLog(e,t,s);if(V[e].apply(console,i),this._shouldReport(e)){let e=this._getThrottleKey(t,s,r);this._checkThrottle(e)||this.createSSOLogData(Object.assign(Object.assign({message:s},r),{method:t})).end()}}}_getThrottleKey(e,t,s){var e=""+e+t+Qe(Object.assign(Object.assign({},s),{costTime:""})),r=_t(JSON.stringify(e));let i=4294967295;var n=r["length"];for(let e=0;e<n;e++){i^=r[e];for(let e=0;e<8;e++)1&~i?i>>>=1:i=i>>>1^3988292384}return""+((4294967295^i)>>>0)}reset(){console.log("SSO_LOG_MODULE.reset"),gt.removeTask(Lt),J.unSubscribeInnerEvent(At.CLOUD_CONFIG_UPDATE,this._handleCloudConfigUpdate,this),this._lastReportAt=0,this.uploadSSOLogData(),this._sdkAppIdBlackList=[],this._tinyIdWhiteList=[],this._minThreshold=20,this._maxThreshold=100,this._waitingTime=6e4,this._logQueue=[],this._logLevel=i.DEBUG,this._globalThrottle={count:0,startTime:Date.now()},this._singleThrottleMap.clear()}};let u="Channel",bt="channel_schedule_task",Gt="channel_reconnect_task",Pt="connected",wt="disconnected",Ut="network_status_change";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 qt=function s(r,i,n){function o(t,e){if(!i[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=i[t]={exports:{}};r[t][0].call(e.exports,function(e){return o(r[t][1][e]||e)},e,e.exports,s,r,i,n)}return i[t].exports}for(var a=Ft,e=0;e<n.length;e++)o(n[e]);return o}({1:[function(e,t,s){var r="undefined"!=typeof Uint8Array&&"undefined"!=typeof Uint16Array&&"undefined"!=typeof Int32Array,i=(s.assign=function(e){for(var t,s,r=Array.prototype.slice.call(arguments,1);r.length;){var i=r.shift();if(i){if("object"!=kt(i))throw new TypeError(i+"must be non-object");for(var n in i)t=i,s=n,Object.prototype.hasOwnProperty.call(t,s)&&(e[n]=i[n])}}return e},s.shrinkBuf=function(e,t){return e.length===t?e:e.subarray?e.subarray(0,t):(e.length=t,e)},{arraySet:function(e,t,s,r,i){if(t.subarray&&e.subarray)e.set(t.subarray(s,s+r),i);else for(var n=0;n<r;n++)e[i+n]=t[s+n]},flattenChunks:function(e){for(var t,s,r,i,n=t=0,o=e.length;n<o;n++)t+=e[n].length;for(i=new Uint8Array(t),n=s=0,o=e.length;n<o;n++)r=e[n],i.set(r,s),s+=r.length;return i}}),n={arraySet:function(e,t,s,r,i){for(var n=0;n<r;n++)e[i+n]=t[s+n]},flattenChunks:function(e){return[].concat.apply([],e)}};s.setTyped=function(e){e?(s.Buf8=Uint8Array,s.Buf16=Uint16Array,s.Buf32=Int32Array,s.assign(s,i)):(s.Buf8=Array,s.Buf16=Array,s.Buf32=Array,s.assign(s,n))},s.setTyped(r)},{}],2:[function(e,t,s){var u=e("./common"),i=!0,n=!0;try{String.fromCharCode.apply(null,[0])}catch(e){i=!1}try{String.fromCharCode.apply(null,new Uint8Array(1))}catch(e){n=!1}for(var l=new u.Buf8(256),r=0;r<256;r++)l[r]=252<=r?6:248<=r?5:240<=r?4:224<=r?3:192<=r?2:1;function c(e,t){if(t<65534&&(e.subarray&&n||!e.subarray&&i))return String.fromCharCode.apply(null,u.shrinkBuf(e,t));for(var s="",r=0;r<t;r++)s+=String.fromCharCode(e[r]);return s}l[254]=l[254]=1,s.string2buf=function(e){for(var t,s,r,i,n=e.length,o=0,a=0;a<n;a++)55296==(64512&(s=e.charCodeAt(a)))&&a+1<n&&56320==(64512&(r=e.charCodeAt(a+1)))&&(s=65536+(s-55296<<10)+(r-56320),a++),o+=s<128?1:s<2048?2:s<65536?3:4;for(t=new u.Buf8(o),a=i=0;i<o;a++)55296==(64512&(s=e.charCodeAt(a)))&&a+1<n&&56320==(64512&(r=e.charCodeAt(a+1)))&&(s=65536+(s-55296<<10)+(r-56320),a++),s<128?t[i++]=s:(s<2048?t[i++]=192|s>>>6:(s<65536?t[i++]=224|s>>>12:(t[i++]=240|s>>>18,t[i++]=128|s>>>12&63),t[i++]=128|s>>>6&63),t[i++]=128|63&s);return t},s.buf2binstring=function(e){return c(e,e.length)},s.binstring2buf=function(e){for(var t=new u.Buf8(e.length),s=0,r=t.length;s<r;s++)t[s]=e.charCodeAt(s);return t},s.buf2string=function(e,t){for(var s,r,i,n=t||e.length,o=new Array(2*n),a=s=0;a<n;)if((r=e[a++])<128)o[s++]=r;else if(4<(i=l[r]))o[s++]=65533,a+=i-1;else{for(r&=2===i?31:3===i?15:7;1<i&&a<n;)r=r<<6|63&e[a++],i--;1<i?o[s++]=65533:r<65536?o[s++]=r:(r-=65536,o[s++]=55296|r>>10&1023,o[s++]=56320|1023&r)}return c(o,s)},s.utf8border=function(e,t){for(var s=(t=(t=t||e.length)>e.length?e.length:t)-1;0<=s&&128==(192&e[s]);)s--;return!(s<0||0===s)&&s+l[e[s]]>t?s:t}},{"./common":1}],3:[function(e,t,s){t.exports=function(e,t,s,r){for(var i=65535&e,n=e>>>16&65535,o=0;0!==s;){for(s-=o=2e3<s?2e3:s;n=n+(i=i+t[r++]|0)|0,--o;);i%=65521,n%=65521}return i|n<<16}},{}],4:[function(e,t,s){t.exports={Z_NO_FLUSH:0,Z_PARTIAL_FLUSH:1,Z_SYNC_FLUSH:2,Z_FULL_FLUSH:3,Z_FINISH:4,Z_BLOCK:5,Z_TREES:6,Z_OK:0,Z_STREAM_END:1,Z_NEED_DICT:2,Z_ERRNO:-1,Z_STREAM_ERROR:-2,Z_DATA_ERROR:-3,Z_BUF_ERROR:-5,Z_NO_COMPRESSION:0,Z_BEST_SPEED:1,Z_BEST_COMPRESSION:9,Z_DEFAULT_COMPRESSION:-1,Z_FILTERED:1,Z_HUFFMAN_ONLY:2,Z_RLE:3,Z_FIXED:4,Z_DEFAULT_STRATEGY:0,Z_BINARY:0,Z_TEXT:1,Z_UNKNOWN:2,Z_DEFLATED:8}},{}],5:[function(e,t,s){var a=function(){for(var e=[],t=0;t<256;t++){for(var s=t,r=0;r<8;r++)s=1&s?3988292384^s>>>1:s>>>1;e[t]=s}return e}();t.exports=function(e,t,s,r){var i=a,n=r+s;e^=-1;for(var o=r;o<n;o++)e=e>>>8^i[255&(e^t[o])];return~e}},{}],6:[function(e,t,s){t.exports=function(){this.text=0,this.time=0,this.xflags=0,this.os=0,this.extra=null,this.extra_len=0,this.name="",this.comment="",this.hcrc=0,this.done=!1}},{}],7:[function(e,t,s){t.exports=function(e,t){var s,r,i,n,o,a,u=e.state,l=e.next_in,c=e.input,d=l+(e.avail_in-5),p=e.next_out,h=e.output,g=p-(t-e.avail_out),_=p+(e.avail_out-257),m=u.dmax,v=u.wsize,f=u.whave,I=u.wnext,E=u.window,C=u.hold,S=u.bits,M=u.lencode,y=u.distcode,T=(1<<u.lenbits)-1,A=(1<<u.distbits)-1;e:do{for(S<15&&(C+=c[l++]<<S,S+=8,C+=c[l++]<<S,S+=8),s=M[C&T];;){if(C>>>=r=s>>>24,S-=r,0==(r=s>>>16&255))h[p++]=65535&s;else{if(!(16&r)){if(!(64&r)){s=M[(65535&s)+(C&(1<<r)-1)];continue}if(32&r){u.mode=12;break e}e.msg="invalid literal/length code",u.mode=30;break e}for(i=65535&s,(r&=15)&&(S<r&&(C+=c[l++]<<S,S+=8),i+=C&(1<<r)-1,C>>>=r,S-=r),S<15&&(C+=c[l++]<<S,S+=8,C+=c[l++]<<S,S+=8),s=y[C&A];;){if(C>>>=r=s>>>24,S-=r,!(16&(r=s>>>16&255))){if(!(64&r)){s=y[(65535&s)+(C&(1<<r)-1)];continue}e.msg="invalid distance code",u.mode=30;break e}if(n=65535&s,S<(r&=15)&&(C+=c[l++]<<S,(S+=8)<r)&&(C+=c[l++]<<S,S+=8),m<(n+=C&(1<<r)-1)){e.msg="invalid distance too far back",u.mode=30;break e}if(C>>>=r,S-=r,(r=p-g)<n){if(f<(r=n-r)&&u.sane){e.msg="invalid distance too far back",u.mode=30;break e}if(a=E,(o=0)===I){if(o+=v-r,r<i){for(i-=r;h[p++]=E[o++],--r;);o=p-n,a=h}}else if(I<r){if(o+=v+I-r,(r-=I)<i){for(i-=r;h[p++]=E[o++],--r;);if(o=0,I<i){for(i-=r=I;h[p++]=E[o++],--r;);o=p-n,a=h}}}else if(o+=I-r,r<i){for(i-=r;h[p++]=E[o++],--r;);o=p-n,a=h}for(;2<i;)h[p++]=a[o++],h[p++]=a[o++],h[p++]=a[o++],i-=3;i&&(h[p++]=a[o++],1<i)&&(h[p++]=a[o++])}else{for(o=p-n;h[p++]=h[o++],h[p++]=h[o++],h[p++]=h[o++],2<(i-=3););i&&(h[p++]=h[o++],1<i)&&(h[p++]=h[o++])}break}}break}}while(l<d&&p<_);l-=i=S>>3,C&=(1<<(S-=i<<3))-1,e.next_in=l,e.next_out=p,e.avail_in=l<d?d-l+5:5-(l-d),e.avail_out=p<_?_-p+257:257-(p-_),u.hold=C,u.bits=S}},{}],8:[function(e,t,s){var N=e("../utils/common"),b=e("./adler32"),G=e("./crc32"),P=e("./inffast"),w=e("./inftrees"),U=0,k=-2,F=1,r=852,i=592;function q(e){return(e>>>24&255)+(e>>>8&65280)+((65280&e)<<8)+((255&e)<<24)}function n(){this.mode=0,this.last=!1,this.wrap=0,this.havedict=!1,this.flags=0,this.dmax=0,this.check=0,this.total=0,this.head=null,this.wbits=0,this.wsize=0,this.whave=0,this.wnext=0,this.window=null,this.hold=0,this.bits=0,this.length=0,this.offset=0,this.extra=0,this.lencode=null,this.distcode=null,this.lenbits=0,this.distbits=0,this.ncode=0,this.nlen=0,this.ndist=0,this.have=0,this.next=null,this.lens=new N.Buf16(320),this.work=new N.Buf16(288),this.lendyn=null,this.distdyn=null,this.sane=0,this.back=0,this.was=0}function o(e){var t;return e&&e.state?(t=e.state,e.total_in=e.total_out=t.total=0,e.msg="",t.wrap&&(e.adler=1&t.wrap),t.mode=F,t.last=0,t.havedict=0,t.dmax=32768,t.head=null,t.hold=0,t.bits=0,t.lencode=t.lendyn=new N.Buf32(r),t.distcode=t.distdyn=new N.Buf32(i),t.sane=1,t.back=-1,U):k}function a(e){var t;return e&&e.state?((t=e.state).wsize=0,t.whave=0,t.wnext=0,o(e)):k}function u(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 l(e,t){var s;return e?(s=new n,(e.state=s).window=null,(s=u(e,t))!==U&&(e.state=null),s):k}var x,V,B=!0;function j(e,t,s,r){var i,e=e.state;return null===e.window&&(e.wsize=1<<e.wbits,e.wnext=0,e.whave=0,e.window=new N.Buf8(e.wsize)),r>=e.wsize?(N.arraySet(e.window,t,s-e.wsize,e.wsize,0),e.wnext=0,e.whave=e.wsize):(r<(i=e.wsize-e.wnext)&&(i=r),N.arraySet(e.window,t,s-r,i,e.wnext),(r-=i)?(N.arraySet(e.window,t,s-r,r,0),e.wnext=r,e.whave=e.wsize):(e.wnext+=i,e.wnext===e.wsize&&(e.wnext=0),e.whave<e.wsize&&(e.whave+=i))),0}s.inflateReset=a,s.inflateReset2=u,s.inflateResetKeep=o,s.inflateInit=function(e){return l(e,15)},s.inflateInit2=l,s.inflate=function(e,t){var s,r,i,n,o,a,u,l,c,d,p,h,g,_,m,v,f,I,E,C,S,M,y,T,A=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),o=e.next_out,i=e.output,u=e.avail_out,n=e.next_in,r=e.input,a=e.avail_in,l=s.hold,c=s.bits,d=a,p=u,M=U;e:for(;;)switch(s.mode){case F:if(0===s.wrap)s.mode=13;else{for(;c<16;){if(0===a)break e;a--,l+=r[n++]<<c,c+=8}if(2&s.wrap&&35615===l)O[s.check=0]=255&l,O[1]=l>>>8&255,s.check=G(s.check,O,2,0),c=l=0,s.mode=2;else if(s.flags=0,s.head&&(s.head.done=!1),!(1&s.wrap)||(((255&l)<<8)+(l>>8))%31)e.msg="incorrect header check",s.mode=30;else if(8!=(15&l))e.msg="unknown compression method",s.mode=30;else{if(c-=4,S=8+(15&(l>>>=4)),0===s.wbits)s.wbits=S;else if(S>s.wbits){e.msg="invalid window size",s.mode=30;break}s.dmax=1<<S,e.adler=s.check=1,s.mode=512&l?10:12,c=l=0}}break;case 2:for(;c<16;){if(0===a)break e;a--,l+=r[n++]<<c,c+=8}if(s.flags=l,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=l>>8&1),512&s.flags&&(O[0]=255&l,O[1]=l>>>8&255,s.check=G(s.check,O,2,0)),c=l=0,s.mode=3;case 3:for(;c<32;){if(0===a)break e;a--,l+=r[n++]<<c,c+=8}s.head&&(s.head.time=l),512&s.flags&&(O[0]=255&l,O[1]=l>>>8&255,O[2]=l>>>16&255,O[3]=l>>>24&255,s.check=G(s.check,O,4,0)),c=l=0,s.mode=4;case 4:for(;c<16;){if(0===a)break e;a--,l+=r[n++]<<c,c+=8}s.head&&(s.head.xflags=255&l,s.head.os=l>>8),512&s.flags&&(O[0]=255&l,O[1]=l>>>8&255,s.check=G(s.check,O,2,0)),c=l=0,s.mode=5;case 5:if(1024&s.flags){for(;c<16;){if(0===a)break e;a--,l+=r[n++]<<c,c+=8}s.length=l,s.head&&(s.head.extra_len=l),512&s.flags&&(O[0]=255&l,O[1]=l>>>8&255,s.check=G(s.check,O,2,0)),c=l=0}else s.head&&(s.head.extra=null);s.mode=6;case 6:if(1024&s.flags&&((h=a<(h=s.length)?a:h)&&(s.head&&(S=s.head.extra_len-s.length,s.head.extra||(s.head.extra=new Array(s.head.extra_len)),N.arraySet(s.head.extra,r,n,h,S)),512&s.flags&&(s.check=G(s.check,r,h,n)),a-=h,n+=h,s.length-=h),s.length))break e;s.length=0,s.mode=7;case 7:if(2048&s.flags){if(0===a)break e;for(h=0;S=r[n+h++],s.head&&S&&s.length<65536&&(s.head.name+=String.fromCharCode(S)),S&&h<a;);if(512&s.flags&&(s.check=G(s.check,r,h,n)),a-=h,n+=h,S)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(h=0;S=r[n+h++],s.head&&S&&s.length<65536&&(s.head.comment+=String.fromCharCode(S)),S&&h<a;);if(512&s.flags&&(s.check=G(s.check,r,h,n)),a-=h,n+=h,S)break e}else s.head&&(s.head.comment=null);s.mode=9;case 9:if(512&s.flags){for(;c<16;){if(0===a)break e;a--,l+=r[n++]<<c,c+=8}if(l!==(65535&s.check)){e.msg="header crc mismatch",s.mode=30;break}c=l=0}s.head&&(s.head.hcrc=s.flags>>9&1,s.head.done=!0),e.adler=s.check=0,s.mode=12;break;case 10:for(;c<32;){if(0===a)break e;a--,l+=r[n++]<<c,c+=8}e.adler=s.check=q(l),c=l=0,s.mode=11;case 11:if(0===s.havedict)return e.next_out=o,e.avail_out=u,e.next_in=n,e.avail_in=a,s.hold=l,s.bits=c,2;e.adler=s.check=1,s.mode=12;case 12:if(5===t||6===t)break e;case 13:if(s.last)l>>>=7&c,c-=7&c,s.mode=27;else{for(;c<3;){if(0===a)break e;a--,l+=r[n++]<<c,c+=8}switch(s.last=1&l,--c,3&(l>>>=1)){case 0:s.mode=14;break;case 1:R=L=void 0;var R,L=s;if(B){for(x=new N.Buf32(512),V=new N.Buf32(32),R=0;R<144;)L.lens[R++]=8;for(;R<256;)L.lens[R++]=9;for(;R<280;)L.lens[R++]=7;for(;R<288;)L.lens[R++]=8;for(w(1,L.lens,0,288,x,0,L.work,{bits:9}),R=0;R<32;)L.lens[R++]=5;w(2,L.lens,0,32,V,0,L.work,{bits:5}),B=!1}if(L.lencode=x,L.lenbits=9,L.distcode=V,L.distbits=5,s.mode=20,6!==t)break;l>>>=2,c-=2;break e;case 2:s.mode=17;break;case 3:e.msg="invalid block type",s.mode=30}l>>>=2,c-=2}break;case 14:for(l>>>=7&c,c-=7&c;c<32;){if(0===a)break e;a--,l+=r[n++]<<c,c+=8}if((65535&l)!=(l>>>16^65535)){e.msg="invalid stored block lengths",s.mode=30;break}if(s.length=65535&l,c=l=0,s.mode=15,6===t)break e;case 15:s.mode=16;case 16:if(h=s.length){if(0===(h=u<(h=a<h?a:h)?u:h))break e;N.arraySet(i,r,n,h,o),a-=h,n+=h,u-=h,o+=h,s.length-=h}else s.mode=12;break;case 17:for(;c<14;){if(0===a)break e;a--,l+=r[n++]<<c,c+=8}if(s.nlen=257+(31&l),l>>>=5,c-=5,s.ndist=1+(31&l),l>>>=5,c-=5,s.ncode=4+(15&l),l>>>=4,c-=4,286<s.nlen||30<s.ndist){e.msg="too many length or distance symbols",s.mode=30;break}s.have=0,s.mode=18;case 18:for(;s.have<s.ncode;){for(;c<3;){if(0===a)break e;a--,l+=r[n++]<<c,c+=8}s.lens[D[s.have++]]=7&l,l>>>=3,c-=3}for(;s.have<19;)s.lens[D[s.have++]]=0;if(s.lencode=s.lendyn,s.lenbits=7,y={bits:s.lenbits},M=w(0,s.lens,0,19,s.lencode,0,s.work,y),s.lenbits=y.bits,M){e.msg="invalid code lengths set",s.mode=30;break}s.have=0,s.mode=19;case 19:for(;s.have<s.nlen+s.ndist;){for(;v=(A=s.lencode[l&(1<<s.lenbits)-1])>>>16&255,f=65535&A,!((m=A>>>24)<=c);){if(0===a)break e;a--,l+=r[n++]<<c,c+=8}if(f<16)l>>>=m,c-=m,s.lens[s.have++]=f;else{if(16===f){for(T=m+2;c<T;){if(0===a)break e;a--,l+=r[n++]<<c,c+=8}if(l>>>=m,c-=m,0===s.have){e.msg="invalid bit length repeat",s.mode=30;break}S=s.lens[s.have-1],h=3+(3&l),l>>>=2,c-=2}else if(17===f){for(T=m+3;c<T;){if(0===a)break e;a--,l+=r[n++]<<c,c+=8}S=0,h=3+(7&(l>>>=m)),l>>>=3,c=c-m-3}else{for(T=m+7;c<T;){if(0===a)break e;a--,l+=r[n++]<<c,c+=8}S=0,h=11+(127&(l>>>=m)),l>>>=7,c=c-m-7}if(s.have+h>s.nlen+s.ndist){e.msg="invalid bit length repeat",s.mode=30;break}for(;h--;)s.lens[s.have++]=S}}if(30===s.mode)break;if(0===s.lens[256]){e.msg="invalid code -- missing end-of-block",s.mode=30;break}if(s.lenbits=9,y={bits:s.lenbits},M=w(1,s.lens,0,s.nlen,s.lencode,0,s.work,y),s.lenbits=y.bits,M){e.msg="invalid literal/lengths set",s.mode=30;break}if(s.distbits=6,s.distcode=s.distdyn,y={bits:s.distbits},M=w(2,s.lens,s.nlen,s.ndist,s.distcode,0,s.work,y),s.distbits=y.bits,M){e.msg="invalid distances set",s.mode=30;break}if(s.mode=20,6===t)break e;case 20:s.mode=21;case 21:if(6<=a&&258<=u){e.next_out=o,e.avail_out=u,e.next_in=n,e.avail_in=a,s.hold=l,s.bits=c,P(e,p),o=e.next_out,i=e.output,u=e.avail_out,n=e.next_in,r=e.input,a=e.avail_in,l=s.hold,c=s.bits,12===s.mode&&(s.back=-1);break}for(s.back=0;v=(A=s.lencode[l&(1<<s.lenbits)-1])>>>16&255,f=65535&A,!((m=A>>>24)<=c);){if(0===a)break e;a--,l+=r[n++]<<c,c+=8}if(v&&!(240&v)){for(I=m,E=v,C=f;v=(A=s.lencode[C+((l&(1<<I+E)-1)>>I)])>>>16&255,f=65535&A,!(I+(m=A>>>24)<=c);){if(0===a)break e;a--,l+=r[n++]<<c,c+=8}l>>>=I,c-=I,s.back+=I}if(l>>>=m,c-=m,s.back+=m,s.length=f,0===v){s.mode=26;break}if(32&v){s.back=-1,s.mode=12;break}if(64&v){e.msg="invalid literal/length code",s.mode=30;break}s.extra=15&v,s.mode=22;case 22:if(s.extra){for(T=s.extra;c<T;){if(0===a)break e;a--,l+=r[n++]<<c,c+=8}s.length+=l&(1<<s.extra)-1,l>>>=s.extra,c-=s.extra,s.back+=s.extra}s.was=s.length,s.mode=23;case 23:for(;v=(A=s.distcode[l&(1<<s.distbits)-1])>>>16&255,f=65535&A,!((m=A>>>24)<=c);){if(0===a)break e;a--,l+=r[n++]<<c,c+=8}if(!(240&v)){for(I=m,E=v,C=f;v=(A=s.distcode[C+((l&(1<<I+E)-1)>>I)])>>>16&255,f=65535&A,!(I+(m=A>>>24)<=c);){if(0===a)break e;a--,l+=r[n++]<<c,c+=8}l>>>=I,c-=I,s.back+=I}if(l>>>=m,c-=m,s.back+=m,64&v){e.msg="invalid distance code",s.mode=30;break}s.offset=f,s.extra=15&v,s.mode=24;case 24:if(s.extra){for(T=s.extra;c<T;){if(0===a)break e;a--,l+=r[n++]<<c,c+=8}s.offset+=l&(1<<s.extra)-1,l>>>=s.extra,c-=s.extra,s.back+=s.extra}if(s.offset>s.dmax){e.msg="invalid distance too far back",s.mode=30;break}s.mode=25;case 25:if(0===u)break e;if(s.offset>(h=p-u)){if((h=s.offset-h)>s.whave&&s.sane){e.msg="invalid distance too far back",s.mode=30;break}g=h>s.wnext?(h-=s.wnext,s.wsize-h):s.wnext-h,h>s.length&&(h=s.length),_=s.window}else _=i,g=o-s.offset,h=s.length;for(u-=h=u<h?u:h,s.length-=h;i[o++]=_[g++],--h;);0===s.length&&(s.mode=21);break;case 26:if(0===u)break e;i[o++]=s.length,u--,s.mode=21;break;case 27:if(s.wrap){for(;c<32;){if(0===a)break e;a--,l|=r[n++]<<c,c+=8}if(p-=u,e.total_out+=p,s.total+=p,p&&(e.adler=s.check=(s.flags?G:b)(s.check,i,p,o-p)),p=u,(s.flags?l:q(l))!==s.check){e.msg="incorrect data check",s.mode=30;break}c=l=0}s.mode=28;case 28:if(s.wrap&&s.flags){for(;c<32;){if(0===a)break e;a--,l+=r[n++]<<c,c+=8}if(l!==(4294967295&s.total)){e.msg="incorrect length check",s.mode=30;break}c=l=0}s.mode=29;case 29:M=1;break e;case 30:M=-3;break e;case 31:return-4;default:return k}return e.next_out=o,e.avail_out=u,e.next_in=n,e.avail_in=a,s.hold=l,s.bits=c,(s.wsize||p!==e.avail_out&&s.mode<30&&(s.mode<27||4!==t))&&j(e,e.output,e.next_out,p-e.avail_out)?(s.mode=31,-4):(d-=e.avail_in,p-=e.avail_out,e.total_in+=d,e.total_out+=p,s.total+=p,s.wrap&&p&&(e.adler=s.check=(s.flags?G:b)(s.check,i,p,e.next_out-p)),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===p||4===t)&&M===U?-5:M)},s.inflateEnd=function(e){var t;return e&&e.state?((t=e.state).window&&(t.window=null),e.state=null,U):k},s.inflateGetHeader=function(e,t){return e&&e.state&&2&(e=e.state).wrap?((e.head=t).done=!1,U):k},s.inflateSetDictionary=function(e,t){var s,r=t.length;return!e||!e.state||0!==(s=e.state).wrap&&11!==s.mode?k:11===s.mode&&b(1,t,r,0)!==s.check?-3:j(e,t,r,r)?(s.mode=31,-4):(s.havedict=1,U)},s.inflateInfo="pako inflate (from Nodeca project)"},{"../utils/common":1,"./adler32":3,"./crc32":5,"./inffast":7,"./inftrees":9}],9:[function(e,t,s){var P=e("../utils/common"),w=[3,4,5,6,7,8,9,10,11,13,15,17,19,23,27,31,35,43,51,59,67,83,99,115,131,163,195,227,258,0,0],U=[16,16,16,16,16,16,16,16,17,17,17,17,18,18,18,18,19,19,19,19,20,20,20,20,21,21,21,21,16,72,78],k=[1,2,3,4,5,7,9,13,17,25,33,49,65,97,129,193,257,385,513,769,1025,1537,2049,3073,4097,6145,8193,12289,16385,24577,0,0],F=[16,16,16,16,17,17,18,18,19,19,20,20,21,21,22,22,23,23,24,24,25,25,26,26,27,27,28,28,29,29,64,64];t.exports=function(e,t,s,r,i,n,o,a){for(var u,l,c,d,p,h,g,_,m,v=a.bits,f=0,I=0,E=0,C=0,S=0,M=0,y=0,T=0,A=0,O=0,D=null,R=0,L=new P.Buf16(16),N=new P.Buf16(16),b=null,G=0,f=0;f<=15;f++)L[f]=0;for(I=0;I<r;I++)L[t[s+I]]++;for(S=v,C=15;1<=C&&0===L[C];C--);if(C<S&&(S=C),0===C)i[n++]=20971520,i[n++]=20971520,a.bits=1;else{for(E=1;E<C&&0===L[E];E++);for(S<E&&(S=E),f=T=1;f<=15;f++)if((T=(T<<1)-L[f])<0)return-1;if(0<T&&(0===e||1!==C))return-1;for(N[1]=0,f=1;f<15;f++)N[f+1]=N[f]+L[f];for(I=0;I<r;I++)0!==t[s+I]&&(o[N[t[s+I]]++]=I);if(h=0===e?(D=b=o,19):1===e?(D=w,R-=257,b=U,G-=257,256):(D=k,b=F,-1),f=E,p=n,y=I=O=0,c=-1,d=(A=1<<(M=S))-1,1===e&&852<A||2===e&&592<A)return 1;for(;;){for(m=o[I]<h?(_=0,o[I]):o[I]>h?(_=b[G+o[I]],D[R+o[I]]):(_=96,0),u=1<<(g=f-y),E=l=1<<M;i[p+(O>>y)+(l-=u)]=g<<24|_<<16|m,0!==l;);for(u=1<<f-1;O&u;)u>>=1;if(0!==u?O=(O&u-1)+u:O=0,I++,0==--L[f]){if(f===C)break;f=t[s+o[I]]}if(S<f&&(O&d)!==c){for(p+=E,T=1<<(M=f-(y=0===y?S:y));M+y<C&&!((T-=L[M+y])<=0);)M++,T<<=1;if(A+=1<<M,1===e&&852<A||2===e&&592<A)return 1;i[c=O&d]=S<<24|M<<16|p-n}}0!==O&&(i[p+O]=f-y<<24|64<<16),a.bits=S}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"),p=e("./utils/common"),h=e("./utils/strings"),g=e("./zlib/constants"),r=e("./zlib/messages"),i=e("./zlib/zstream"),n=e("./zlib/gzheader"),_=Object.prototype.toString;function o(e){if(!(this instanceof o))return new o(e);this.options=p.assign({chunkSize:16384,windowBits:0,to:""},e||{});var t=this.options,e=(t.raw&&0<=t.windowBits&&t.windowBits<16&&(t.windowBits=-t.windowBits,0===t.windowBits)&&(t.windowBits=-15),!(0<=t.windowBits&&t.windowBits<16)||e&&e.windowBits||(t.windowBits+=32),15<t.windowBits&&t.windowBits<48&&!(15&t.windowBits)&&(t.windowBits|=15),this.err=0,this.msg="",this.ended=!1,this.chunks=[],this.strm=new i,this.strm.avail_out=0,d.inflateInit2(this.strm,t.windowBits));if(e!==g.Z_OK)throw new Error(r[e]);if(this.header=new n,d.inflateGetHeader(this.strm,this.header),t.dictionary&&("string"==typeof t.dictionary?t.dictionary=h.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 o(t);if(t.push(e,!0),t.err)throw t.msg||r[t.err];return t.result}o.prototype.push=function(e,t){var s,r,i,n,o,a=this.strm,u=this.options.chunkSize,l=this.options.dictionary,c=!1;if(this.ended)return!1;r=t===~~t?t:!0===t?g.Z_FINISH:g.Z_NO_FLUSH,"string"==typeof e?a.input=h.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 p.Buf8(u),a.next_out=0,a.avail_out=u),(s=(s=d.inflate(a,g.Z_NO_FLUSH))===g.Z_NEED_DICT&&l?d.inflateSetDictionary(this.strm,l):s)===g.Z_BUF_ERROR&&!0===c&&(s=g.Z_OK,c=!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?(i=h.utf8border(a.output,a.next_out),n=a.next_out-i,o=h.buf2string(a.output,i),a.next_out=n,a.avail_out=u-n,n&&p.arraySet(a.output,a.output,i,n,0),this.onData(o)):this.onData(p.shrinkBuf(a.output,a.next_out))),0===a.avail_in&&0===a.avail_out&&(c=!0),(0<a.avail_in||0===a.avail_out)&&s!==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))},o.prototype.onData=function(e){this.chunks.push(e)},o.prototype.onEnd=function(e){e===g.Z_OK&&("string"===this.options.to?this.result=this.chunks.join(""):this.result=p.flattenChunks(this.chunks)),this.chunks=[],this.err=e,this.msg=this.strm.msg},s.Inflate=o,s.inflate=a,s.inflateRaw=function(e,t){return(t=t||{}).raw=!0,a(e,t)},s.ungzip=a},{"./utils/common":1,"./utils/strings":2,"./zlib/constants":4,"./zlib/gzheader":6,"./zlib/inflate":8,"./zlib/messages":10,"./zlib/zstream":11}]},{},[])("/lib/inflate.js"),xt=new class{constructor(){this._socketAdapter=null,this._url="",this._isReconnecting=!1,this._pendingRequests=new Map,this._nextHeartbeatAt=0,this._lastDiagnoseAt=0,this._isHeartbeatInProgress=!1,this._connectionEstablishedTime=0,this._connectionStartTime=0,this._connectionId=-1,this._isBinarySupported=!0,this._intendedDelay=1e3,this._currentConnectState=Pt,this._beforeSendInterceptors=[]}init(){gt.addTask({id:bt,intervalMs:1e3,callback:this._executeScheduledTaskIfReady,context:this}),this._updateIsBinarySupported(),this._url=function(e){var{sdkAppId:t,testEnv:s,disableIndependentDomain:r}=c.get("instance"),i=ut(t);let n="";return s?n=ot.TEST[i].DEFAULT:r?(n=ot.PRODUCTION[i].DEFAULT,ct=a.DEFAULT):n=ot.PRODUCTION[i].INITIAL.replace("*",""+t),dt(n,{isBinary:e})}(this._isBinarySupported),J.subscribeInnerEvent("networkStatusChange",this._handleNetworkStatusChange,this),J.subscribeInnerEvent("activityStatusChange",this._handleActivityStatusChange,this),this.connect()}sendPacket(e,t){var s,{requestId:r,timeout:i=15e3,canResend:n=!0}=t||{};if(ze(e))return Nt.warn("sendPacket",u+".sendPacket: packet is empty "),null;this._executeBeforeSendInterceptors(e),this._currentConnectState===wt&&this._handleConnectStateChange({state:wt,shouldEmitEvent:!0,shouldAttemptReconnect:!0,reason:"send_fail"});var o=JSON.stringify(e);let a=null;if(r){let{resolve:e,reject:t,promise:s}=Xe();a=s,this._pendingRequests.set(r,{resolve:e,reject:t,timestamp:Date.now(),uplinkData:o,timeout:i,canResend:n})}t=this._isBinarySupported?_t(o).buffer:o;return null!=(s=this._socketAdapter)&&s.send(t),a}connect(){this._socketAdapter=new nt(this._url),this._connectionEstablishedTime=0,this._addEventListeners(),this._connectionStartTime=Date.now();var e=null==(e=this._socketAdapter)?void 0:e.getId(),t=u+`.connect isWorkerEnabled: false socketID:${e} url:`+this._url;this._connectionId=e,this._ssoLog({method:"connect",message:t})}disconnect(){var e=null==(e=this._socketAdapter)?void 0:e.getId(),e=u+".disconnect socketID:"+e;this._ssoLog({method:"disconnect",message:e}),this._removeEventListeners(),null!=(e=this._socketAdapter)&&e.disconnect()}getSocketAdapter(){return this._socketAdapter}dispose(){console.log(u+".dispose"),gt.removeTask(bt),gt.removeTask(Gt),J.unSubscribeInnerEvent("networkStatusChange",this._handleNetworkStatusChange,this),J.unSubscribeInnerEvent("activityStatusChange",this._handleActivityStatusChange,this),this.disconnect(),this._socketAdapter=null,this._isReconnecting=!1,this._isHeartbeatInProgress=!1,this._pendingRequests.clear(),this._nextHeartbeatAt=0,this._lastDiagnoseAt=0,this._intendedDelay=1e3,this._url=""}registerBeforeSendInterceptor(e,t){this._beforeSendInterceptors.push(e.bind(t))}_executeBeforeSendInterceptors(e){for(var t of this._beforeSendInterceptors){var{servcmd:s=""}=null==e?void 0:e.head;t(s.includes(".")?s.split(".").pop():"")}}_shouldSkipReconnect(){var e="connecting"===this._currentConnectState&&this._isReconnecting;return!this._socketAdapter||e}reconnect(){return I(this,void 0,void 0,function*(){var e=u+`.reconnect isReconnecting: ${this._isReconnecting} currentConnectState: `+this._currentConnectState;if(this._ssoLog({method:"reconnect",message:e}),!this._shouldSkipReconnect()){this._url=pt(this._isBinarySupported);try{this._isReconnecting=!0,this.disconnect(),this.connect()}catch(e){this._isReconnecting=!1,this._handleConnectStateChange({state:wt,shouldEmitEvent:!0,shouldAttemptReconnect:!0,reason:"reconnect_failed"}),console.warn(u+".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=u+`.onClose closeSocketID: ${e} currentSocketID: ${this._connectionId} connectionDuration: ${s} code: ${null==t?void 0:t.code} reason: `+(null==t?void 0:t.reason);this._ssoLog({method:"onClose",message:s}),e===this._connectionId&&this._handleConnectStateChange({state:wt,shouldEmitEvent:!0,shouldAttemptReconnect:!0,reason:"socket_close"}),this._isReconnecting&&(this._isReconnecting=!1)}_onError(e){var{socketId:e,error:t}=e||{},t=u+`.onError sourceSocketID: ${e} currentSocketID: ${this._connectionId} isReconnecting: ${this._isReconnecting} error: `+JSON.stringify(t);this._ssoLog({method:"onError",message:t}),e===this._connectionId&&this._handleConnectStateChange({state:wt,shouldEmitEvent:!0,shouldAttemptReconnect:!0,reason:"socket_error"}),this._isReconnecting&&(this._isReconnecting=!1)}_onSendFail(e){var{socketId:e,error:t}=e||{},e=u+`.onSendFail sendFailSocketId: ${e} currentSocketID: ${this._connectionId} isReconnecting: ${this._isReconnecting} error: `+t;this._ssoLog({method:"onSendFail",message:e}),this._isReconnecting&&(this._isReconnecting=!1)}_onMessage(t){let s,e;this._updateHeartbeatTime();try{s=this._isBinarySupported?(this._isCompressedData(t.data)?e=>{var t=new Uint8Array(e).slice(4);let s;try{s=qt.inflate(t,{to:"string"})}catch(e){console.error("inflate error",e)}return s}:function(e){var i=new Uint8Array(e);let n="",o=0;for(var a=i["length"];o<a;){let t=i[o],s=0,r=0;if(t<=127?(s=0,r=255&t):t<=223?(s=1,r=31&t):t<=239?(s=2,r=15&t):t<=244&&(s=3,r=7&t),0<a-o-s)for(let e=0;e<s;e+=1)t=i[o+e+1],r=r<<6|63&t;else r=65533,s=a-o;n+=String.fromCodePoint(r),o+=s+1}return n})(t.data):t.data,e=JSON.parse(s)}catch(s){let e=t.data;return void this._ssoLog({method:"jsonParseError",message:e})}var r;e&&e.head&&({seq:t,servcmd:r}=e.head,this._pendingRequests.has(""+t+r)?this._handleRequestResponse(e):this._handlePushMessage(e))}_handleRequestResponse(e){var{seq:t,servcmd:s}=e.head,{int32_error_code:r,str_error_message:i}=(null==e?void 0:e.body)||{},n=(null==(n=null==e?void 0:e.body)?void 0:n.ErrorCode)||r,r=(null==(r=null==e?void 0:e.body)?void 0:r.ErrorInfo)||i,i=""+t+s,{resolve:t,reject:s}=this._pendingRequests.get(i);this._pendingRequests.delete(i),n&&0!==n?(J.emitInnerEvent("error",{errorCode:n,errorInfo:r}),s({errorCode:n,errorInfo:r})):t(e.body)}_handlePushMessage(e){var t=e.head["servcmd"],{NeedAck:s,SessionData:r}=e.body;1===s&&this._sendAck(r),J.emitInnerEvent(t,e)}_checkPendingRequestsAndResend(){var e;Nt.debug("_checkPendingRequestsAndResend",` reConnectFlag:${this._isReconnecting} promiseMap.size:`+this._pendingRequests.size),null!=(e=this._pendingRequests)&&e.forEach((e,t)=>{var{uplinkData:s,canResend:r,resolve:i,reject:n,timeout:o}=e;if(r){this._pendingRequests.set(t,{resolve:i,reject:n,timestamp:Date.now(),uplinkData:s,timeout:o,canResend:r});let e=this._isBinarySupported?_t(s).buffer:s;null!=(i=this._socketAdapter)&&i.send(e)}else this._pendingRequests.delete(t)})}_onConnect(e){var{socketId:e,event:t={}}=e||{},s=(this._connectionId=e,this._connectionEstablishedTime=Date.now(),Date.now()-this._connectionStartTime),s=u+`.onConnect cost:${s} ms. socketID:${e} res:`+JSON.stringify(t);if(this._ssoLog({method:"onConnect",message:s}),this._checkPendingRequestsAndResend(),this._sendHeartbeatIfReady(),this._isReconnecting){u;this._ssoLog({method:"reconnectSuccess",message:"Channel.reconnect success"}),J.emitInnerEvent(At.RECONNECTED),this._isReconnecting=!1}this._resetReconnectDelay(),this._handleConnectStateChange({state:Pt,shouldEmitEvent:!0,shouldAttemptReconnect:!1})}_sendAck(e){e=ft({servcmd:"openim.ws_msg_push_ack",data:{SessionData:e}});this.sendPacket(e)}_executeScheduledTaskIfReady(){return I(this,void 0,void 0,function*(){this._clearTimeoutRequest(),this._sendHeartbeatIfReady()})}_canSendHeartbeat(){var e;return(null==(e=this._socketAdapter)?void 0:e.isConnected())&&Date.now()>=this._nextHeartbeatAt&&!this._isHeartbeatInProgress}_sendHeartbeat(){return I(this,void 0,void 0,function*(){var e,t=ft({servcmd:"heartbeat.alive",data:{}});try{let e=""+t.head.seq+t.head.servcmd;yield this.sendPacket(t,{requestId:e,timeout:3e3})}catch(t){var s=null==(e=c.get("netWorkMonitor"))?void 0:e.isNetWorkOnline,s=u+`.sendHeartbeat failed. isNetWorkOnline:${s} error: `+t;this._ssoLog({method:"sendHeartbeatError",message:s}),this._handleConnectStateChange({state:wt,shouldEmitEvent:!0,shouldAttemptReconnect:!0})}})}_sendHeartbeatIfReady(){return I(this,void 0,void 0,function*(){this._canSendHeartbeat()&&(this._isHeartbeatInProgress=!0,yield this._sendHeartbeat(),this._isHeartbeatInProgress=!1)})}_updateHeartbeatTime(){this._nextHeartbeatAt=me?Date.now()+5e3:Date.now()+1e4}_handleNetworkStatusChange(e){var t=u+".networkStatusChange "+JSON.stringify(e),{isNetworkOnline:t,networkType:e}=(this._ssoLog({method:"networkStatusChange",message:t}),e);t&&"none"!==e?this._handleConnectStateChange({state:Pt,shouldEmitEvent:!1,shouldAttemptReconnect:!0,reason:Ut}):this._handleConnectStateChange({state:wt,shouldEmitEvent:!1,shouldAttemptReconnect:!0,reason:Ut})}isPrivateNetWork(){var e=c.get("instance")||{};return e.proxyServer&&!e.fileDownloadProxy}_handleConnectStateChange(e){var{state:e,shouldAttemptReconnect:t,shouldEmitEvent:s,reason:r}=e,r=u+`._handleConnectStateChange currentConnectState: ${this._currentConnectState} shouldAttemptReconnect: ${t} shouldEmitEvent: ${s} reason: `+r;this._currentConnectState!==e&&(this._ssoLog({method:"handleConnectStateChange",message:r}),s&&(Nt.info("_handleConnectStateChange",` from ${this._currentConnectState} to `+e),J.emitOuterEvent("netStateChange",{name:"netStateChange",data:{state:e}}),(this._currentConnectState=e)===wt)&&J.emitInnerEvent(At.SOCKET_DISCONNECTED),t)&&(this._resetReconnectDelay(),gt.addTask({id:Gt,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=u+`.activityStatusChange ${JSON.stringify(e)} readyState: `+t;this._ssoLog({method:"activityStatusChange",message:e}),3===t&&this._handleConnectStateChange({state:wt,shouldEmitEvent:!0,shouldAttemptReconnect:!0,reason:"activity_status_change"})}_resetReconnectDelay(){var e;Nt.debug(u+"._resetReconnectDelay"),gt.removeTask(Gt),null!=(e=c.get("activityMonitor"))&&e.isActive;this._intendedDelay=1e3}_scheduleReconnectWithBackoff(){var e=null==(e=c.get("activityMonitor"))?void 0:e.isActive,e=(this._intendedDelay=e?Math.min(5e3,Math.max(1e3,1.5*this._intendedDelay)):Math.min(3e5,Math.max(1e3,1.5*this._intendedDelay)),(new Date).toTimeString().slice(0,8)),e=u+`.scheduleReconnectWithBackoff timeStr: ${e} intendedDelay: `+this._intendedDelay;Nt.debug(e),this.reconnect(),gt.updateTaskInterval(Gt,this._intendedDelay)}_ssoLog(e){var{method:e,message:t}=e;Nt.info(e,t)}_diagnose(){this.isPrivateNetWork()||(this._lastDiagnoseAt=Date.now(),function(t){I(this,void 0,void 0,function*(){var e=t.split("/")[2];if(e.startsWith("ws")){e=`https://${e}/v3/netcheck/getconninfo?${t.slice(t.indexOf("info?")+5)}&reqtime=`+Date.now();try{yield $e({method:"GET",url:e,data:{}})}catch(e){Nt.warn("diagnoseBySSO","diagnoseBySSO failed. error:"+e.message)}}})}(this._url),function(t){I(this,void 0,void 0,function*(){var e=`https://boce-cdn.my-imcloud.com/v3/netcheck/getconninfo?${t.slice(t.indexOf("info?")+5)}&reqtime=`+Date.now();try{yield $e({method:"GET",url:e,data:{}})}catch(e){Nt.warn("diagnoseByCDN', 'diagnoseByCDN failed. error:"+e.message)}})}(this._url),this._beforeSendInterceptors=[])}_clearTimeoutRequest(){for(var[e,t]of this._pendingRequests.entries()){var{reject:t,timestamp:s,timeout:r}=t;Date.now()-s>=r&&(this._pendingRequests.delete(e),3e4<=Date.now()-this._lastDiagnoseAt&&this._diagnose(),t({errorCode:2801,errorInfo:"NETWORK_TIMEOUT",data:{requestId:e}}))}}_updateIsBinarySupported(){var e;(null!=(e=c.get("instance"))&&e.devMode||(e=He(),ge)||le&&"windows"===e||me)&&(this._isBinarySupported=!1)}_isCompressedData(e){e=new Uint8Array(e);return 67===e[0]&&79===e[1]&&77===e[2]&&80===e[3]}};let k={init:function(e){c.set("instance",e),xt.init()},destroy:function(){xt.dispose(),c.clear(),gt.dispose()},notificationCenter:J,channel:xt,store:c,ssoLog:Nt,utils:t,common:n,constants:e},Vt=e=>"function"==typeof e;function Bt(t,s,r){let i=r||[];var e,n;return!(!t||!s)&&(e=Object.keys(t).filter(e=>!i.includes(e)),n=Object.keys(s).filter(e=>!i.includes(e)),e.length===n.length)&&e.every(e=>!!s.hasOwnProperty(e)&&("object"==typeof t[e]&&null!==t[e]?Bt(t[e],s[e],r):t[e]===s[e]))}(_=b=b||{}).SDK_READY="sdkStateReady",_.SDK_NOT_READY="sdkStateNotReady",_.SDK_DESTROY="sdkDestroy",_.MESSAGE_RECEIVED="onMessageReceived",_.ROOM_CUSTOM_DATA_RECEIVED="onRoomCustomDataReceived",_.MESSAGE_MODIFIED="onMessageModified",_.MESSAGE_REVOKED="onMessageRevoked",_.MESSAGE_READ_BY_PEER="onMessageReadByPeer",_.MESSAGE_READ_RECEIPT_RECEIVED="onMessageReadReceiptReceived",_.MESSAGE_EXTENSIONS_UPDATED="onMessageExtensionsUpdated",_.MESSAGE_EXTENSIONS_DELETED="onMessageExtensionsDeleted",_.MESSAGE_REACTIONS_UPDATED="onMessageReactionsUpdated",_.CONVERSATION_LIST_UPDATED="onConversationListUpdated",_.TOTAL_UNREAD_MESSAGE_COUNT_UPDATED="onTotalUnreadMessageCountUpdated",_.CONVERSATION_GROUP_LIST_UPDATED="onConversationGroupListUpdated",_.CONVERSATION_IN_GROUP_UPDATED="onConversationInGroupUpdated",_.GROUP_LIST_UPDATED="onGroupListUpdated",_.GROUP_ATTRIBUTES_UPDATED="groupAttributesUpdated",_.GROUP_COUNTER_UPDATED="onGroupCounterUpdated",_.TOPIC_CREATED="onTopicCreated",_.TOPIC_DELETED="onTopicDeleted",_.TOPIC_UPDATED="onTopicUpdated",_.PROFILE_UPDATED="onProfileUpdated",_.USER_STATUS_UPDATED="onUserStatusUpdated",_.BLACKLIST_UPDATED="blacklistUpdated",_.FRIEND_LIST_UPDATED="onFriendListUpdated",_.FRIEND_GROUP_LIST_UPDATED="onFriendGroupListUpdated",_.FRIEND_APPLICATION_LIST_UPDATED="onFriendApplicationListUpdated",_.MY_FOLLOWERS_LIST_UPDATED="onMyFollowersListUpdated",_.MY_FOLLOWING_LIST_UPDATED="onMyFollowingListUpdated",_.MUTUAL_FOLLOWERS_LIST_UPDATED="onMutualFollowersListUpdated",_.KICKED_OUT="kickedOut",_.ERROR="error",_.NET_STATE_CHANGE="netStateChange",_.ALL_RECEIVE_MESSAGE_OPT_UPDATED="onAllReceiveMessageOptUpdated",_.SERVER_CONFIG_UPDATED="onServerConfigUpdated",_.PINNED_GROUP_MESSAGE_UPDATED="onPinnedGroupMessageUpdated";var jt=b;(N=dr=dr||{}).LOGOUT="logout",N.DESTROY="destroy",N.CLOUD_CONFIG_UPDATE="cloud_config_update",N.PROFILE_UPDATE="profile_updated",N.ERROR="error",N.RECONNECTED="reconnected",N.FORCE_OFFLINE="im_open_status.stat_forceoffline",N.COMMERCIAL_CONFIG_PUSH="im_sdk_config_mgr.push_imsdk_purchase_bitsv2",N.OVERLOAD_PUSH="OverLoadPush.notify2",N.NEW_MESSAGE="new_message",N.MESSAGE_PUSH="im_open_push.msg_push",N.MESSAGE_DELETED="message_deleted",N.MESSAGE_REVOKED="message_revoked",N.MESSAGE_MODIFIED="message_modified",N.SOCKET_DISCONNECTED="socket_disconnected",N.CONVERSATION_UPDATED="conversation_updated",N.TOPIC_MESSAGE_DELETED="topic_message_deleted",N.TOPIC_MESSAGE_REVOKED="topic_message_revoked",N.TOPIC_MESSAGE_MODIFIED="topic_message_modified",N.TOPIC_NEW_MESSAGE="topic_new_message",N.QUALITY_STAT="quality_stat",N.SYNC_CONVERSATION_LIST="sync_conversation_list";var Kt,Wt,d=dr,Ht=((t=yi=yi||{}).NEW_INVITATION_RECEIVED="newInvitationReceived",t.INVITEE_ACCEPTED="ts_invitee_accepted",t.INVITEE_REJECTED="ts_invitee_rejected",t.INVITATION_CANCELLED="ts_invitation_cancelled",t.INVITATION_TIMEOUT="ts_invitation_timeout",t.INVITATION_MODIFIED="ts_invitation_modified",yi);let Yt=Object.assign({},{KICKED_OUT_MULT_ACCOUNT:"multipleAccount",KICKED_OUT_MULT_DEVICE:"multipleDevice",KICKED_OUT_USERSIG_EXPIRED:"userSigExpired",KICKED_OUT_REST_API:"REST_API_Kick"}),$t={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"},zt=((n=Kt=Kt||{}).UNSENT="unSend",n.SUCCESS="success",n.FAIL="fail",{modify:d.MESSAGE_MODIFIED,delete:d.MESSAGE_DELETED,revoke:d.MESSAGE_REVOKED}),Jt=((e=Wt=Wt||{})[e.FORWARD=0]="FORWARD",e[e.BACKWARD=1]="BACKWARD",Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},$t),{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:Kt,Direction:Wt})),Qt={[zt.modify]:d.TOPIC_MESSAGE_MODIFIED,[zt.delete]:d.TOPIC_MESSAGE_DELETED,[zt.revoke]:d.TOPIC_MESSAGE_REVOKED},Xt={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"},Zt=Object.assign({},Xt),es={CONV_C2C:"C2C",CONV_GROUP:"GROUP",CONV_TOPIC:"TOPIC",CONV_SYSTEM:"@TIM#SYSTEM"},ts=Object.assign(Object.assign(Object.assign(Object.assign({},es),{CONV_AT_ME:1,CONV_AT_ALL:2,CONV_AT_ALL_AT_ME:3}),{CONV_MARK_TYPE_STAR:1,CONV_MARK_TYPE_UNREAD:2,CONV_MARK_TYPE_FOLD:4,CONV_MARK_TYPE_HIDE:8}),{READ_ALL_C2C_MSG:"readAllC2CMessage",READ_ALL_GROUP_MSG:"readAllGroupMessage",READ_ALL_MSG:"readAllMessage"}),ss=Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},{SNS_TYPE_NO_RELATION:"CheckResult_Type_NoRelation",SNS_TYPE_A_WITH_B:"CheckResult_Type_AWithB",SNS_TYPE_B_WITH_A:"CheckResult_Type_BWithA",SNS_TYPE_BOTH_WAY:"CheckResult_Type_BothWay"}),{ALLOW_TYPE_ALLOW_ANY:"AllowType_Type_AllowAny",ALLOW_TYPE_NEED_CONFIRM:"AllowType_Type_NeedConfirm",ALLOW_TYPE_DENY_ANY:"AllowType_Type_DenyAny"}),{SNS_ADD_TYPE_SINGLE:"Add_Type_Single",SNS_ADD_TYPE_BOTH:"Add_Type_Both"}),{SNS_DELETE_TYPE_SINGLE:"Delete_Type_Single",SNS_DELETE_TYPE_BOTH:"Delete_Type_Both"}),{SNS_APPLICATION_TYPE_BOTH:"Pendency_Type_Both",SNS_APPLICATION_SENT_TO_ME:"Pendency_Type_ComeIn",SNS_APPLICATION_SENT_BY_ME:"Pendency_Type_SendOut",SNS_APPLICATION_AGREE:"Response_Action_Agree",SNS_APPLICATION_AGREE_AND_ADD:"Response_Action_AgreeAndAdd"}),{SNS_CHECK_TYPE_BOTH:"CheckResult_Type_Both",SNS_CHECK_TYPE_SINGLE:"CheckResult_Type_Single"}),{FORBID_TYPE_NONE:"AdminForbid_Type_None",FORBID_TYPE_SEND_OUT:"AdminForbid_Type_SendOut"}),rs={GRP_WORK:"Private",GRP_PUBLIC:"Public",GRP_MEETING:"ChatRoom",GRP_AVCHATROOM:"AVChatRoom",GRP_COMMUNITY:"Community",GRP_ROOM:"Room",GRP_LIVE:"Live"},is={COMMUNITY:"@TGS#_",TOPIC:"@TOPIC#_"},ns={JOINED:1,QUITTED:2,KICKED:3,ADMIN_SET:4,ADMIN_CANCELED:5,GROUP_PROFILE_UPDATED:6,GROUP_MEMBER_PROFILE_UPDATED:7,TOPIC_PROFILE_UPDATED:8},os=Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},rs),{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:is,GROUP_TIPS_OPERATION_TYPE:ns}),S=Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},Yt),Jt),Zt),ts),ss),os),{IOS_OFFLINE_PUSH_NO_SOUND:"push.no_sound",IOS_OFFLINE_PUSH_DEFAULT_SOUND:"default"}),{NET_STATE_CONNECTING:"connecting",NET_STATE_DISCONNECTED:"disconnected"}),as={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},us={BASIC:"1",STANDARD:"2",PROFESSIONAL:"3"},p={SYNC_SERVER_INFO_AFTER_RE_ONLINE:"sync-server-info-after-re-online",SYNC_SERVER_INFO_AFTER_LOGIN:"sync-server-info-after-login",RECEIVE_C2C_NEW_MESSAGE:"receive-c2c-new-message",RECEIVE_GROUP_NEW_MESSAGE:"receive-group-new-message",RECEIVE_GROUP_TIPS_NOTIFICATION:"receive-group-tips-notification"},o={USER_STATUS_UPDATE:"user-status-update",CONVERSATION_RECOVER:"conversation-recover",HISTORY_MESSAGE_RECOVER:"history-message-recover",BLACKLIST_RECOVER:"blacklist-recover",FRIEND_RECOVER:"friend-recover",GROUP_ATTRIBUTE_CACHE_CLEAR:"group-attribute-cache-clear",UNREAD_MESSAGE_RECOVER:"unread-message-recover",HANDLE_NEW_MESSAGE:"handle-new-message",HANDLE_CONVERSATION_PROFILE_UPDATED:"handle-conversation-profile-updated",COMMERCIAL_CONFIG_UPDATE:"commercial-config-update",UNREAD_MESSAGE_SYNC:"unread-message-sync",FRIEND_AND_BLACKLIST_SYNC:"friend-and-blacklist-sync",SIGNALING_MESSAGE_RECOVER:"signaling-message-recover",GROUP_LIST_SYNC:"group-list-sync",CONVERSATION_LIST_SYNC:"conversation-list-sync",USER_PROFILE_SYNC:"user-profile-sync",CONVERSATION_UPDATE_AFTER_UNREAD_SYNC_FINISHED:"conversation-update-after-unread-sync-finished",CONVERSATION_UPDATE_AFTER_GROUP_LIST_SYNC_FINISHED:"conversation-update-after-group-list-sync-finished",HANDLE_C2C_NEW_MESSAGE:"handle-c2c-new-message",HANDLE_GROUP_NEW_MESSAGE:"handle-group-new-message",CREATE_OR_UPDATE_CONVERSATION_BY_RECEIVE_NEW_MESSAGE:"create-or-update-conversation-by-receive-new-message",HANDLE_GROUP_TIPS_FROM_SYNC_UNREAD:"handle-group-tips-from-sync-unread",HANDLE_C2C_REVOKED_MESSAGE_FROM_SYNC_UNREAD:"handle-c2c-revoked-message-from-sync-unread",GROUP_REVOKED_NOTICE_RECOVER:"group-revoked-notice-recover",CLOUD_CONFIG_SYNC:"cloud-config-sync",UPDATE_GROUP_NEXT_SEQUENCE:"update-group-next-sequence",EMIT_C2C_MESSAGE_EVENT:"emit-c2c-message-event",EMIT_GROUP_MESSAGE_EVENT:"emit-group-message-event",CONVERSATION_GROUP_LIST_SYNC:"conversation-group-list-sync",CONVERSATION_GROUP_UPDATE:"conversation-group-update",UPDATE_TOPIC_AFTER_UNREAD_SYNC_FINISHED:"update-topic-after-unread-sync-finished",UPDATE_TOPIC_BY_RECEIVE_NEW_MESSAGE:"update-topic-by-received-new-message",TOPIC_REQUEST_INFO_RESET:"topic-request-info-reset",QUALITY_REPORT:"quality-report",GROUP_TIPS_RECOVER:"group-tips-recover",HANDLE_GROUP_TIPS_NOTIFICATION:"handle-group-tips-notification"},ls={[p.SYNC_SERVER_INFO_AFTER_RE_ONLINE]:[{stepId:o.USER_STATUS_UPDATE},{stepId:o.GROUP_ATTRIBUTE_CACHE_CLEAR},{stepId:o.UNREAD_MESSAGE_SYNC},{stepId:o.CONVERSATION_RECOVER},{stepId:o.HISTORY_MESSAGE_RECOVER,dependency:o.CONVERSATION_RECOVER},{stepId:o.BLACKLIST_RECOVER},{stepId:o.FRIEND_RECOVER},{stepId:o.GROUP_REVOKED_NOTICE_RECOVER,dependency:o.HISTORY_MESSAGE_RECOVER},{stepId:o.GROUP_TIPS_RECOVER,dependency:o.HISTORY_MESSAGE_RECOVER},{stepId:o.TOPIC_REQUEST_INFO_RESET},{stepId:o.HANDLE_C2C_REVOKED_MESSAGE_FROM_SYNC_UNREAD,dependency:o.UNREAD_MESSAGE_SYNC},{stepId:o.HANDLE_GROUP_TIPS_FROM_SYNC_UNREAD,dependency:o.UNREAD_MESSAGE_SYNC},{stepId:o.CONVERSATION_UPDATE_AFTER_UNREAD_SYNC_FINISHED,dependency:[o.UNREAD_MESSAGE_SYNC,o.CONVERSATION_RECOVER]},{stepId:o.EMIT_C2C_MESSAGE_EVENT,dependency:[o.UNREAD_MESSAGE_SYNC,o.CONVERSATION_UPDATE_AFTER_UNREAD_SYNC_FINISHED],skipIfDependencyMissing:!1}],[p.SYNC_SERVER_INFO_AFTER_LOGIN]:[{stepId:o.COMMERCIAL_CONFIG_UPDATE},{stepId:o.CLOUD_CONFIG_SYNC},{stepId:o.USER_PROFILE_SYNC},{stepId:o.UNREAD_MESSAGE_SYNC},{stepId:o.FRIEND_AND_BLACKLIST_SYNC},{stepId:o.GROUP_LIST_SYNC},{stepId:o.CONVERSATION_LIST_SYNC},{stepId:o.SIGNALING_MESSAGE_RECOVER,dependency:o.UNREAD_MESSAGE_SYNC},{stepId:o.UPDATE_TOPIC_AFTER_UNREAD_SYNC_FINISHED,dependency:[o.UNREAD_MESSAGE_SYNC]},{stepId:o.CONVERSATION_UPDATE_AFTER_UNREAD_SYNC_FINISHED,dependency:[o.UNREAD_MESSAGE_SYNC,o.CONVERSATION_LIST_SYNC]},{stepId:o.CONVERSATION_UPDATE_AFTER_GROUP_LIST_SYNC_FINISHED,dependency:[o.GROUP_LIST_SYNC,o.CONVERSATION_LIST_SYNC]},{stepId:o.CONVERSATION_GROUP_LIST_SYNC},{stepId:o.CONVERSATION_GROUP_UPDATE,dependency:[o.CONVERSATION_LIST_SYNC,o.CONVERSATION_GROUP_LIST_SYNC]},{stepId:o.QUALITY_REPORT}],[p.RECEIVE_C2C_NEW_MESSAGE]:[{stepId:o.HANDLE_C2C_NEW_MESSAGE},{stepId:o.UNREAD_MESSAGE_SYNC},{stepId:o.CREATE_OR_UPDATE_CONVERSATION_BY_RECEIVE_NEW_MESSAGE,dependency:o.HANDLE_C2C_NEW_MESSAGE},{stepId:o.EMIT_C2C_MESSAGE_EVENT,dependency:[o.HANDLE_C2C_NEW_MESSAGE,o.CREATE_OR_UPDATE_CONVERSATION_BY_RECEIVE_NEW_MESSAGE],skipIfDependencyMissing:!1},{stepId:o.CONVERSATION_UPDATE_AFTER_UNREAD_SYNC_FINISHED,dependency:[o.UNREAD_MESSAGE_SYNC]}],[p.RECEIVE_GROUP_NEW_MESSAGE]:[{stepId:o.HANDLE_GROUP_NEW_MESSAGE},{stepId:o.CREATE_OR_UPDATE_CONVERSATION_BY_RECEIVE_NEW_MESSAGE,dependency:o.HANDLE_GROUP_NEW_MESSAGE},{stepId:o.UPDATE_GROUP_NEXT_SEQUENCE,dependency:o.HANDLE_GROUP_NEW_MESSAGE},{stepId:o.UPDATE_TOPIC_BY_RECEIVE_NEW_MESSAGE,dependency:o.HANDLE_GROUP_NEW_MESSAGE},{stepId:o.EMIT_GROUP_MESSAGE_EVENT,dependency:[o.HANDLE_GROUP_NEW_MESSAGE,o.CREATE_OR_UPDATE_CONVERSATION_BY_RECEIVE_NEW_MESSAGE],skipIfDependencyMissing:!1}],[p.RECEIVE_GROUP_TIPS_NOTIFICATION]:[{stepId:o.HANDLE_GROUP_TIPS_NOTIFICATION},{stepId:o.CREATE_OR_UPDATE_CONVERSATION_BY_RECEIVE_NEW_MESSAGE,dependency:o.HANDLE_GROUP_TIPS_NOTIFICATION}]},cs={MESSAGE_SEND_SUCCESS_RATE:"messageSendSuccessRate"},ds={TOTAL_COUNT:"sendMessageTotalCount",SUCCESS_COUNT:"sendMessageSuccessCount",FAILED_COUNT:"sendMessageFailedCount",SEND_COST:"sendMessageCost"},ps=["login","getMyProfile","getUserProfile","updateMyProfile","setSelfStatus","getUserStatus","subscribeUserStatus","unsubscribeUserStatus","modifyMessage","deleteGroupMember","dismissGroup","getGroupMemberList","getGroupOnlineMemberCount","joinGroup","markGroupMemberList","quitGroup","searchCloudMessages","searchCloudGroups","searchCloudGroupMembers","searchCloudUsers","getMyFollowingList","getMyFollowersList","getMutualFollowersList","followUser","unfollowUser","getUserFollowInfo","checkFollowType","getFriendProfile","addFriend","deleteFriend","updateFriend","checkFriend","setFriendApplicationRead","createFriendGroup","deleteFriendGroup","addToFriendGroup","removeFromFriendGroup","renameFriendGroup","changeGroupOwner","createGroup","dismissGroup","getGroupList","getGroupOnlineMemberCount","getGroupProfile","searchGroupByID","updateGroupProfile","handleGroupApplication","deleteGroupAttributes","getGroupAttributes","initGroupAttributes","setGroupAttributes","addGroupMember","deleteGroupMember","getGroupMemberList","getGroupMemberProfile","setGroupMemberMuteTime","setGroupMemberNameCard","setGroupMemberRole","deleteMessage","revokeMessage","setMessageExtensions","getMessageExtensions","deleteMessageExtensions","getMessageList","addMessageReaction","removeMessageReaction","clearHistoryMessage","invite","accept","cancel","reject","modifyInvitation","deleteConversation","pinConversation","setMessageRead","setAllMessageRead","getConversationList","getTotalUnreadMessageCount","renameConversationGroup","deleteConversationGroup","markConversation","setConversationCustomData","deleteConversationsFromGroup","addConversationsToGroup","createConversationGroup"];var hs,gs,_s=Object.freeze({__proto__:null,ERROR_CODE:as,InnerEvent:d,NEED_LOG_API:ps,OuterConstant:S,OuterEvent:jt,QUALITY_METRICS:cs,SDK_EDITION:us,SDK_INFO:{VERSION:"1.7.3",APPID:537048168},SEND_MESSAGE_STAT:ds,SignalingEvent:Ht,WORKFLOW_DEFINITIONS:ls,WORKFLOW_NAME:p,WORKFLOW_STEP:o});(_=hs=hs||{})[_.USER_INITIATED=0]="USER_INITIATED",_[_.KICKED_OUT=1]="KICKED_OUT",(b=gs=gs||{})[b.multipleAccount=1]="multipleAccount",b[b.multipleDevice=2]="multipleDevice",b[b.restApi=3]="restApi",(N=ba=ba||{})[N.multipleDevice=3002]="multipleDevice",N[N.multipleAccount=3003]="multipleAccount",N[N.usersigExpired=70001]="usersigExpired",N[N.restApi=20002]="restApi";let ms={[gs.multipleAccount]:"multipleAccount",[gs.multipleDevice]:"multipleDevice",[gs.restApi]:"REST_API_Kick",[ba.multipleAccount]:"multipleAccount",[ba.multipleDevice]:"multipleDevice",[ba.restApi]:"REST_API_Kick",[ba.usersigExpired]:"userSigExpired"},vs="login_online_presence_task",{ERROR:fs,DESTROY:Is,FORCE_OFFLINE:Es}=d,{KICKED_OUT_MULT_ACCOUNT:Cs,KICKED_OUT_MULT_DEVICE:Ss,KICKED_OUT_REST_API:Ms,ACCOUNT_A2KEY_EXPIRED:ys,MSG_A2KEY_EXPIRED:Ts}=as;class As{init(){var e=k["notificationCenter"];e.subscribeInnerEvent(Es,this._handleForceOfflineFromServerPush,this),e.subscribeInnerEvent(fs,Ts,this._handleForceOfflineFromResponse,this),e.subscribeInnerEvent(fs,ys,this._handleForceOfflineFromResponse,this),e.subscribeInnerEvent(fs,Cs,this._handleForceOfflineFromResponse,this),e.subscribeInnerEvent(fs,Ss,this._handleForceOfflineFromResponse,this),e.subscribeInnerEvent(fs,Ms,this._handleForceOfflineFromResponse,this),e.subscribeInnerEvent(Is,this._dispose,this)}_handleForceOfflineFromServerPush(e){var{EventArray:e=[]}=(null==e?void 0:e.body)||{};this._extractKickedOutMessages(e).forEach(e=>{var{KickType:e,NewInstInfo:t}=e["KickoutMsgNotify"];this._processKickedOutReasonInfo({kickedOutReasonCode:e,newInstanceInfo:t})})}_extractKickedOutMessages(e){return e.reduce((e,t)=>[...e,...t.C2cNotifyMsgArray||[]],[]).filter(e=>{return this._isKickedOut(null==(e=null==e?void 0:e.KickoutMsgNotify)?void 0:e.KickType)})}_handleForceOfflineFromResponse(e){e=e.errorCode;this._processKickedOutReasonInfo({kickedOutReasonCode:e})}_processKickedOutReasonInfo(r){return I(this,void 0,void 0,function*(){var e=r["kickedOutReasonCode"],{ssoLog:t,utils:{safeStringify:s}}=k;try{this._logKickedOutEvent(r),yield k.login.loginAction.logout(hs.KICKED_OUT)}catch(e){t.debug("_processKickedOutReasonInfo"," fail "+s(e))}finally{k.notificationCenter.emitOuterEvent(jt.KICKED_OUT,{data:{type:ms[e]},name:jt.KICKED_OUT}),[gs.restApi,ys,Ts].includes(e)&&k.channel.reconnect()}})}_logKickedOutEvent(e){var{kickedOutReasonCode:e,newInstanceInfo:t={}}=e,e=`type:${ms[e]} newInstanceInfo: `+JSON.stringify(t);k.ssoLog.warn("kickedOut",e)}_isKickedOut(e){return[gs.multipleAccount,gs.multipleDevice,gs.restApi].includes(e)}_dispose(){var e=k["notificationCenter"];e.unSubscribeInnerEvent(Es,this._handleForceOfflineFromServerPush,this),e.unSubscribeInnerEvent(fs,ys,this._handleForceOfflineFromResponse,this),e.unSubscribeInnerEvent(fs,Ts,this._handleForceOfflineFromResponse,this),e.unSubscribeInnerEvent(fs,Cs,this._handleForceOfflineFromResponse,this),e.unSubscribeInnerEvent(fs,Ss,this._handleForceOfflineFromResponse,this),e.unSubscribeInnerEvent(fs,Ms,this._handleForceOfflineFromResponse,this),e.unSubscribeInnerEvent(Is,this._dispose,this)}}function Os(r){return I(this,void 0,void 0,function*(){let e="im_open_status.wslogin",t=k.common.generateProtocolData({servcmd:e,data:{State:"Online",is_web_uniapp:0,InstType:0,CustomInfo:r}}),s=""+t.head.seq+e,d=yield k.channel.sendPacket(t,{timeout:9e4,requestId:s});if(d){let{HelloInterval:e,InstId:t,TinyId:s,TimeStamp:r,CustomStatus:i,PurchaseBits:n,A2Key:o,RichMsgAuthKey:a,ErrorCode:u,ErrorInfo:l,ActionStatus:c}=d;return{helloInterval:e,instanceID:t,tinyID:s,timeStamp:r,customStatus:i,purchaseBits:n,a2Key:o,authKey:a,errorCode:u,errorInfo:l,actionStatus:c}}})}function Ds(t){var s;try{var r=c.getStorage("errorMessage");if(!t||!r)return"";var i=(null==(s=JSON.parse(r))?void 0:s.errorMessage)||{},{isIntl:n=!1,code:o,replacement1:a="",replacement2:u=""}=t;if(!o)return"";var l=n?o+"_en":o+"_cn";let e=i[i[l]?l:o]||"";return e=e&&(a&&(e=e.replace("$replacement1",a)),u)?e.replace("$replacement2",u):e}catch(t){return console.warn("Error parsing stored error messages:",t),""}}class m extends Error{constructor(e){var{functionName:t="Unknown",code:s,message:r="",data:i="",moreMessage:n=""}=e;let o=r;s&&!r&&(o=Ds(e));r=(s?`${t} failed. error: {"message": ${o}, "code": ${s}}`:`${t} failed. error: {"message": ${o}}`)+" "+n;super(),this.code=s,this.errorCode=s,this.errorMessage=r,this.message=r,this.data=i}}function Rs(e,t){if(e&&!0!==(null==(e=k.store.get("login"))?void 0:e.isLoggedIn))throw new m({code:as.USER_NOT_LOGGED_IN,functionName:t})}function Ls(t,s,r){if(Array.isArray(t))for(let e=0;e<t.length;e++)Ns.call(this,Object.assign(Object.assign({},t[e]),{value:s[e],name:r}));else for(var e in t)Ns.call(this,Object.assign(Object.assign({},t[e]),{value:s[0][e],name:r,key:e}))}function Ns({required:e,rules:r,value:t,allowEmpty:i,name:n,key:o,customValidator:a}){if(void 0===t){if(e)throw new m({functionName:n,message:`[${n}] Missing required params: "${o}"`})}else{let s="";if(!r.some(e=>{return e===Object.prototype.toString.call(t).match(/^\[object (.*)\]$/)[1].toLowerCase()})){for(let t=0;t<r.length;t++){let e=r[t];e=e.replace(e[0],e[0].toUpperCase()),s+=e+"/"}let e=`[${o}] must be type of ${s=s.substring(0,s.length-1)}, received type: ${Reflect.apply(Object.prototype.toString,t,[]).replace(/^\[object\s(\w+)\]$/,"$1").toLowerCase()}.`;throw new m({functionName:n,message:e})}if(!1===i){if(Array.isArray(t)&&(0===t.length||"string"==typeof t[0]&&""===t[0].trim()))throw new m({functionName:n,message:o+" can not be empty."});if("string"==typeof t&&""===t.trim())throw new m({functionName:n,message:o+" can not be empty."})}if(a&&"function"==typeof a){let e=a(t);if(!0!==e)throw new m({functionName:n,message:`[${o}] custom validation failed: `+(e||"Invalid value")})}}}let bs=[],Gs={},Ps={};function ws(e,t){var s;Rs(Gs[e],e),Ls(Ps[e],t,e),s=e,bs.forEach(e=>{var{interceptor:e,context:t}=e;e.apply(t,[s])})}function Us(e,t){bs.push({interceptor:e,context:t})}function ks(e){var{params:e,auth:t}=e;e&&"object"==typeof e&&Object.assign(Ps,e),t&&"object"==typeof t&&Object.assign(Gs,t)}function Fs(e){return k.store.get("commercialConfig").get(e)}class h{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),k.ssoLog.debug("_executeWorkflowStep",`[Workflow ${e}] Step ${t} started at `+new Date(s).toISOString())):(this._workflowStartTimes.set(e,s),k.ssoLog.debug("_executeWorkflowStep",`[Workflow ${e}] started at `+new Date(s).toISOString()))},success:(s,e)=>{var r=Date.now();if(e){var t=this._stepStartTimes.get(s+"-"+e),t=t?r-t:0;this._stepStartTimes.delete(s+"-"+e),k.ssoLog.debug("_executeWorkflowStep",`[Workflow ${s}] Step ${e} completed successfully at ${new Date(r).toISOString()} (${t}ms)`)}else{let e=this._workflowStartTimes.get(s),t=e?r-e:0;this._workflowStartTimes.delete(s),k.ssoLog.debug("_executeWorkflowStep",`[Workflow ${s}] completed successfully at ${new Date(r).toISOString()} (${t}ms)`)}},error:(s,e,r)=>{var{ssoLog:i,utils:{safeStringify:n}}=k,o=Date.now();if(e){var t=this._stepStartTimes.get(s+"-"+e),t=t?o-t:0;this._stepStartTimes.delete(s+"-"+e),i.error("_executeWorkflowStep",`[Workflow ${s}] Step ${e} failed at ${new Date(o).toISOString()} (${t}ms) `+n(r),{error:r})}else{let e=this._workflowStartTimes.get(s),t=e?o-e:0;this._workflowStartTimes.delete(s),i.error("_executeWorkflowStep",`[Workflow ${s}] failed at ${new Date(o).toISOString()} (${t}ms) `+n(r),{error:r})}}}}static getInstance(){return h._instance||(h._instance=new h),h._instance}static setInstance(e){h._instance=e}init(){this._initializeWorkflows()}registerWorkflowStep(e,t,s,r){var i;this._handlers.has(e)?ls[e].find(e=>e.stepId===t)?(i=this._handlers.get(e)).has(t)||i.set(t,r?s.bind(r):s):k.ssoLog.debug("registerWorkflowStep",`Step '${t}' not defined in workflow '${e}'`):k.ssoLog.debug("registerWorkflowStep",`Workflow '${e}' not defined in core`)}executeWorkflow(o,s){return I(this,void 0,void 0,function*(){if(this._validateWorkflow(o)){k.ssoLog.debug("executeWorkflow",`[Workflow ${o}] Started execution at `+(new Date).toISOString());let e=ls[o],n={cancelled:!1};this._activeWorkflows.set(o,{cancelToken:n});try{let t=new Map,i=(e.forEach(e=>{t.set(e.stepId,e)}),{workflowName:o,pendingSteps:new Set(e.map(e=>e.stepId)),completedSteps:new Set,runningSteps:new Set,stepMap:t,stepResults:{},data:s,cancelToken:n});yield new Promise((t,s)=>{let r=()=>{n.cancelled?t():this._getExecutableSteps({pendingSteps:i.pendingSteps,completedSteps:i.completedSteps,stepMap:i.stepMap,workflowName:o}).filter(e=>!i.runningSteps.has(e)).forEach(e=>{i.completedSteps.has(e)||i.runningSteps.has(e)||this._executeWorkflowStep(e,i,{onComplete:()=>{0===i.pendingSteps.size?t():0===this._getExecutableSteps({pendingSteps:i.pendingSteps,completedSteps:i.completedSteps,stepMap:i.stepMap,workflowName:o}).filter(e=>!i.runningSteps.has(e)).length&&0===i.runningSteps.size&&(k.ssoLog.debug("executeWorkflow",`Workflow ${o} completed with some steps skipped due to dependency failures`),t())},onError:s,onStepComplete:r})})};r()}),k.ssoLog.debug("executeWorkflow",`[Workflow ${o}] Completed execution at `+(new Date).toISOString())}catch(e){k.ssoLog.error("executeWorkflow",`[Workflow ${o}] Failed execution at `+(new Date).toISOString(),{error:e})}finally{this._activeWorkflows.delete(o)}}})}_executeWorkflowStep(a,u,l){return I(this,void 0,void 0,function*(){let{workflowName:n,runningSteps:e,stepMap:s,stepResults:r,data:i}=u;e.add(a),this._logWorkflowExecution(n,a,"start");try{let e=s.get(a),t=null;null!=e&&e.dependency&&(X(e.dependency)?t=r[e.dependency]:Array.isArray(e.dependency)&&(t={},e.dependency.forEach(e=>{t[e]=r[e]})));var o=this._handlers.get(n).get(a);if(o){let e=yield Promise.resolve(o({data:i,result:t}));r[a]=e,this._logWorkflowExecution(n,a,"success")}u.completedSteps.add(a)}catch(e){let t=`[Workflow].${n}.`+a,{errorCode:s,errorInfo:r=t+" failed"}=e||{},i=new m({functionName:t,code:s,message:r});k.ssoLog.error(t,r,{error:i}),this._logWorkflowExecution(n,a,"error",e),l.onError(e)}finally{e.delete(a),u.pendingSteps.delete(a),l.onStepComplete(),l.onComplete()}})}reset(){this._cancelAllWorkflows()}destroy(){this.reset(),this._handlers.clear()}_initializeWorkflows(){Object.keys(ls).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(ls).forEach(e=>{this._cancelWorkFlow(e)})}_validateWorkflow(e){return!!ls[e]&&!!this._handlers.get(e)}_getExecutableSteps(e){let{pendingSteps:t,completedSteps:s,stepMap:r,workflowName:i}=e;return Array.from(t).filter(e=>{var{dependency:t,skipIfDependencyMissing:e=!0}=r.get(e)||{};if(!t)return!0;if(X(t))return this._isStepRegistered({workflowName:i,stepId:t})?s.has(t):!e;if(ee(t)){if(0<t.filter(e=>!this._isStepRegistered({workflowName:i,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===S.GRP_COMMUNITY||(""+t).startsWith(is.COMMUNITY)&&!(""+t).includes(is.TOPIC),Vs=(e="")=>{e=e.startsWith("GROUP")?e.replace("GROUP",""):e;return e.startsWith(is.COMMUNITY)&&(""+e).includes(is.TOPIC)},Bs="openim",js="million_group_open_http_svc";function Ks(s){return I(this,void 0,void 0,function*(){var{servcmd:e,data:t}=Ws(e=s.data)||Hs(e)?function(e){let{servcmd:t,data:s}=e;var r,i,n;return Hs(s)?({servcmd:e,data:r}=e,{GroupId:i=""}=r,[i]=(n=i).split(is.TOPIC),{servcmd:Ys(e),data:Object.assign(Object.assign({},r),{GroupId:i,TopicId:n})}):{servcmd:t=Ws(s)?Ys(t):t,data:s}}(s):s,t=k.common.generateProtocolData({servcmd:e,data:t}),e=""+t.head.seq+e;return k.channel.sendPacket(t,{requestId:e})})}function Ws(e){var{Type:e,GroupId:t,GroupIdList:s=[]}=e,t=t||s[0]||"";return xs({type:e,groupID:t})}function Hs(e){var{GroupId:e=""}=e;return Vs(e)}function Ys(e){return e.includes(Bs)?e:(e=e.split(".")[1],js+"."+e)}function g(){var e;return null==(e=k.store.get("login"))?void 0:e.userId}let $s=e=>ee(e)||te(e),zs=(s,r,i,n)=>{if(!$s(s)||!$s(r))return 0;let o=0;var a,u=Object.keys(r);for(let e=0,t=u.length;e<t;e++)if(a=u[e],!(Q(r[a])||i&&i.includes(a)))if($s(s[a])&&$s(r[a]))o+=zs(s[a],r[a],i,n);else{if(n&&n.includes(r[a]))continue;s[a]!==r[a]&&(s[a]=r[a],o+=1)}return o},Js=(e,t)=>{if(Q(t))return"";switch(e){case S.MSG_TEXT:return t.text||"";case S.MSG_IMAGE:return"[Image]";case S.MSG_LOCATION:return"[Location]";case S.MSG_AUDIO:return"[Voice]";case S.MSG_VIDEO:return"[Video]";case S.MSG_FILE:return"[File]";case S.MSG_CUSTOM:return"[Custom Messages]";case S.MSG_GRP_TIP:return"[Group Notification]";case S.MSG_GRP_SYS_NOTICE:return"[Group System Message]";case S.MSG_FACE:return"[Animated Sticker]";case S.MSG_MERGER:return"[Chat Record]";default:return""}},Qs=[{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}],Xs="im_sdk_config_mgr.fetch_config",Zs="im_sdk_config_mgr.push_configv2",er="cloud-config",tr=new class{init(e){this.core=e}};function sr(s){return I(this,void 0,void 0,function*(){var e=(tr.core.store.get("instance")||{})["sdkAppId"],e=tr.core.helper.generateProtocolData({servcmd:Xs,data:{uint32_sdkappid:e,uint64_version:s}}),t=""+e.head.seq+Xs;return tr.core.channel.sendPacket(e,{requestId:t})})}var rr=new class{constructor(){this._core=null,this._expirationTime=0,this._version=0,this._isFetching=!1,this._cmdFrequencyLimitMap=new Map,this._methodCallFrequencyMap=new Map}install(e){var{notificationCenter:e,InnerEvent:t,helper:s,constants:{WORKFLOW_NAME:r,WORKFLOW_STEP:i},channel:n}=this._core=e;e.subscribeInnerEvent(Zs,this._handlePushedConfig,this),s.registerWorkflowStep(r.SYNC_SERVER_INFO_AFTER_LOGIN,i.CLOUD_CONFIG_SYNC,this._handleLoginSuccess,this),e.subscribeInnerEvent(t.LOGOUT,this._reset,this),e.subscribeInnerEvent(t.DESTROY,this._dispose,this),s.registerExperimentalAPI("getServerConfig",this),this._updateCmdFreqLimitMap(Qs),n.registerBeforeSendInterceptor(this.checkMethodCallOverLimit,this)}getServerConfig(s){return I(this,void 0,void 0,function*(){var e,t={code:0,data:""};return s&&(t.data=(null==(e=this._core.store.get("cloudConfig"))?void 0:e[s])||""),t})}checkMethodCallOverLimit(e){if(this._cmdFrequencyLimitMap.has(e))if(this._methodCallFrequencyMap.has(e)){var{count:t,interval:s}=this._cmdFrequencyLimitMap.get(e),{startTime:r,methodCallCounter:i}=this._methodCallFrequencyMap.get(e);if(Date.now()-r>1e3*s)this._methodCallFrequencyMap.set(e,{startTime:Date.now(),methodCallCounter:1});else if(this._methodCallFrequencyMap.set(e,{startTime:r,methodCallCounter:i+=1}),t<i)throw new this._core.helper.ChatError({code:2996,replacement1:e})}else this._methodCallFrequencyMap.set(e,{startTime:Date.now(),methodCallCounter:1})}_handlePushedConfig(s){return I(this,void 0,void 0,function*(){var{ssoLog:e,utils:{safeStringify:t}}=this._core;e.info("_handlePushedConfig",t(s)),yield this._updateCloudConfig(s)})}_handleLoginSuccess(){return I(this,void 0,void 0,function*(){var e,{ssoLog:t,utils:{safeStringify:s}}=this._core;try{this._canFetch()&&(e=yield sr(this._version),t.info("_fetchCloudConfigIfLogin",s(e)),yield this._updateCloudConfig(e)),this._core.helper.taskScheduler.addTask({id:er,intervalMs:1e3,callback:this._fetchCloudConfigIfReady,context:this})}catch(e){t.error("_fetchCloudConfigIfLogin",s(e))}})}_fetchCloudConfigIfReady(){return I(this,void 0,void 0,function*(){var{ssoLog:t,utils:{safeStringify:s}}=this._core;if(this._canFetch())try{var e=yield sr(this._version);t.info("_fetchCloudConfigIfReady",s(e)),yield this._updateCloudConfig(e)}catch(e){t.error("_fetchCloudConfigIfReady",s(e))}})}_updateCloudConfig(t){return I(this,void 0,void 0,function*(){var e=this._parseCloudConfig(t);e&&(this._core.store.set("cloudConfig",e),yield this._parseCmdFreqLimit(),this._core.notificationCenter.emitInnerEvent(this._core.InnerEvent.CLOUD_CONFIG_UPDATE,e),this._core.notificationCenter.emitOuterEvent(this._core.OuterEvent.SERVER_CONFIG_UPDATED,{name:this._core.OuterEvent.SERVER_CONFIG_UPDATED,data:{config:e}}))})}_canFetch(){var e=(this._core.store.get("login")||{})["isLoggedIn"];return e&&!this._isFetching&&Date.now()>=this._expirationTime}_parseCloudConfig(e){var{int32_error_code:t,str_json_config:s,uint32_expired_time:r,uint64_version:i}=e;let n=null;if(0===t){if(this._version!==i)try{n=JSON.parse(s),this._version=i}catch(e){}this._expirationTime=Date.now()+1e3*r}else this._expirationTime=void 0===t?Date.now()+36e5:Date.now()+12e4;return n}_parseCmdFreqLimit(){return I(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(er),this._core.store.clear("cloudConfig"),this._updateCmdFreqLimitMap(Qs),this._methodCallFrequencyMap.clear(),this._expirationTime=0,this._version=0,this._isFetching=!1}_dispose(){var{notificationCenter:e,InnerEvent:t}=this._core;e.unSubscribeInnerEvent(Zs,this._handlePushedConfig,this),e.unSubscribeInnerEvent(t.LOGOUT,this._reset,this),e.unSubscribeInnerEvent(t.DESTROY,this._dispose,this),this._reset()}};class l{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 ir={SEARCH_GRP_SNS:new l(0,Math.pow(2,1)).toString(),AV_HISTORY_MSG:new l(0,Math.pow(2,2)).toString(),GRP_COMMUNITY:new l(0,Math.pow(2,3)).toString(),MSG_TO_SPECIFIED_GRP_MBR:new l(0,Math.pow(2,4)).toString(),AV_MBR_LIST:new l(0,Math.pow(2,6)).toString(),USER_STATUS:new l(0,Math.pow(2,7)).toString(),CONV_MARK:new l(0,Math.pow(2,9)).toString(),CONV_GROUP:new l(0,Math.pow(2,10)).toString(),AV_BAN_MBR:new l(0,Math.pow(2,11)).toString(),MSG_EXT:new l(0,Math.pow(2,13)).toString(),GRP_COUNTER:new l(0,Math.pow(2,15)).toString(),PLUGIN_TRANSLATE:new l(Math.pow(2,6)).toString(),PLUGIN_VOICE_TO_TEXT:new l(Math.pow(2,7)).toString(),PLUGIN_CS:new l(Math.pow(2,8)).toString(),PLUGIN_PUSH:new l(Math.pow(2,9)).toString(),PLUGIN_BOT:new l(Math.pow(2,10)).toString(),MSG_REACTION:new l(Math.pow(2,16)).toString(),FOLLOW:new l(Math.pow(2,20)).toString()},nr="CommercialConfig",or="commercial-config";var ar,ur,lr=new class{constructor(){this._core=null,this._expirationTime=0,this._isFetching=!1,this._featureMap=new Map,this._methodKeyMap=new Map,this._purchaseBits="0"}install(e){var{helper:t,notificationCenter:s,constants:{WORKFLOW_NAME:r,WORKFLOW_STEP:i,InnerEvent:n}}=this._core=e;s.subscribeInnerEvent(n.COMMERCIAL_CONFIG_PUSH,this._handlePushedConfig,this),s.subscribeInnerEvent(n.LOGOUT,this._handleLogout,this),s.subscribeInnerEvent(n.DESTROY,this._dispose,this),t.registerWorkflowStep(r.SYNC_SERVER_INFO_AFTER_LOGIN,i.COMMERCIAL_CONFIG_UPDATE,this._syncCommercialConfig,this),e.helper.registerExperimentalAPI("isCommercialAbilityEnabled",this),e.helper.registerExperimentalAPI("queryCommercialAbility",this)}isCommercialAbilityEnabled(e){return I(this,void 0,void 0,function*(){var s=parseInt(e,10).toString(2),r=s["length"];let i,n=!0;for(let e=r-1,t=0;0<=e;e--,t++)if("1"===s.charAt(e)&&(i=(t<32?new l(0,2**t):new l(2**(t-32),0)).toString(),!this._featureMap.get(i))){n=!1;break}return this._core.ssoLog.debug("isFeatureEnabled",nr+`.isFeatureEnabled decimalNumber:${e} key:${i} ret:`+n),{code:0,data:{enabled:n}}})}queryCommercialAbility(){return this._purchaseBits}_fetchAndParseCommercialConfig(){return I(this,void 0,void 0,function*(){let s,{ssoLog:e,helper:r,utils:{safeStringify:t}}=this._core;try{this._isFetching=!0;let e=r.generateProtocolData({servcmd:"im_sdk_config_mgr.fetch_imsdk_purchase_bitsv2",data:{uint32_sdkappid:null==(s=this._core.store.get("instance"))?void 0:s.sdkAppId}}),t=yield this._core.channel.sendPacket(e);null!=t&&t.body&&(this._parseCommercialConfig(t.body),this._core.store.set("commercialConfig",this._methodKeyMap))}catch(s){e.error("_fetchAndParseCommercialConfig",t(s))}finally{this._isFetching=!1}})}_syncCommercialConfig(t){return I(this,void 0,void 0,function*(){var e=((null==t?void 0:t.data)||{})["purchaseBits"];e&&(this._parsePurchaseBits(e),this._core.store.set("commercialConfig",this._methodKeyMap)),this._canFetch()&&(yield this._fetchAndParseCommercialConfig()),this._core.helper.taskScheduler.addTask({id:or,intervalMs:1e3,callback:this._fetchCommercialConfigIfReady,context:this})})}_canFetch(){var e=null==(e=this._core.store.get("login"))?void 0:e.isLoggedIn,t=Date.now()>=this._expirationTime;return e&&!this._isFetching&&t}_handlePushedConfig(e){null!=e&&e.body&&(this._parseCommercialConfig(e.body),this._core.store.set("commercialConfig",this._methodKeyMap))}_fetchCommercialConfigIfReady(){return I(this,void 0,void 0,function*(){this._canFetch()&&(yield this._fetchAndParseCommercialConfig())})}_parseCommercialConfig(e){var t,s,r,i,n=this._core["ssoLog"];"object"==typeof e&&({int32_error_code:t,str_error_message:s,str_purchase_bits:r,uint32_expired_time:i}=e,0===t?(this._parsePurchaseBits(r),this._expirationTime=Date.now()+1e3*i):void 0===t?(n.warn("_parseCommercialConfig",nr+"._parseCommercialConfig failed. Invalid message format:",e),this._expirationTime=Date.now()+36e5):(n.warn("_parseCommercialConfig",nr+`._parseCommercialConfig errorCode:${t} errorMessage:`+s),this._expirationTime=Date.now()+12e4))}_isValidPurchaseBits(e){return e&&"string"==typeof e&&1<=e.length&&e.length<=64&&/[01]{1,64}/.test(e)}_parsePurchaseBits(s){var{ssoLog:e,utils:{safeStringify:t}}=this._core;if(this._isValidPurchaseBits(s)){this._purchaseBits=s,this._featureMap.clear(),this._methodKeyMap.clear();var r;for(let e=s.length-1,t=0;0<=e;e--,t++)if(r=(t<32?new l(0,2**t):new l(2**(t-32),0)).toString(),"1"===s[e]){this._featureMap.set(r,!0);let e=this._getKeyByValue(ir,r);e&&this._methodKeyMap.set(e,!0)}else{this._featureMap.set(r,!1);let e=this._getKeyByValue(ir,r);e&&this._methodKeyMap.set(e,!1)}}else e.warn("_parsePurchaseBits",nr+".parsePurchaseBits invalid purchases:"+t(s))}_getKeyByValue(e,t){e=Object.entries(e).find(([,e])=>e===t);return e?e[0]:void 0}_handleLogout(){this._reset()}_dispose(){this._reset(),this._core.notificationCenter.unSubscribeInnerEvent(this._core.InnerEvent.COMMERCIAL_CONFIG_PUSH,this._handlePushedConfig,this),this._core.notificationCenter.unSubscribeInnerEvent(this._core.InnerEvent.LOGOUT,this._reset,this),this._core.notificationCenter.unSubscribeInnerEvent(this._core.InnerEvent.DESTROY,this._dispose,this)}_reset(){this._core.helper.taskScheduler.removeTask(or),this._core.store.set("commercialConfig",{}),this._expirationTime=0,this._isFetching=!1,this._featureMap.clear(),this._purchaseBits="0"}},cr=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)}},dr=new class{constructor(){this.name="ConfigCenter"}install(e){tr.init(e),rr.install(e),lr.install(e),cr.install(e)}},t=new class{constructor(){this.name="ErrorMessage",this._core=null}install(e){return I(this,void 0,void 0,function*(){if(this._core=e,this._canFetch()){let e=yield this._fetchErrorMessage();var t;e&&(t=this._parseResponse(e),this._saveErrorMessage(t))}})}_canFetch(){var e=this._core.store.getStorage("errorMessage");return!e||this._isExpired(e)}_saveErrorMessage(e){this._core.store.setStorage("errorMessage",{errorMessage:e,errorMessageSavedTime:(new Date).getTime()})}_fetchErrorMessage(){return I(this,void 0,void 0,function*(){try{return yield this._core.helper.httpRequest({method:"GET",url:"https://web.sdk.qcloud.com/im/download/error-message/v3/0.0.6/tim-error-message.txt"})}catch(e){console.error(e)}})}_isExpired(e){return!e||(e=e["errorMessageSavedTime"],e&&6048e5<=(new Date).getTime()-e)}_parseResponse(e){if("string"==typeof e){var s=e.split(";\n"),r={},i=new RegExp(/'/g);for(let t=0;t<s.length;t++){var n=s[t].indexOf(":"),o=s[t].slice(0,n);let e=s[t].slice(n+1);o.startsWith("//")||""!==e&&(e=e.replace(i,""),r[o]=e)}return r}}};(yi=ar=ar||{})[yi.START_SYNC=0]="START_SYNC",yi[yi.SYNCING=1]="SYNCING",yi[yi.SYNC_COMPLETE=2]="SYNC_COMPLETE",(n=ur=ur||{})[n.LOGIN_SUCCESS=0]="LOGIN_SUCCESS",n[n.NEW_MESSAGE_RECEIVED=1]="NEW_MESSAGE_RECEIVED";var e=new class{constructor(){this.name="UnreadMessageSynchronizer",this._unreadDBMessageMap=new Map,this._cookie=""}install(e){var t=(this._core=e)["constants"];e.helper.registerWorkflowStep(t.WORKFLOW_NAME.SYNC_SERVER_INFO_AFTER_RE_ONLINE,t.WORKFLOW_STEP.UNREAD_MESSAGE_SYNC,this._syncUnreadDBMessageAfterReOnline,this),e.helper.registerWorkflowStep(t.WORKFLOW_NAME.RECEIVE_C2C_NEW_MESSAGE,t.WORKFLOW_STEP.UNREAD_MESSAGE_SYNC,this._syncUnreadDBMessageAfterNewMessageReceived,this),e.helper.registerWorkflowStep(t.WORKFLOW_NAME.SYNC_SERVER_INFO_AFTER_LOGIN,t.WORKFLOW_STEP.UNREAD_MESSAGE_SYNC,this._syncUnreadDBMessageAfterLogin,this),e.notificationCenter.subscribeInnerEvent(e.InnerEvent.LOGOUT,this._reset,this),e.notificationCenter.subscribeInnerEvent(e.InnerEvent.DESTROY,this._dispose,this)}_syncUnreadMessage(t){return I(this,void 0,void 0,function*(){let{isAfterReOnline:o=!1,isAfterNewMessageReceived:a=!1,isAfterLogin:e=!1}=t||{},u=ar.START_SYNC;for(var l=[],c=[],d=[],p=[];this._canContinueSync({cookie:this._cookie,syncFlag:u});){let e=yield this._fetchUnreadDBMessage({cookie:this._cookie,syncFlag:u,syncTriggerEvent:a?ur.NEW_MESSAGE_RECEIVED:ur.LOGIN_SUCCESS});if(!e)break;let{unreadMessageList:t=[],revokedMessageList:s=[],overflowUnreadCountList:r,unreadCountList:i,groupTipList:n}=e;if(this._cookie=(null==e?void 0:e.cookie)||"",u=null==e?void 0:e.syncFlag,this._parseAndSaveUnreadMessageList(t),d.push(...s),this._updateConversationUnreadOptions({unreadCountList:i,overflowUnreadCountList:r,conversationUpdateFieldList:l}),Array.isArray(n)&&c.push(...n),o){let e=this._handleNewMessageList(t)["messages"];p.push(...e)}}return o?{conversationUpdateFieldList:l,revokedMessageList:d,unreadMessageMap:this._unreadDBMessageMap,groupTipList:c,messages:p}:{conversationUpdateFieldList:l,isInstantMessage:!e,isUnreadC2CMessage:!0,revokedMessageList:d,unreadMessageMap:this._unreadDBMessageMap,groupTipList:c}})}_syncUnreadDBMessageAfterLogin(){return I(this,void 0,void 0,function*(){return this._cookie="",this._syncUnreadMessage({isAfterLogin:!0})})}_syncUnreadDBMessageAfterNewMessageReceived(e){return I(this,void 0,void 0,function*(){if(1===e.data.Flag)return this._syncUnreadMessage({isAfterNewMessageReceived:!0})})}_updateConversationUnreadOptions(e){let{unreadCountList:t,overflowUnreadCountList:s,conversationUpdateFieldList:r}=e,{OuterConstant:{CONV_C2C:i,CONV_SYSTEM:n}}=this._core["constants"];null!=t&&t.forEach(e=>{let{From_Account:t,UnreadCount:s}=e;if(t!==n){let e=r.find(({conversationID:e})=>e===""+i+t);e?e.unreadCount=s:r.push({conversationID:""+i+t,unreadCount:s,type:i})}}),null!=s&&s.forEach(e=>{let{From_Account:t,LastMsgTime:s}=e;t===n||r.find(({conversationID:e})=>e===""+i+t)||r.push({conversationID:""+i+t,type:i,lastMsgTime:s})})}_syncUnreadDBMessageAfterReOnline(){return I(this,void 0,void 0,function*(){return this._syncUnreadMessage({isAfterReOnline:!0})})}_updateMessageProfile(r){var e;let i=(this._core.message||{})["messageDataHandler"],t=null==(e=this._core.store.get("login"))?void 0:e.userId,{from:s,nick:n,avatar:o,conversationID:a=""}=r;if(s!==t){let s=i.getLatestMsgSentByPeer(a);if(s){let{nick:e,avatar:t}=s;n&&o?n===e&&o===t||i.updateNickAndAvatarOfSentMessage({conversationID:a,latestNick:n,latestAvatar:o,isSentByMe:!1}):(r.nick=e,r.avatar=t)}}else{let e=i.getLatestMsgSentByMe(a);!e||n===e.nick&&o===e.avatar||i.updateNickAndAvatarOfSentMessage({conversationID:a,latestNick:n,latestAvatar:o,isSentByMe:!0})}}_handleNewMessageList(e){let t=(this._core.message||{})["messageDataHandler"],u=new Map,s=[];return e.forEach(a=>{this._updateMessageProfile(a);let e=1===a.isModified;if(t.isMessageSentByCurrentInstance(a)?a.isModified=e:e=!1,a.isOnlineMessage())a._onlineOnlyFlag=!0,t.isMessageSentByCurrentInstance(a)||s.push(a);else if(!t.isInMessageList(a)){if(t.storeConversationMessage(a)){let{conversationID:e,conversationType:t,conversationSubType:s,flow:r,_isExcludedFromUnreadCount:i,_isExcludedFromLastMessage:n}=a,o=n?"":a;u.has(e)?(u.get(e).lastMessage=o,"in"!==r||i||u.get(e).unreadCount++):u.set(e,{conversationID:e,type:t,subType:s,unreadCount:i||"in"!==r?0:1,lastMessage:o})}t.isMessageSentByCurrentInstance(a)&&!e||s.push(a)}}),{messages:s,conversationOptions:u}}_fetchUnreadDBMessage(c){return I(this,void 0,void 0,function*(){var{ssoLog:e,utils:{safeStringify:t}}=this._core;try{e.debug("_fetchUnreadDBMessage","unread-message-synchronizer._fetchUnreadDBMessage options:"+t(c));var s,r,i,n,o,a,u,l=yield function(i,u){return I(this,void 0,void 0,function*(){let{cookie:e,syncFlag:t,syncTriggerEvent:s}=i,r="openim.getmsg",o=u.helper.generateProtocolData({servcmd:r,data:{Cookie:e,SyncFlag:t,IsOnlineSync:s,NeedAbstract:1,NeedSignaling:1,NeedCachedMsg:1}}),a=""+o.head.seq+r;try{let e=yield u.channel.sendPacket(o,{requestId:a});if(!e)return null;let{C2CPairUnreadCount:t,C2CRemainingUnreadCount:s,EventArray:r}=e,{unreadMessageList:i,revokedMessageList:n}=function(e,E){let r=[],i=[];return null!=e&&e.forEach(I=>{var e,t,s=function(){var{From_Account:e,From_AccountHeadurl:t,From_AccountNick:s,IsNeedReadReceipt:r,MsgBody:i,MsgClientTime:n,MsgRandom:o,MsgSeq:a,MsgTimeStamp:u,SendMsgControl:l,SupportMessageExtension:c,To_Account:d,TinyId:p,MsgCheckResult:h,CloudCustomData:g,IsPeerRead:_,MsgFlagBits:m,MsgVersion:v,EventArray:f}=I;return{from:e,avatar:t,nick:s,needReadReceipt:1===r,readReceiptSentByPeer:_,clientTime:n,messageFlagBits:m,random:o,sequence:a,time:u,messageControlInfo:l,isSupportExtension:c,to:d,tinyID:p,checkResult:h,cloudCustomData:g,messageVersion:v,eventArray:f,elements:E.message.messageHelper.parseServerPushMessageElement(i)}}();if(null!=(t=null==(e=null==(e=null==I?void 0:I.EventArray)?void 0:e[0])?void 0:e.hasOwnProperty)&&t.call(e,"C2cNotifyMsgArray"))i.push(...function(){let e,t=[];return null!=(e=I.EventArray)&&e.forEach(e=>{var e=e["C2cNotifyMsgArray"],e=null==(e=null==(e=null==e?void 0:e[0])?void 0:e.WithdrawC2cMsgNotify)?void 0:e.C2cWithdrawInfoArray;Array.isArray(e)&&t.push(...e)}),t}());else{let e=E.message.messageFactory.createMessage(Object.assign(Object.assign({},s),{conversationType:"C2C",flow:"in"})),t=s["elements"];e.setElement(t),r.push(e)}}),{unreadMessageList:r,revokedMessageList:i}}(e.MsgList,u);return{syncFlag:null==e?void 0:e.SyncFlag,unreadMessageList:i,revokedMessageList:n,unreadCountList:t,overflowUnreadCountList:s,cookie:null==e?void 0:e.Cookie,groupTipList:r}}catch(e){console.warn(e)}})}(c,this._core);return l?({syncFlag:s,unreadMessageList:r,revokedMessageList:i,cookie:n,unreadCountList:o,overflowUnreadCountList:a,groupTipList:u}=l,this._parseAndSaveUnreadMessageList(r),{syncFlag:s,cookie:n,unreadMessageList:r,revokedMessageList:i,unreadCountList:o,overflowUnreadCountList:a,groupTipList:u}):null}catch(e){console.log(e)}})}_canContinueSync({cookie:e,syncFlag:t}){return t===ar.START_SYNC||t===ar.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()}},pr=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()}},hr=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()}},gr=new class{init(e){var{IN_WX_MINI_APP:t,IN_WX_MINI_PLUGIN:s}=e.helper;s||(t?hr:pr).init(e)}};var _r=new class{init(e){this._core=e,this._activateNetworkMonitoring(),e.notificationCenter.subscribeInnerEvent(e.InnerEvent.DESTROY,this._dispose,this)}_activateNetworkMonitoring(){return I(this,void 0,void 0,function*(){navigator.onLine?this._onOnline():this._onOffline(),this._onOnlineCallback=this._onOnline.bind(this),this._onOfflineCallback=this._onOffline.bind(this),window.addEventListener("online",this._onOnlineCallback),window.addEventListener("offline",this._onOfflineCallback)})}_deactivateNetworkMonitoring(){null!==this._onOnlineCallback&&(window.removeEventListener("online",this._onOnlineCallback),this._onOnlineCallback=null),null!==this._onOfflineCallback&&(window.removeEventListener("offline",this._onOfflineCallback),this._onOfflineCallback=null)}_onNetworkStatusChange(e){var t,{isConnected:e,networkType:s}=e;null!=(t=this._core)&&t.store.set("netWorkMonitor",{isNetworkOnline:e,networkType:s}),null!=(t=this._core)&&t.notificationCenter.emitInnerEvent("networkStatusChange",{isNetworkOnline:e,networkType:s})}_onOnline(){this._onNetworkStatusChange({isConnected:!0,networkType:"online"})}_onOffline(){this._onNetworkStatusChange({isConnected:!1,networkType:"none"})}_reset(){var e;this._deactivateNetworkMonitoring(),null!=(e=this._core)&&e.store.clear("netWorkMonitor")}_dispose(){var e;null!=(e=this._core)&&e.notificationCenter.unSubscribeInnerEvent(null==(e=this._core)?void 0:e.InnerEvent.DESTROY,this._dispose,this),this._reset()}},mr=new class{init(e){this._core=e,this._activateNetworkMonitoring(),e.notificationCenter.subscribeInnerEvent(e.InnerEvent.DESTROY,this._dispose,this)}_activateNetworkMonitoring(){return I(this,void 0,void 0,function*(){try{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()}},vr=new class{init(e){var t=e.utils["IN_MINI_APP"];(t?mr:_r).init(e)}},_=new class{constructor(){this.name="SystemStateMonitor"}install(e){gr.init(e),vr.init(e)}};let fr=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.*"]),Ir="tui_room_svr.*",Er=new class{constructor(){this.name="BusinessCommandTransfer",this._transferredCommands=fr}install(e){var{notificationCenter:e,InnerEvent:t,helper:s}=this._core=e;e.subscribeInnerEvent(t.CLOUD_CONFIG_UPDATE,this._onCloudConfigUpdate,this),e.subscribeInnerEvent(t.LOGOUT,this._reset,this),e.subscribeInnerEvent(t.DESTROY,this._dispose,this),e.subscribeInnerEvent("im_open_push.msg_push",e.InnerEventSubType.BUSINESS_COMMAND,this._onServerPushBusinessCommand,this),s.registerExperimentalAPI("sendTRTCCustomData",this,"transferBusinessCommand"),s.registerExperimentalAPI("sendRoomCustomData",this,"transferBusinessCommand")}transferBusinessCommand(s){return I(this,void 0,void 0,function*(){var t="transferBusinessCommand";try{var{serviceCommand:e=Ir}=s||{};if(this._isValidTransferredCommand(e))return{code:0,data:(yield function(n,o){return I(this,void 0,void 0,function*(){var{helper:e,channel:t}=o,{serviceCommand:s=Ir,data:r}=n||{};let i={};try{i="string"==typeof r?JSON.parse(r):r}catch(e){console.warn(e)}r=e.generateProtocolData({servcmd:s,data:i}),e=""+r.head.seq+s;return t.sendPacket(r,{requestId:e})})}(s,this._core))||{}};throw new this._core.helper.ChatError({code:2995,functionName:t})}catch(e){throw console.warn(e),new this._core.helper.ChatError({code:null==e?void 0:e.errorCode,message:null==e?void 0:e.errorInfo,data:{},functionName:t})}})}_onCloudConfigUpdate(e={}){try{var t;"string"==typeof e.rtc_cmd&&(t=JSON.parse(e.rtc_cmd),Array.isArray(t))&&(this._transferredCommands=new Set([...this._transferredCommands,...t]))}catch(e){console.log(e)}}_isValidTransferredCommand(e=""){e=`${null==e?void 0:e.split(".")[0]}.*`;return this._transferredCommands.has(e)}_onServerPushBusinessCommand(e){var{OuterEvent:t,notificationCenter:s}=this._core,e=(e||{})["MsgContent"],t=t["ROOM_CUSTOM_DATA_RECEIVED"];s.emitOuterEvent(t,{name:t,data:e})}_reset(){this._transferredCommands=fr}_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)}},Cr="signaling",Sr="signaling-timeout";function Mr(e){return e.filter(e=>{var t,s;return"TIMCustomElem"===e.type&&({cloudCustomData:e="",payload:{data:s=""}={}}=e,e=e.match(/"type":"tsignaling"/),t=s.match(/inviteID/),s=s.match(/actionType/),e||t&&s)})}function yr(e){var t=e.payload["data"];try{return JSON.parse(t)}catch(e){return console.error(e),null}}function Tr(e,t){return e.toString(16).padStart(t,"0")}function Ar(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 Or,Dr,Rr,v=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){Cr;var{inviteID:e,groupID:t,inviter:s}=e,s=s===this._core.common.getCurrentUserID();if(!this._onlineSignalingMap.has(e))return!1;var r=this._onlineSignalingMap.get(e)["inviteeList"];if(console.log(`signaling.isInvitationValid inviteID:${e} inviteeList:${r} groupID:`+t),t){if(s)return 0<r.length;let e=this._core.common.getCurrentUserID();return r.includes(e)}return!0}updateSignaling(e){let s=Cr+".updateSignaling",{inviteID:r,inviter:t,inviteeList:i,groupID:n}=e;if(console.log(s+` inviteID:${r} inviter:${t} groupID:`+n),n&&this.hasSignaling(r)){let e=i[0],t=this._onlineSignalingMap.get(r)["inviteeList"];t.includes(e)&&(t.splice(t.indexOf(e),1),console.log(s+` remove ${e}. localInviteeList.length:`+t.length)),0===t.length&&this.removeSignaling(r)}else this.removeSignaling(r)}setSignalingListenStatus(e){this._isSignalingListening=e}getSignalingListenStatus(){return this._isSignalingListening}_dispose(){var e;this._reset(),null!=(e=this._core)&&e.notificationCenter.unSubscribeInnerEvent(this._core.InnerEvent.DESTROY,this._dispose,this),null!=(e=this._core)&&e.notificationCenter.unSubscribeInnerEvent(this._core.InnerEvent.LOGOUT,this._reset,this),this._isSignalingListening=!1}_reset(){this._onlineSignalingMap.clear()}},Lr=new class{init(e){this._core=e}createInviteSignaling(e){var t=this._generateInviteID(),t=this._createInviteSignalingData(Object.assign(Object.assign({},e),{inviteID:t})),{groupID:s,inviteeList:r}=t,s=s||r[0];return{signaling:this._createSignaling(t,s),signalingData:t,signalingExtensionOptions:this._createSignalingExtensionOptions(e)}}createAcceptSignaling(e){var t=this._createAcceptSignalingData(e),{groupID:s,inviter:r}=t;return{signaling:this._createSignaling(t,s||r),signalingData:t,signalingExtensionOptions:this._createSignalingExtensionOptions(e)}}createCancelSignaling(e){var t=this._createCancelSignalingData(e),{groupID:s,inviteeList:r}=t,s=s||r[0];return{signaling:this._createSignaling(t,s),signalingData:t,signalingExtensionOptions:this._createSignalingExtensionOptions(e)}}createRejectSignaling(e){var t=this._createRejectSignalingData(e),{groupID:s,inviter:r}=t;return{signaling:this._createSignaling(t,s||r),signalingData:t,signalingExtensionOptions:this._createSignalingExtensionOptions(e)}}createTimeoutSignaling(e){var{isInviter:t=!1}=e,e=this._createTimeoutSignalingData(e),{groupID:s,inviteeList:r,inviter:i}=e,s=s||(t?r[0]:i);return{signaling:this._createSignaling(e,s),signalingData:e,signalingExtensionOptions:this._createSignalingExtensionOptions(e)}}_createSignalingExtensionOptions(e){var{data:e="",onlineUserOnly:t,inviteID:s="",offlinePushInfo:r,actionType:i}=e,s=(null==(s=null==(s=v.getSignaling(s))?void 0:s.signaling)?void 0:s._onlineOnlyFlag)||!1;return{onlineUserOnly:t||s,offlinePushInfo:r,messageControlInfo:this._createMessageControlInfo(e,i)}}_createMessageControlInfo(e,t){t=5===t&&!!e.match(/excludeTimeoutSignalingFromHistoryMessage/),e=!!e.match(/excludeFromHistoryMessage/)||!!e.match(/excludeOriginalSignalingFromHistoryMessage/);return{excludedFromContentModeration:!0,excludedFromUnreadCount:t||e,excludedFromLastMessage:t||e}}_createInviteSignalingData(e){Cr;var{userID:t,timeout:s=0,groupID:r="",inviteeList:i=[]}=e,n=this._core.common.getCurrentUserID(),e=Object.assign(Object.assign({},this._generateBaseSignalData(e)),{actionType:1,inviter:n,inviteeList:r?i:[t],timeout:s});return console.log("signaling._createInviteSignalingData signalingData:",e),e}_createAcceptSignalingData(e){Cr;var t=e["inviteID"],s=this._core.common.getCurrentUserID(),{inviter:t,groupID:r}=v.getSignaling(t),e=Object.assign(Object.assign({},this._generateBaseSignalData(e)),{actionType:3,groupID:r,inviter:t,inviteeList:[s]});return console.log("signaling._createAcceptSignalingData signalingData:",e),e}_createCancelSignalingData(e){Cr;var t=e["inviteID"],s=this._core.common.getCurrentUserID(),{inviteeList:t,groupID:r}=v.getSignaling(t),e=Object.assign(Object.assign({},this._generateBaseSignalData(e)),{actionType:2,groupID:r,inviter:s,inviteeList:t});return console.log("signaling._createCancelSignalingData signalingData:",e),e}_createRejectSignalingData(e){Cr;var t=e["inviteID"],s=this._core.common.getCurrentUserID(),{inviter:t,groupID:r}=v.getSignaling(t),e=Object.assign(Object.assign({},this._generateBaseSignalData(e)),{actionType:4,groupID:r,inviter:t,inviteeList:[s]});return console.log("signaling._createRejectSignalingData signalingData:",e),e}_createTimeoutSignalingData(e){Cr;var{isInviter:t=!1,inviteID:s}=e,{inviteeList:s,inviter:r}=v.getSignaling(s),i=this._core.common.getCurrentUserID(),e=Object.assign(Object.assign({},this._generateBaseSignalData(e)),{actionType:5,inviter:r,inviteeList:t?s:[i]});return console.log("signaling._createTimeoutSignalingData signalingData:",e),e}_createSignaling(e,t){var{groupID:s=""}=e,t={to:t,conversationType:s?"GROUP":"C2C",priority:"High",payload:{data:JSON.stringify(e)}};return null==(s=null==(e=null==(s=this._core)?void 0:s.message)?void 0:e.messageFactory)?void 0:s.createCustomMessage(t)}_generateInviteID(){return[Tr(Ar(32),8),Tr(Ar(16),4),Tr(16384|Ar(12),4),Tr(32768|Ar(14),4),Tr(Ar(48),12)].join("-")}_generateBaseSignalData(e){var{data:e="",inviteID:t="",groupID:s=""}=e;return{businessID:1,timeout:0,data:e,inviteID:t,groupID:s}}},Nr=new class{constructor(){this._isProcessingSignaling=!1}init(e){(this._core=e).helper.registerApi({apiName:"invite",context:this}),e.helper.registerApi({apiName:"accept",context:this}),e.helper.registerApi({apiName:"cancel",context:this}),e.helper.registerApi({apiName:"reject",context:this}),e.helper.registerApi({apiName:"modifyInvitation",context:this}),e.helper.registerApi({apiName:"getSignalingInfo",context:this}),e.helper.registerApi({apiName:"addSignalingListener",context:this}),e.helper.registerApi({apiName:"removeSignalingListener",context:this}),e.notificationCenter.subscribeInnerEvent(e.InnerEvent.DESTROY,this._dispose,this),e.notificationCenter.subscribeInnerEvent(e.InnerEvent.LOGOUT,this._reset,this)}invite(t){return I(this,void 0,void 0,function*(){var s;try{this._validateBeforeInvite(t);var{signaling:r,signalingData:i,signalingExtensionOptions:e}=Lr.createInviteSignaling(t),n=yield this._sendSignaling(r,e);if(0!==(null==n?void 0:n.code))return n;{let{inviteID:e,timeout:t}=i;return v.saveSignaling(e,Object.assign(Object.assign({},i),{signaling:r})),0<t&&(null!=(s=this._core)&&s.helper.taskScheduler.addOnceTask({id:Sr+"-"+e,intervalMs:1e3*(t+5),callback:this.handleInvitationExpiryTimer.bind(this,e)})),Object.assign(Object.assign({},n),{inviteID:e})}}catch(e){throw e}})}accept(n){return I(this,void 0,void 0,function*(){try{var e=n["inviteID"],{signaling:t,signalingData:s,signalingExtensionOptions:r}=(this._validateBeforeAccept(e),this._isProcessingSignaling=!0,Lr.createAcceptSignaling(n)),i=yield this._sendSignaling(t,r);return 0===(null==i?void 0:i.code)?(v.updateSignaling(s),Object.assign(Object.assign({},i),{inviteID:e})):i}catch(e){throw e}finally{this._isProcessingSignaling=!1}})}cancel(i){return I(this,void 0,void 0,function*(){try{var e=i["inviteID"],{signaling:t,signalingExtensionOptions:s}=(this._validateBeforeCancel(e),this._isProcessingSignaling=!0,Lr.createCancelSignaling(i)),r=yield this._sendSignaling(t,s);return 0===(null==r?void 0:r.code)?(v.removeSignaling(e),Object.assign(Object.assign({},r),{inviteID:e})):r}catch(e){throw e}finally{this._isProcessingSignaling=!1}})}reject(i){return I(this,void 0,void 0,function*(){try{var e=i["inviteID"],{signaling:t,signalingExtensionOptions:s}=(this._validateBeforeReject(e),this._isProcessingSignaling=!0,Lr.createRejectSignaling(i)),r=yield this._sendSignaling(t,s);return 0===(null==r?void 0:r.code)?(v.removeSignaling(e),Object.assign(Object.assign({},r),{inviteID:e})):r}catch(e){throw e}finally{this._isProcessingSignaling=!1}})}modifyInvitation(e){return I(this,void 0,void 0,function*(){var r,i,{inviteID:n,data:o}=e;let a="";try{this._validateBeforeModifyInvitation(n);let e=v.getSignaling(n),t=e["signaling"],s=f(e,["signaling"]);a=t.payload.data,s.data=o,t.payload.data=JSON.stringify(s);var u=yield null==(i=null==(r=this._core)?void 0:r.message.messageAction)?void 0:i.modifyMessage(t);return v.hasSignaling(n)&&v.saveSignaling(n,Object.assign(Object.assign({},s),{signaling:t})),u}catch(e){if(a){let e=v.getSignaling(n)["signaling"];e.payload.data=a}throw e}})}getSignalingInfo(e){var{ssoLog:t,utils:{safeStringify:s}}=this._core;if(0!==Mr([e]).length)return e={businessID:(e=yr(e)).businessID||1,inviteID:e.inviteID,groupID:e.groupID||"",inviter:e.inviter||"",inviteeList:e.inviteeList||[],data:e.data||"",actionType:e.actionType||1,timeout:e.timeout||0},t.debug(Cr+" getSignalingInfo "+s(e)),e}addSignalingListener(e,t,s){var r;e===(null==(r=this._core)?void 0:r.SignalingEvent.NEW_INVITATION_RECEIVED)&&v.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)&&v.setSignalingListenStatus(!1),null!=(r=this._core)&&r.notificationCenter.unSubscribeOuterEvent(e,t,s)}handleInvitationExpiryTimer(e){var t=v.getOnlineSignalingMap(),s=this._core.common.getCurrentUserID();t.has(e)&&(t=t.get(e).inviter===s,this._sendTimeoutNotice({inviteID:e,isInviter:t}))}_sendSignaling(t,s){return I(this,void 0,void 0,function*(){var e;return null==(e=null==(e=null==(e=this._core)?void 0:e.message)?void 0:e.messageSender)?void 0:e.sendMessage(t,s)})}_sendTimeoutNotice(s){return I(this,void 0,void 0,function*(){var i;this._core.ssoLog.debug("_sendTimeoutNotice",Cr+"._sendTimeoutNotice params:"+JSON.stringify(s));let{isInviter:n,inviteID:o}=s,{signaling:a,signalingData:u,signalingExtensionOptions:e}=Lr.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}=u;null!=(i=this._core)&&i.notificationCenter.emitOuterEvent(null==(i=this._core)?void 0:i.SignalingEvent.INVITATION_TIMEOUT,{name:null==(i=this._core)?void 0:i.SignalingEvent.INVITATION_TIMEOUT,data:{data:e,groupID:t,inviteID:o,inviteeList:s,inviter:r,isSelfTimeout:!0,message:a}}),n?v.removeSignaling(o):v.updateSignaling(u)}})}_validateInviteId(e,t){if(!v.hasSignaling(t))throw new this._core.helper.ChatError({functionName:e,code:8010})}_validateProcessStatus(e){if(this._isProcessingSignaling)throw new this._core.helper.ChatError({functionName:e,message:"processing other signaling operations"})}_validateBeforeInvite(e){var e=e["userID"],t=this._core.common.getCurrentUserID();if(e===t)throw new this._core.helper.ChatError({functionName:"invite",message:`cannot invite yourself, currentUserId:${t}, inviteeId:`+e})}_validateBeforeAccept(t){var s="accept";this._validateInviteId(s,t),this._validateProcessStatus(s);let r=this._core.common.getCurrentUserID(),e=v.getSignaling(t)["inviteeList"];if(!e.includes(r)){let e=`userID:${r} not in inviteeList. inviteID:`+t;throw new this._core.helper.ChatError({functionName:s,message:e})}}_validateBeforeCancel(e){var t="cancel",s=(this._validateInviteId(t,e),this._validateProcessStatus(t),this._core.common.getCurrentUserID()),r=v.getSignaling(e)["inviter"];if(r!==s){let e=`unmatched inviter:${r} and my userID:`+s;throw new this._core.helper.ChatError({functionName:t,message:e})}}_validateBeforeReject(t){var s="reject";this._validateInviteId(s,t),this._validateProcessStatus(s);let r=this._core.common.getCurrentUserID(),e=v.getSignaling(t)["inviteeList"];if(!e.includes(r)){let e=`userID:${r} not in inviteeList. inviteID:`+t;throw new this._core.helper.ChatError({functionName:s,message:e})}}_validateBeforeModifyInvitation(e){this._validateInviteId("modifyInvitation",e)}_dispose(){var e;this._reset(),null!=(e=this._core)&&e.notificationCenter.unSubscribeInnerEvent(this._core.InnerEvent.DESTROY,this._dispose,this),null!=(e=this._core)&&e.notificationCenter.unSubscribeInnerEvent(this._core.InnerEvent.LOGOUT,this._reset,this)}_reset(){this._isProcessingSignaling=!1}},br=new class{constructor(){this._actionProcessor=new Map([[1,this._onNewInvitationReceived.bind(this)],[4,this._onInviteeRejected.bind(this)],[3,this._onInviteeAccepted.bind(this)],[2,this._onInvitationCancelled.bind(this)],[5,this._onInvitationTimeout.bind(this)]])}init(e){(this._core=e).notificationCenter.subscribeOuterEvent(e.OuterEvent.MESSAGE_RECEIVED,this._handleMessageReceived,this),e.notificationCenter.subscribeOuterEvent(e.OuterEvent.MESSAGE_MODIFIED,this._handleMessageModified,this),e.notificationCenter.subscribeInnerEvent(e.InnerEvent.DESTROY,this._dispose,this)}handleActionSignaling(e){e.forEach(e=>{var t,s=yr(e);s&&null!=(t=this._actionProcessor.get(s.actionType))&&t(s,e)})}_handleMessageReceived(e){v.getSignalingListenStatus()&&0!==(e=Mr(e.data)).length&&this.handleActionSignaling(e)}_handleMessageModified(e){v.getSignalingListenStatus()&&0<(e=Mr(e.data)).length&&e.forEach(e=>{var t=yr(e);t&&this._onInvitationModified(t,e)})}_onNewInvitationReceived(t,s){Cr;var{inviteID:r,inviteeList:i,groupID:n}=t,o=this._core.common.getCurrentUserID();if(this._core.ssoLog.debug("_onNewInvitationReceived",`signaling._onNewInvitationReceived signalingData:${JSON.stringify(t)}}`),!n||i.includes(o)){let e=t["timeout"];var n=Date.now()/1e3-s.time,o=(0<e&&0<n&&e>n&&(e-=n),v.getSignaling(r));o!==t&&(o||v.saveSignaling(r,Object.assign(Object.assign({},t),{signaling:s})),0<e&&(null!=(n=this._core)&&n.helper.taskScheduler.addOnceTask({id:Sr+"-"+r,intervalMs:1e3*e,callback:Nr.handleInvitationExpiryTimer.bind(Nr,r)})),this._emitEvent({name:null==(o=this._core)?void 0:o.SignalingEvent.NEW_INVITATION_RECEIVED,data:Object.assign(Object.assign({},this._generateBaseEmitData(t)),{inviteeList:i})}))}}_onInviteeRejected(e){Cr;var{inviteID:t,inviter:s,groupID:r,inviteeList:i}=e,n=v.hasSignaling(t);this._core.ssoLog.debug("_onInviteeRejected",`signaling._onInviteeRejected inviteID:${t} hasInviteID:${n} inviter:${s} groupID:`+r),n&&(v.updateSignaling(e),this._emitEvent({name:null==(t=this._core)?void 0:t.SignalingEvent.INVITEE_REJECTED,data:Object.assign(Object.assign({},this._generateBaseEmitData(e)),{invitee:i[0]})}))}_onInviteeAccepted(e){Cr;var{inviteID:t,inviter:s,groupID:r,inviteeList:i}=e,n=v.hasSignaling(t);this._core.ssoLog.debug("_onInviteeAccepted",`signaling._onInviteeAccepted inviteID:${t} hasInviteID:${n} inviter:${s} groupID:`+r),n&&(v.updateSignaling(e),this._emitEvent({name:null==(t=this._core)?void 0:t.SignalingEvent.INVITEE_ACCEPTED,data:Object.assign(Object.assign({},this._generateBaseEmitData(e)),{invitee:i[0]})}))}_onInvitationCancelled(e){Cr;var{inviteID:t,inviter:s,groupID:r}=e,i=v.hasSignaling(t);this._core.ssoLog.debug("_onInvitationCancelled",`signaling._onInvitationCancelled inviteID:${t} hasInviteID:${i} inviter:${s} groupID:`+r),i&&(v.removeSignaling(t),this._emitEvent({name:null==(s=this._core)?void 0:s.SignalingEvent.INVITATION_CANCELLED,data:this._generateBaseEmitData(e)}))}_onInvitationTimeout(e){Cr;var{inviteID:t,inviteeList:s}=e,r=v.hasSignaling(t);this._core.ssoLog.debug("_onInvitationTimeout",`signaling._onInvitationTimeout inviteID:${t} hasInviteID:${r} data:`+e.data),r&&(v.updateSignaling(e),this._emitEvent({name:null==(t=this._core)?void 0:t.SignalingEvent.INVITATION_TIMEOUT,data:Object.assign(Object.assign({},this._generateBaseEmitData(e)),{inviteeList:s,isSelfTimeout:!1})}))}_onInvitationModified(e,t){Cr;var{inviteID:s,data:r}=e,i=v.hasSignaling(s);this._core.ssoLog.debug("_onInvitationModified",`signaling._onInvitationModified inviteID:${s} data:`+r),i&&(v.saveSignaling(s,Object.assign(Object.assign({},e),{signaling:t})),this._emitEvent({name:null==(i=this._core)?void 0:i.SignalingEvent.INVITATION_MODIFIED,data:{inviteID:s,data:r}}))}_emitEvent(e){var t;null!=(t=this._core)&&t.notificationCenter.emitOuterEvent(e.name,e)}_generateBaseEmitData(e){var{inviteID:e,inviter:t,groupID:s,data:r}=e;return{inviteID:e,inviter:t,groupID:s,data:r||""}}_dispose(){var e;null!=(e=this._core)&&e.notificationCenter.unSubscribeOuterEvent(this._core.OuterEvent.MESSAGE_RECEIVED,this._handleMessageReceived,this),null!=(e=this._core)&&e.notificationCenter.unSubscribeOuterEvent(this._core.OuterEvent.MESSAGE_MODIFIED,this._handleMessageModified,this),null!=(e=this._core)&&e.notificationCenter.unSubscribeOuterEvent(this._core.InnerEvent.DESTROY,this._dispose,this)}},Gr=new class{constructor(){this._offlineSignalingMap=new Map}init(e){var{notificationCenter:e,helper:t,constants:{InnerEvent:s,WORKFLOW_STEP:r,WORKFLOW_NAME:i}}=this._core=e;e.subscribeInnerEvent(s.DESTROY,this._dispose,this),e.subscribeInnerEvent(s.LOGOUT,this._reset,this),t.registerWorkflowStep(i.SYNC_SERVER_INFO_AFTER_LOGIN,r.SIGNALING_MESSAGE_RECOVER,this._handleC2COfflineMessage,this)}_handleC2COfflineMessage(e){var{result:{unreadMessageMap:e}={}}=e||{};if(0!==(null==e?void 0:e.size)&&v.getSignalingListenStatus()){e=Mr([...e.values()]);if(0!==e.length&&(e.forEach(e=>{this._handleC2CActionType(e)}),0<this._offlineSignalingMap.size)){let e=this._sortOfflineSignalingByTime();br.handleActionSignaling(e)}}}_handleC2CActionType(e){var t,s=yr(e);s&&(t=s["actionType"],1===t?this._saveValidOfflineInvite(s,e):this._removeOfflineInvite(s))}_saveValidOfflineInvite(e,t){var{inviteID:s,inviteeList:r=[],timeout:i=0}=e,n=this._core.common.getCurrentUserID();r.includes(n)&&(r=Date.now()/1e3-t.time,0<i&&i<r&&0!==i||this._offlineSignalingMap.set(s,Object.assign(Object.assign({},e),{signalingList:[t]})))}_removeOfflineInvite(e){var{inviteID:e=""}=e;this._offlineSignalingMap.has(e)&&this._offlineSignalingMap.delete(e)}_sortOfflineSignalingByTime(){let t=[];return this._offlineSignalingMap.forEach(e=>{t=[...t,...e.signalingList]}),t.sort((e,t)=>e.time-t.time)}_dispose(){var e;this._reset(),null!=(e=this._core)&&e.notificationCenter.unSubscribeInnerEvent(this._core.InnerEvent.LOGOUT,this._reset,this),null!=(e=this._core)&&e.notificationCenter.unSubscribeInnerEvent(this._core.InnerEvent.DESTROY,this._dispose,this)}_reset(){this._offlineSignalingMap.clear()}};let Pr={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}}},wr={invite:!0,cancel:!0,accept:!0,reject:!0,modifyInvitation:!0},Ur=new class{constructor(){this.name="Signaling"}install(e){Nr.init(e),br.init(e),Lr.init(e),v.init(e),Gr.init(e),e.helper.registerValidateConfig({auth:wr,params:Pr})}},E=new class{init(e){this.core=e}},kr=((b=Or=Or||{}).MSG_TEXT="TIMTextElem",b.MSG_CUSTOM="TIMCustomElem",b.MSG_LOCATION="TIMLocationElem",b.MSG_FACE="TIMFaceElem",(N=Dr=Dr||{})[N.FORWARD=0]="FORWARD",N[N.BACKWARD=1]="BACKWARD",{ZH_CN:"zh (cmn-Hans-CN)",EN_US:"en-US",YUE_HK:"yue-Hant-HK",JA_JP:"ja-JP",ZH_PY:"zh-PY"}),Fr="16k_zh-PY",qr={[kr.ZH_CN]:"16k_zh",[kr.EN_US]:"16k_en",[kr.YUE_HK]:"16k_yue",[kr.JA_JP]:"16k_ja",[kr.ZH_PY]:Fr},xr=/\.(wav|pcm|ogg-opus|speex|silk|mp3|m4a|aac|amr)/,Vr={READ:0,UNREAD:1},Br=((ba=Rr=Rr||{}).IN="in",ba.OUT="out","C2C"),jr="GROUP";function Kr(n){return I(this,void 0,void 0,function*(){var e,s=E.core["appStore"],{messageList:t,conversationID:r}=n,s=s.conversationStore.getConversationMap();let i=null==(e=s.get(r))?void 0:e.peerReadTime;if(!i){let e=r.replace(Br,""),t=yield function(t){return I(this,void 0,void 0,function*(){var e={To_Account:t};return E.core.common.buildAndSendPacket({servcmd:"openim.get_peer_read_time",data:e})})}([e]);if(t){let e=t["ReadTime"];i=null==e?void 0:e[0],s.has(r)&&(s.get(r).peerReadTime=i)}}t.forEach(e=>{e.time<=i&&!e.isPeerRead&&"out"===e.flow&&(e.isPeerRead=!0)})})}function Wr(a){return I(this,void 0,void 0,function*(){var e;let{message:s,user:t,appStore:r,constants:{OuterConstant:i}}=E.core,n=r.conversationStore.getConversationMap();if(n.has(a)){let s=null==(e=n.get(a))?void 0:e.userProfile;if(s&&a.startsWith(i.CONV_C2C)){let{avatar:e,nick:t}=s;E.core.message.messageDataHandler.updateNickAndAvatarOfSentMessage({conversationID:a,latestAvatar:e,latestNick:t,isSentByMe:!1})}}var o=((yield t.userProfile.getMyProfile())||{})["data"];if(o){let{avatar:e,nick:t}=o;s.messageDataHandler.updateNickAndAvatarOfSentMessage({conversationID:a,latestAvatar:e,latestNick:t,isSentByMe:!0})}})}function Hr(e){let t,s=E.core["message"],{conversationID:r,messageID:i}=e;return t=(t=s.messageDataHandler.getLocalMessageList(r).find(e=>e.ID===i))||s.messageDataHandler.getSparseMessageList(r).find(e=>e.ID===i)}function Yr(e){return e.map(e=>{var{from:t,to:s,cloudCustomData:r,avatar:i,nick:n,ID:o,clientSequence:a,clientTime:u,messageRandom:l,messageSequence:c,time:d}=e;return{ClientSeq:a,CloudCustomData:r,From_Account:t,From_AccountHeadurl:i,From_AccountNick:n,Id:o,MsgBody:JSON.parse(JSON.stringify(e.transformElementsToServerFormat())),MsgClientTime:u,MsgRandom:l,Random:l,MsgSeq:c,MsgTimeStamp:d,ReceiverId:s,SenderId:t,To_Account:s}})}function $r(e){var{From_Account:t,From_AccountHeadurl:s,From_AccountNick:r,GroupId:i,MsgClientTime:n,ClientSeq:o,To_Account:a,MsgTimeStamp:u,TinyId:l,MsgRandom:c,MsgSeq:d}=e;return{from:t,avatar:s,nick:r,clientTime:n,time:u,tinyID:l,random:c,sequence:d,to:a,groupID:i,clientSequence:o,_elements:null==(t=e.MsgBody)?void 0:t.map(e=>{var t=e["MsgType"];return E.core.message.messageFactory.getElementClass(t).parseServerPushElement(e)})}}var zr=new class{constructor(){this._reactionsMap=new Map}init(e){var{helper:e,notificationCenter:t,InnerEvent:{MESSAGE_PUSH:s},InnerEventSubType:{MESSAGE_REACTION_UPDATED:r,MESSAGE_REACTION_UPDATED_SYNC:i}}=this._core=e;e.registerApi({apiName:"addMessageReaction",context:this}),e.registerApi({apiName:"removeMessageReaction",context:this}),e.registerApi({apiName:"getMessageReactions",context:this}),e.registerApi({apiName:"getAllUserListOfMessageReaction",context:this}),t.subscribeInnerEvent(s,r,this._handleReactionUpdated,this),t.subscribeInnerEvent(s,i,this._handleReactionSync,this)}addMessageReaction(d,p){return I(this,void 0,void 0,function*(){let{OuterConstant:e,helper:s}=this._core;this._validateMessageReactionBusinessCapability();var{conversationID:r,ID:i,conversationType:t,from:n,to:o,clientSequence:a,random:u,time:l,sequence:c}=d,r=`conversationID:${r} messageID:${i} reactionID:`+p;try{return this._recordMessageReactedByMe(i,p),t===e.CONV_C2C?yield function(o,a){return I(this,void 0,void 0,function*(){var{from:e,to:t,clientSequence:s,random:r,time:i,reactionID:n}=o,t={From_Account:e,To_Account:t,MsgKey:s+`_${r}_`+i,Reaction:n,Add_Account:[null==(e=a.store.get("login"))?void 0:e.userId]};return E.core.common.buildAndSendPacket({servcmd:"openim_msg_ext_http_svc.reaction_add",data:t})})}({from:n,to:o,clientSequence:a,random:u,time:l,reactionID:p},this._core):t===e.CONV_GROUP&&(yield function(r,i){return I(this,void 0,void 0,function*(){var{to:e,reactionID:t,sequence:s}=r,s={GroupId:e,MsgSeq:s,Reaction:t,Add_Account:[null==(e=i.store.get("login"))?void 0:e.userId]};return E.core.common.buildAndSendPacket({servcmd:"openim_msg_ext_http_svc.group_reaction_add",data:s})})}({to:o,reactionID:p,sequence:c},this._core)),{code:0,successLog:{message:r}}}catch(e){this._removeMyReactionRecord(i,p);let t=(e||{})["errorCode"];throw new s.ChatError({functionName:"addMessageReaction",code:t,moreMessage:r})}})}removeMessageReaction(d,p){return I(this,void 0,void 0,function*(){var{OuterConstant:e,helper:s}=this._core,{conversationID:r,ID:t,conversationType:i,from:n,to:o,clientSequence:a,random:u,time:l,sequence:c}=(this._validateMessageReactionBusinessCapability(),d),r=`conversationID:${r} messageID:${t} reactionID:`+p;try{return this._removeMyReactionRecord(t,p),i===e.CONV_C2C?yield function(o,a){return I(this,void 0,void 0,function*(){var{from:e,to:t,clientSequence:s,random:r,time:i,reactionID:n}=o,t={From_Account:e,To_Account:t,MsgKey:s+`_${r}_`+i,Reaction:n,Del_Account:[null==(e=a.store.get("login"))?void 0:e.userId]};return E.core.common.buildAndSendPacket({servcmd:"openim_msg_ext_http_svc.reaction_del",data:t})})}({from:n,to:o,clientSequence:a,random:u,time:l,reactionID:p},this._core):i===e.CONV_GROUP&&(yield function(r,i){return I(this,void 0,void 0,function*(){var{to:e,reactionID:t,sequence:s}=r,s={GroupId:e,MsgSeq:s,Reaction:t,Del_Account:[null==(e=i.store.get("login"))?void 0:e.userId]};return E.core.common.buildAndSendPacket({servcmd:"openim_msg_ext_http_svc.group_reaction_del",data:s},i)})}({to:o,reactionID:p,sequence:c},this._core)),{code:0,successLog:{message:r}}}catch(e){let t=(e||{})["errorCode"];throw new s.ChatError({functionName:"removeMessageReaction",code:t,moreMessage:r})}})}getAllUserListOfMessageReaction(u){return I(this,void 0,void 0,function*(){this._validateMessageReactionBusinessCapability();let{message:e,reactionID:t,nextSeq:r=0}=u,s=100<u.count?100:u.count,i=e["conversationID"],{helper:n,constants:o}=this._core;try{var a;if(a=i.startsWith(o.OuterConstant.CONV_C2C)?yield function(u){return I(this,void 0,void 0,function*(){var{message:e,nextSeq:t,reactionID:s,count:r}=u,{from:e,to:i,clientSequence:n,random:o,time:a}=e,s={Reaction:s,NextSeq:t,Count:r,From_Account:e,To_Account:i,MsgKey:n+`_${o}_`+a};return E.core.common.buildAndSendPacket({servcmd:"openim_msg_ext_http_svc.reaction_iterate",data:s})})}({message:e,reactionID:t,nextSeq:r,count:s}):yield function(n){return I(this,void 0,void 0,function*(){var{message:e,nextSeq:t,reactionID:s,count:r}=n,{sequence:e,to:i}=e,s={Reaction:s,NextSeq:t,GroupId:i,Count:r,MsgSeq:e};return E.core.common.buildAndSendPacket({servcmd:"openim_msg_ext_http_svc.group_reaction_iterate",data:s})})}({message:e,reactionID:t,nextSeq:r,count:s})){let{Reaction_Account:e,NextSeq:t}=a,s=yield this._getUserProfileList(e);return{code:0,data:{nextSeq:t,isCompleted:0===r,userList:s}}}}catch(e){let t=(e||{})["errorCode"];throw new n.ChatError({functionName:"getAllUserListOfMessageReaction",code:t})}})}getMessageReactions(h){return I(this,void 0,void 0,function*(){var e=this._core["constants"],{messageList:t,maxUserCountPerReaction:s=10}=(this._validateMessageReactionBusinessCapability(),h),r=t[0];let i=null,n=new Map,{from:o,to:a,conversationType:u}=r,l=this._generateMessageKeyList(t,n),{Results:c=[]}=(u===e.OuterConstant.CONV_C2C?i=yield function(i){return I(this,void 0,void 0,function*(){var{from:e,to:t,messageKeyList:s,maxUserCountPerReaction:r}=i,e={From_Account:e,To_Account:t,MsgKeyList:s,Count:r};return E.core.common.buildAndSendPacket({servcmd:"openim_msg_ext_http_svc.reaction_multi_stat",data:e})})}({from:o,to:a,messageKeyList:l,maxUserCountPerReaction:s}):u===e.OuterConstant.CONV_GROUP&&(i=yield function(r){return I(this,void 0,void 0,function*(){var{groupId:e,messageSequenceList:t,maxUserCountPerReaction:s}=r,e={GroupId:e,MsgSeqList:t,Count:s};return E.core.common.buildAndSendPacket({servcmd:"openim_msg_ext_http_svc.group_reaction_multi_stat",data:e})})}({groupId:a,messageSequenceList:l,maxUserCountPerReaction:s})),i||{}),d=this._extractUserIDsFromReactionResults(c),p=yield this._getUserProfileMap(d);return{code:0,data:{resultList:c.map(e=>{var{ReactionList:e,MsgSeq:t,MsgKey:s}=e;return{messageID:this._generateMessageID({messageSequence:t,messageKey:s,messageIDMap:n}),reactionList:e.map(e=>{var{Reaction:e,Count:t,Reaction_Account:s,ReactedByMe:r}=e;return{reactionID:e,totalUserCount:t,partialUserList:this._generatePartialUserInfo({userIDList:s,userProfileMap:p}),reactedByMyself:1===r}})}})}}})}dispose(){this._reactionsMap.clear()}_extractUserIDsFromReactionResults(e){let t=[];return null!=e&&e.forEach(e=>{var{ReactionList:e=[]}=e;e.forEach(e=>{e.Reaction_Account&&t.push(...e.Reaction_Account)})}),t}_getUserProfileList(s){return I(this,void 0,void 0,function*(){var e;try{var t=yield null==(e=this._core.user.userProfile)?void 0:e.getUserProfile({userIDList:s});return t?t.data:[]}catch(e){return[]}})}_getUserProfileMap(e){return I(this,void 0,void 0,function*(){let r=new Map;return(yield this._getUserProfileList(e)).forEach(e=>{var{nick:e,avatar:t,userID:s}=e;r.set(s,{nick:e,avatar:t,userID:s})}),r})}_recordMessageReactedByMe(e,t){e=e+"-"+t;this._reactionsMap.has(e)?this._reactionsMap.get(e).reactedByMe=!0:this._reactionsMap.set(e,{reactedByMe:!0})}_removeMyReactionRecord(e,t){e=e+"-"+t;this._reactionsMap.has(e)&&(this._reactionsMap.get(e).reactedByMe=!1)}_recordMessageReactionInfo(e){var{messageID:e,reactionID:t,reactionInfo:s}=e,e=e+"-"+t,t=this._reactionsMap.get(e)||{};this._reactionsMap.set(e,Object.assign(Object.assign({},t),s))}_validateMessageReactionBusinessCapability(){var{helper:e,constants:t}=this._core;if(!e.checkBusinessCapabilityBits("MSG_REACTION"))throw new e.ChatError({functionName:"addMessageReaction",code:t.ERROR_CODE.NO_USE,replacement1:"addMessageReaction"})}_handleReactionUpdated(e){let t=e["MsgReactionNotifyList"],{notificationCenter:d,constants:p}=this._core;t.forEach(c=>I(this,void 0,void 0,function*(){let{C2CMsgInfo:e,GroupMsgInfo:t,MsgReactionSummary:s}=c,{TinyId:r,MsgClientTime:i,MsgRandom:n}=Object.assign(Object.assign({},e),t),o=r+`-${i}-`+n,a=this._extractUserIDsFromReactionResults([{ReactionList:s}]),u=yield this._getUserProfileMap(a),l=s.map(e=>{var{Reaction:t,Reaction_Account:s}=e,r=this._generatePartialUserInfo({userIDList:s,userProfileMap:u}),s=s?e.Count:0,e=(null==(e=this._reactionsMap.get(o+"-"+t))?void 0:e.reactedByMe)||!1;return this._recordMessageReactionInfo({messageID:o,reactionID:t,reactionInfo:{reactionID:t,totalUserCount:s,partialUserList:r}}),{reactionID:t,totalUserCount:s,partialUserList:r,reactedByMyself:e}});d.emitOuterEvent(p.OuterEvent.MESSAGE_REACTIONS_UPDATED,{name:p.OuterEvent.MESSAGE_REACTIONS_UPDATED,data:{messageID:o,reactionList:l}})}))}_handleReactionSync(e){var{notificationCenter:t,constants:s}=this._core,{C2CMsgInfo:e={},GroupMsgInfo:r={},Reaction:i,OperateType:n}=e.MsgReactionNotify,{TinyId:e="",MsgClientTime:r=0,MsgRandom:o=0}=Object.assign(Object.assign({},e),r),r=e+`-${r}-`+o,o=r+"-"+i;if(1===n?this._recordMessageReactedByMe(r,i):this._removeMyReactionRecord(r,i),null!=(e=this._reactionsMap.get(o))&&e.reactionID){let e=this._reactionsMap.get(o);e.reactedByMyself=1===n,t.emitOuterEvent(s.OuterEvent.MESSAGE_REACTIONS_UPDATED,{name:s.OuterEvent.MESSAGE_REACTIONS_UPDATED,data:{messageID:r,reactionList:[e]}})}}_generatePartialUserInfo({userIDList:e,userProfileMap:t}){let s=[];return null!=e&&e.forEach(e=>{t.has(e)&&s.push(t.get(e))}),s}_generateMessageID(e){var{messageSequence:e,messageKey:t,messageIDMap:s}=e;return t?s.get(t):s.get(e)}_generateMessageKeyList(e,i){var t=this._core["constants"],s=e[0]["conversationType"];let r=[];return s===t.OuterConstant.CONV_C2C?r=e.map(e=>{var{clientSequence:e,random:t,time:s,ID:r}=e,e=e+`_${t}_`+s;return i.set(e,r),e}):s===t.OuterConstant.CONV_GROUP&&(r=e.map(e=>{var{ID:e,sequence:t}=e;return i.set(t,e),t})),r}},Jr=new class{init(e){var{helper:e,InnerEvent:{MESSAGE_PUSH:t},InnerEventSubType:{C2C_MESSAGE_READ_RECEIPT:s,GROUP_MESSAGE_READ_RECEIPT:r},notificationCenter:i}=this._core=e;e.registerApi({apiName:"sendMessageReadReceipt",context:this}),e.registerApi({apiName:"getMessageReadReceiptList",context:this}),e.registerApi({apiName:"getGroupMessageReadMemberList",context:this}),i.subscribeInnerEvent(t,s,this._handleC2CMessageReadReceipt,this),i.subscribeInnerEvent(t,r,this._handleGroupMessageReadReceipt,this)}sendMessageReadReceipt(e){return I(this,void 0,void 0,function*(){let{common:r,constants:t}=this._core,s=this._filterValidMessageSendByOther(e);if(0===s.length)throw new r.ChatError({code:t.ERROR_CODE.READ_RECEIPT_MSG_LIST_EMPTY});try{let e=s[0]["conversationType"];return e===t.OuterConstant.CONV_C2C?yield function(r){return I(this,void 0,void 0,function*(){var{common:e,constants:t}=E.core,t=r[0].conversationID.replace(t.OuterConstant.CONV_C2C,""),s=r.map(e=>{var{from:e,to:t,sequence:s,random:r,time:i,clientTime:n}=e;return{From_Account:e,To_Account:t,MsgSeq:s,MsgRandom:r,MsgTime:i,MsgClientTime:n}});return e.buildAndSendPacket({servcmd:"openim.c2c_msg_read_receipt",data:{Peer_Account:t,C2CMsgInfo:s}})})}(s):yield function(s){return I(this,void 0,void 0,function*(){var{common:e,constants:t}=E.core,t={GroupId:s[0].conversationID.replace(t.OuterConstant.CONV_GROUP,""),MsgSeqList:s.map(e=>({MsgSeq:e.sequence}))};return e.buildAndSendPacket({servcmd:"group_open_http_svc.group_msg_receipt",data:t})})}(s),{code:0,data:{}}}catch(e){let{errorCode:t,errorInfo:s}=e;throw new r.ChatError({code:t,message:s})}})}getMessageReadReceiptList(i){return I(this,void 0,void 0,function*(){let{common:r,constants:t}=this._core;try{let e=i[0]["conversationType"];if(e===t.OuterConstant.CONV_GROUP){let s=this._filterValidMessageSendByMe(i);if(0<(null==s?void 0:s.length)){let e=yield function(s){return I(this,void 0,void 0,function*(){var{common:e,constants:t}=E.core,t={GroupId:s[0].conversationID.replace(t.OuterConstant.CONV_GROUP,""),MsgSeqList:s.map(e=>({MsgSeq:e.sequence}))};return e.buildAndSendPacket({servcmd:"group_open_http_svc.get_group_msg_receipt",data:t})})}(s),t=(e||{})["GroupMsgReceiptList"];this._updateGroupMessagesReadReceiptInfo({messageList:i,readReceiptList:t})}}return{code:0,data:{messageList:i}}}catch(e){let{errorCode:t,errorInfo:s}=e;throw new r.ChatError({code:t,message:s})}})}getGroupMessageReadMemberList(n){return I(this,void 0,void 0,function*(){let{constants:e,common:r}=this._core,{message:t,filter:o=Vr.READ,cursor:s=""}=n,{conversationID:i,sequence:a,ID:u}=t,l=i.replace(e.OuterConstant.CONV_GROUP,""),c=100<=n.count?100:n.count;try{let n=yield function(n){return I(this,void 0,void 0,function*(){var{sequence:e,groupID:t,filter:s,cursor:r,count:i}=n,e={MsgSeq:e,GroupId:t,Filter:s,Cursor:r,Num:i};return E.core.common.buildAndSendPacket({servcmd:"group_open_http_svc.get_group_msg_receipt_detail",data:e})})}({groupID:l,sequence:a,filter:o,cursor:s,count:c});if(n){let{Cursor:e,IsFinish:t,UnreadList:s,ReadList:r}=n,i={cursor:e,isCompleted:1===t,messageID:u,unreadUserIDList:[],readUserIDList:[]};return o===Vr.READ?i.readUserIDList=r.map(e=>e.Read_Account):o===Vr.UNREAD&&(i.unreadUserIDList=s.map(e=>e.Unread_Account)),{code:0,data:i}}}catch(e){let{errorCode:t,errorInfo:s}=e;throw new r.ChatError({code:t,message:s})}})}_handleC2CMessageReadReceipt(e){let i=[],{constants:t,helper:s}=this._core,{C2cMsgInfo:n,PeerReadTime:o,Peer_Account:a}=e;if(!s.isEmpty(n)){let r=""+t.OuterConstant.CONV_C2C+a;null!=n&&n.forEach(e=>{var{TinyId:e,MsgClientTime:t,MsgRandom:s}=e,e=e+`-${t}-`+s,t=Hr({conversationID:r,messageID:e});t&&!t.readReceiptInfo.isPeerRead&&(t.readReceiptInfo.isPeerRead=!0,t.readReceiptInfo.timestamp=o,i.push({userID:a,messageID:e,isPeerRead:!0,timestamp:o}))}),this._emitReadReceiptEventIfNeed(i)}}_updateGroupMessagesReadReceiptInfo(e){let{messageList:t,readReceiptList:s}=e,r=new Map;t.forEach(e=>{r.set(e.sequence,e)}),null!=s&&s.forEach(e=>{var t,s;0===e.Code&&({MsgSeq:e,ReadNum:t,UnreadNum:s}=e,e=r.get(e))&&(e.readReceiptInfo.readCount=t,e.readReceiptInfo.unreadCount=s)})}_handleGroupMessageReadReceipt(e){let a=[],s=this._core["constants"],t=e["GroupTips"];t.forEach(e=>{let{MsgBody:{GroupMsgReceiptList:t},GroupInfo:{GroupId:n}}=e,o=""+s.OuterConstant.CONV_GROUP+n;null!=t&&t.forEach(e=>{var{TinyId:e,MsgClientTime:t,MsgRandom:s,ReadNum:r,UnreadNum:i}=e,e=e+`-${t}-`+s,t=Hr({conversationID:o,messageID:e}),s={groupID:n,messageID:e,readCount:0,unreadCount:0};t&&("number"==typeof r&&(t.readReceiptInfo.readCount=r,s.readCount=r),"number"==typeof i&&(t.readReceiptInfo.unreadCount=i,s.unreadCount=i),a.push(s))})}),this._emitReadReceiptEventIfNeed(a)}_emitReadReceiptEventIfNeed(e){var{notificationCenter:t,OuterEvent:s}=this._core;0<e.length&&t.emitOuterEvent(s.MESSAGE_READ_RECEIPT_RECEIVED,{name:s.MESSAGE_READ_RECEIPT_RECEIVED,data:e})}_filterValidMessageSendByOther(e){return this._filterNeedReadReceiptMessages(e).filter(e=>{e=e.from;return e!==this._core.common.getCurrentUserID()})}_filterValidMessageSendByMe(e){let s=this._core.constants["OuterConstant"];return this._filterNeedReadReceiptMessages(e).filter(e=>{var{from:e,status:t}=e;return e===this._core.common.getCurrentUserID()&&t===s.MessageStatus.SUCCESS})}_filterNeedReadReceiptMessages(e){return e.filter(e=>!0===e.needReadReceipt)}dispose(){var{InnerEvent:{MESSAGE_PUSH:e},InnerEventSubType:{C2C_MESSAGE_READ_RECEIPT:t,GROUP_MESSAGE_READ_RECEIPT:s},notificationCenter:r}=this._core;r.unSubscribeInnerEvent(e,t,this._handleC2CMessageReadReceipt,this),r.unSubscribeInnerEvent(e,s,this._handleGroupMessageReadReceipt,this)}};function Qr(o,a,u){return I(this,void 0,void 0,function*(){var{buildAndSendPacket:e}=E.core["common"],{from:t,to:s,clientSequence:r,random:i,time:n}=o;return e({servcmd:"openim_msg_ext_http_svc.set_key_values",data:{From_Account:t,To_Account:s,MsgKey:r+`_${i}_`+n,OperateType:u,ExtensionList:a}})})}function Xr(r,i,n){return I(this,void 0,void 0,function*(){var{buildAndSendPacket:e}=E.core["common"],{to:t,sequence:s}=r;return e({servcmd:"openim_msg_ext_http_svc.group_set_key_values",data:{GroupId:t,MsgSeq:s,OperateType:n,ExtensionList:i}})})}var Zr=new class{constructor(){this._messageExtensionsMap=new Map,this._extensionsLatestSequenceMap=new Map,this._completedFetchExtensions=new Set}init(e){var{notificationCenter:e,helper:{registerApi:t},InnerEvent:{MESSAGE_PUSH:s,LOGOUT:r},InnerEventSubType:{MESSAGE_EXTENSIONS_UPDATED:i}}=this._core=e;t({apiName:"setMessageExtensions",context:this}),t({apiName:"getMessageExtensions",context:this}),t({apiName:"deleteMessageExtensions",context:this}),e.subscribeInnerEvent(s,i,this._handleMessageExtensionsNotify,this),e.subscribeInnerEvent(r,this.reset,this)}setMessageExtensions(c,d){return I(this,void 0,void 0,function*(){this._validateMessageExtensionBusinessCapability("setMessageExtensions");let{constants:{OuterConstant:e},ssoLog:t}=this._core,{ID:s,conversationID:r,sequence:i,time:n,conversationType:o}=c,a=d;20<d.length&&(a=d.slice(0,20),t.warn("setMessageExtensions","the length of extensions cannot exceed 20"));var u=this._generateServerExtensions(c,a),l=`convID:${r} messageID:${s} sequence:${i} time:${n} count:`+a.length;try{let r;if(o===e.CONV_C2C?r=yield Qr(c,u,1):o===e.CONV_GROUP&&(r=yield Xr(c,u,1)),r){let{resultList:e,successCount:t,failureCount:s}=this._handleModifyMessageExtensions(c,r);return{code:0,data:{extensions:e},successLog:{message:l+` successCount:${t} failCount:`+s}}}return{code:0,data:{extensions:[]}}}catch(e){let t=e["errorCode"];throw new this._core.helper.ChatError({functionName:"setMessageExtensions",code:t,moreMessage:l})}})}getMessageExtensions(o){return I(this,void 0,void 0,function*(){let{isUndefined:s}=this._core["utils"],{conversationID:e,ID:r,sequence:t,time:i}=(this._validateMessageExtensionBusinessCapability("getMessageExtensions"),o),n=`convID:${e} messageID:${r} sequence:${t} time:`+i;try{let e,t=(this._completedFetchExtensions.has(r)&&(e=this._extensionsLatestSequenceMap.get(r)),yield this._fetchMessageExtensions(o,e));return s(e)&&1<t.length&&this._completedFetchExtensions.add(r),{code:0,data:{extensions:t},successLog:{message:n}}}catch(e){let{errorCode:t,errorInfo:s=""}=e||{};throw new this._core.common.ChatError({code:t,message:s,moreMessage:n})}})}deleteMessageExtensions(d,p){return I(this,void 0,void 0,function*(){this._validateMessageExtensionBusinessCapability("deleteMessageExtensions");let{utils:{isEmpty:e},constants:{OuterConstant:t}}=this._core,{conversationType:s,conversationID:r,sequence:i,ID:n,time:o}=d,a=3,u=[];e(p)||(a=2,null==p)||p.forEach(e=>{u.push({key:e,value:"",seq:0})});var l=`convID:${r} messageID:${n} sequence:${i} time:${o} operateType:`+a,c=this._generateServerExtensions(d,u);try{let r;if(s===t.CONV_C2C?r=yield Qr(d,c,a):s===t.CONV_GROUP&&(r=yield Xr(d,c,a)),r){let{resultList:e,successCount:t,failureCount:s}=this._handleModifyMessageExtensions(d,r);return{code:0,data:{extensions:e},successLog:{message:l+`successCount:${t} failCount:`+s}}}return{code:0,data:{extensions:[]}}}catch(e){let t=e["errorCode"];throw new this._core.helper.ChatError({functionName:"deleteMessageExtensions",code:t,moreMessage:l})}})}reset(){this._messageExtensionsMap.clear(),this._extensionsLatestSequenceMap.clear(),this._completedFetchExtensions.clear()}dispose(){this.reset();var{notificationCenter:e,InnerEvent:{MESSAGE_PUSH:t,LOGOUT:s},InnerEventSubType:{MESSAGE_EXTENSIONS_UPDATED:r}}=this._core;e.unSubscribeInnerEvent(t,r,this._handleMessageExtensionsNotify,this),e.subscribeInnerEvent(s,this.reset,this)}_handleModifyMessageExtensions(e,t){let s=e["ID"],r=t["Seq"],i=t.ExtensionList||[],n=[],o=0,a=0,u=[];return i.forEach(e=>{var{ErrorCode:e,Extension:t}=e,{Key:t,Value:s,Seq:r}=t;n.push({code:e,key:t,value:s}),0===e?o++:a++,u.push({key:t,value:s,seq:r})}),this._extensionsLatestSequenceMap.set(s,r),0<u.length&&this._updateLocalExtensions(e.ID,u),{resultList:n,successCount:o,failureCount:a}}_updateLocalExtensions(e,t){this._messageExtensionsMap.has(e)||this._messageExtensionsMap.set(e,new Map);let r=this._messageExtensionsMap.get(e);null!=t&&t.forEach(e=>{var{key:e,seq:t,value:s=""}=e;null!=r&&r.set(e,{value:s,seq:t})})}_fetchMessageExtensions(u,s){return I(this,void 0,void 0,function*(){let{constants:{OuterConstant:e},utils:{isEmpty:o}}=this._core;try{let n;var{conversationType:t,ID:a}=u;if(t===e.CONV_C2C?n=yield function(e,t){var s=E.core["common"]["buildAndSendPacket"],{from:e,to:r,clientSequence:i,random:n,time:o}=e;return s({servcmd:"openim_msg_ext_http_svc.get_key_values",data:{From_Account:e,To_Account:r,MsgKey:i+`_${n}_`+o,StartSeq:t}})}(u,s):t===e.CONV_GROUP&&(n=yield function(e,t){var s=E.core["common"]["buildAndSendPacket"],{to:e,sequence:r}=e;return s({servcmd:"openim_msg_ext_http_svc.group_get_key_values",data:{GroupId:e,MsgSeq:r,StartSeq:t}})}(u,s)),n){let{LatestSeq:e,ClearSeq:t,CompleteFlag:s}=n,r=(n.ExtensionList||[]).map(e=>({key:e.Key,value:e.Value,seq:e.Seq}));if(this._updateLocalExtensions(a,r),this._clearLocationExtensions(a,t),this._extensionsLatestSequenceMap.set(a,e),1!==s){let e=r[r.length-1].seq+1;return this._fetchMessageExtensions(u,e)}let i=[];if(this._messageExtensionsMap.has(a)){let e=this._messageExtensionsMap.get(a);null!=e&&e.forEach((e,t)=>{e=e.value;o(e)||i.push({key:t,value:e})})}return i}}catch(e){throw e}})}_clearLocationExtensions(e,r){if(!(r<=0)&&this._messageExtensionsMap.has(e)){let s=this._messageExtensionsMap.get(e);null!=s&&s.forEach((e,t)=>{e.seq<=r&&s.delete(t)})}}_generateServerExtensions(e,t){var s=e["ID"];if(this._messageExtensionsMap.has(s)){let r=this._messageExtensionsMap.get(s);return t.map(e=>{var{key:e,value:t}=e;let s=0;return{Key:e,Value:t,Seq:s=null!=r&&r.has(e)?null==(t=r.get(e))?void 0:t.seq:s}})}return t.map(e=>({Key:e.key,Value:e.value,Seq:0}))}_validateMessageExtensionBusinessCapability(e){var{helper:t,constants:s}=this._core;if(!t.checkBusinessCapabilityBits("MSG_EXT"))throw new t.ChatError({functionName:e,code:s.ERROR_CODE.NO_USE,replacement1:e})}_handleMessageExtensionsNotify(e){var{SetKVInfo:e,DeleteKVInfo:t,ClearKVInfo:s,MsgOptType:r,TinyId:i,MsgLastSeq:n,ExtensionC2cMsgInfo:o,ExtensionGroupMsgInfo:a}=(null==e?void 0:e.MsgExtensionNotify)||{},{MsgClientTime:o,MsgRandom:a}=o||a||{},i=i+`-${o}-`+a;this._extensionsLatestSequenceMap.set(i,n),1===r?this._handleMessageExtensionsUpdated({messageID:i,updateMessageExtensionsInfo:e}):2===r?this._handleMessageExtensionsDeleted({messageID:i,deleteMessageExtensionsInfo:t}):3===r&&this._handleMessageExtensionsCleared({messageID:i,clearMessageExtensionsInfo:s})}_handleMessageExtensionsUpdated(e){let{notificationCenter:t,OuterEvent:s}=this._core,{messageID:r,updateMessageExtensionsInfo:i=[]}=e,n=[];i.forEach(e=>{var{MsgKeyValue:e=[]}=e,e=e.map(e=>(n.push({key:e.Key,value:e.Value}),{key:e.Key,value:e.Value,seq:e.Seq}));this._updateLocalExtensions(r,e)}),t.emitOuterEvent(s.MESSAGE_EXTENSIONS_UPDATED,{name:s.MESSAGE_EXTENSIONS_UPDATED,data:{messageID:r,extensions:n}})}_handleMessageExtensionsDeleted(e){let{notificationCenter:t,OuterEvent:s}=this._core,{messageID:r,deleteMessageExtensionsInfo:i=[]}=e,n=[];i.forEach(e=>{var{MsgKeyValue:e=[]}=e,e=e.map(e=>(n.push(e.Key),{key:e.Key,seq:e.Seq}));this._updateLocalExtensions(r,e)}),t.emitOuterEvent(s.MESSAGE_EXTENSIONS_DELETED,{name:s.MESSAGE_EXTENSIONS_DELETED,data:{messageID:r,keyList:n}})}_handleMessageExtensionsCleared(e){let{notificationCenter:t,OuterEvent:{MESSAGE_EXTENSIONS_DELETED:s},utils:{isEmpty:r}}=this._core,{messageID:i,clearMessageExtensionsInfo:n=[]}=e,o=[];n.forEach(e=>{let s=e["ClearMsgSeq"];this._messageExtensionsMap.has(i)&&(this._messageExtensionsMap.get(i)||[]).forEach((e,t)=>{e.seq<=s&&!r(e.value)&&o.push(t)}),this._clearLocationExtensions(i,s)}),t.emitOuterEvent(s,{name:s,data:{messageID:i,keyList:o}})}};let ei={key:"message",required:!0,rules:["object"],allowEmpty:!1,customValidator:e=>{var{OuterConstant:t}=E.core["constants"];return e.status!==t.MessageStatus.SUCCESS?"message is not success":!0===e.isSupportExtension||"message is not support extension"}},ti={setMessageExtensions:[ei,{key:"extensions",required:!0,rules:["array"],allowEmpty:!1}],getMessageExtensions:[ei],deleteMessageExtensions:[ei]},si=Object.assign(Object.assign(Object.assign(Object.assign({deleteMessage:[{required:!0,rules:["array"],allowEmpty:!1}],revokeMessage:[{required:!0,rules:["object"],allowEmpty:!1}],resendMessage:[{key:"message",required:!0,rules:["object"],allowEmpty:!1},{key:"options",required:!1,rules:["object"],allowEmpty:!1}],getMessageList:{conversationID:{required:!0,rules:["string"],allowEmpty:!1},nextReqMessageID:{required:!1,rules:["string"],allowEmpty:!0},count:{required:!1,rules:["number"],allowEmpty:!0}},getMessageListHopping:{conversationID:{required:!0,rules:["string"],allowEmpty:!1},sequence:{required:!1,rules:["number"],allowEmpty:!0},direction:{required:!1,rules:["number"],allowEmpty:!0},count:{required:!1,rules:["number"],allowEmpty:!0}},createTextAtMessage:{to:{required:!0,rules:["string"],allowEmpty:!1},conversationType:{required:!0,rules:["string"],allowEmpty:!1,customValidator:e=>"GROUP"===e||"conversationType should be GROUP."},payload:{required:!0,rules:["object"],allowEmpty:!1,customValidator:e=>{var t="string"==typeof(null==e?void 0:e.text)&&("string"!=typeof e.text||0!==(null==(t=null==e?void 0:e.text)?void 0:t.length))||"payload.text is invalid.";return!0!==t?t:!(null!=e&&e.atUserList&&!Array.isArray(e.atUserList))||"atUserList should be an array or undefind."}}},findMessage:[{required:!0,rules:["string"],allowEmpty:!1}],translateText:{sourceTextList:{required:!0,rules:["array"],allowEmpty:!1},sourceLanguage:{required:!0,rules:["string"],allowEmpty:!1},targetLanguage:{required:!0,rules:["string"],allowEmpty:!1}},createForwardMessage:{to:{required:!0,rules:["string"],allowEmpty:!1},conversationType:{required:!0,rules:["string"],allowEmpty:!1,customValidator:e=>!(!e.startsWith("C2C")&&!e.startsWith("GROUP"))||"conversationType is invalid."},payload:{required:!0,rules:["object"],allowEmpty:!1}},createLocationMessage:{to:{required:!0,rules:["string"],allowEmpty:!1},conversationType:{required:!0,rules:["string"],allowEmpty:!1},payload:{required:!0,rules:["object"],allowEmpty:!1,customValidator:e=>{var{isString:t,isNumber:s}=E.core["utils"];return t(null==e?void 0:e.description)?s(null==e?void 0:e.longitude)?!!s(null==e?void 0:e.latitude)||"payload.latitude must be a number.":"payload.longitude must be a number.":"payload.description must be a string."}}}},{addMessageReaction:[{key:"message",required:!0,rules:["object"],allowEmpty:!1},{key:"reactionID",required:!0,rules:["string"],allowEmpty:!1}],removeMessageReaction:[{key:"message",required:!0,rules:["object"],allowEmpty:!1},{key:"reactionID",required:!0,rules:["string"],allowEmpty:!1}],getMessageReactions:{messageList:{required:!0,rules:["array"],allowEmpty:!1},maxUserCountPerReaction:{required:!1,rules:["number"],allowEmpty:!0,customValidator:e=>"number"!=typeof e?"maxUserCountPerReaction is invalid.":!(e<0||10<e)||"maxUserCountPerReaction should between [0, 10]."}},getAllUserListOfMessageReaction:{message:{required:!0,rules:["object"],allowEmpty:!1,customValidator:e=>"success"===e.status||"message is invalid."},reactionID:{required:!0,rules:["string"],allowEmpty:!1},nextSeq:{required:!1,rules:["number"],allowEmpty:!0},count:{required:!1,rules:["number"],allowEmpty:!0}}}),{sendMessageReadReceipt:[{required:!0,rules:["array"],allowEmpty:!1}],getMessageReadReceiptList:[{required:!0,rules:["array"],allowEmpty:!1}],getGroupMessageReadMemberList:{message:{required:!0,rules:["object"],allowEmpty:!1},filter:{required:!1,rules:["number"],allowEmpty:!0},count:{required:!1,rules:["number"],allowEmpty:!0},cursor:{required:!1,rules:["string"],allowEmpty:!0}}}),ti),{pinGroupMessage:{groupID:{required:!0,rules:["string"],allowEmpty:!1},message:{required:!0,rules:["object"],allowEmpty:!1},isPinned:{required:!0,rules:["boolean"],allowEmpty:!1}},getPinnedGroupMessageList:[{key:"groupID",required:!0,rules:["string"],allowEmpty:!1}]}),ri=Object.assign(Object.assign(Object.assign(Object.assign({deleteMessage:!0,revokeMessage:!0,resendMessage:!0,getMessageList:!0,getMessageListHopping:!0,createTextAtMessage:!0,findMessage:!0,translateText:!0,createForwardMessage:!0,createLocationMessage:!0},{addMessageReaction:!0,removeMessageReaction:!0,getMessageReactions:!0,getAllUserListOfMessageReaction:!0}),{sendMessageReadReceipt:!0,getMessageReadReceiptList:!0,getGroupMessageReadMemberList:!0}),{setMessageExtensions:!0,getMessageExtensions:!0,deleteMessageExtensions:!0}),{pinGroupMessage:!0,getPinnedGroupMessageList:!0});class ii{constructor(e){this._core=e}deleteMessage(s){return I(this,void 0,void 0,function*(){var{to:e,messageIdentifiers:t}=s,e={From_Account:this._core.common.getCurrentUserID(),To_Account:e,MsgKeyList:t};return this._core.common.buildAndSendPacket({servcmd:"openim.delete_c2c_msg_ramble",data:e})})}revokeMessage(n){return I(this,void 0,void 0,function*(){var{to:e,from:t,sequence:s,time:r,random:i}=n;return this._core.common.buildAndSendPacket({servcmd:"openim.msgwithdraw",data:{MsgInfo:{From_Account:t,To_Account:e,MsgSeq:s,MsgRandom:i,MsgTimeStamp:r}}})})}}class ni{constructor(e){this._core=e}deleteMessage(s){return I(this,void 0,void 0,function*(){var{to:e,messageIdentifiers:t}=s,e={GroupId:e,Deleter_Account:this._core.common.getCurrentUserID(),Seqs:t};return this._core.common.buildAndSendPacket({servcmd:"group_open_http_svc.delete_group_ramble_msg_by_seq",data:e})})}revokeMessage(s){return I(this,void 0,void 0,function*(){var{to:e,sequence:t}=s;return this._core.common.buildAndSendPacket({servcmd:"group_open_http_svc.group_msg_recall",data:{GroupId:e,MsgSeqList:[{MsgSeq:t}]}})})}}class oi{constructor(e){this._core=e}generateRevokeMessage(e){var{conversationID:e,sequence:t,random:s,tinyID:r,clientTime:i,revokeReason:n,revoker:o}=e;let a={};var u=this._core.message["messageDataHandler"];return(a=u.revokeMessage({conversationID:e,sequence:t,random:s,revoker:o}))||(a={conversationID:e,sequence:t},r&&i&&s&&(a.ID=r+`-${i}-`+s)),a.revoker=o,a.revokeReason=n,a.revokerInfo={userID:o,nick:"",avatar:""},a}updateRevokerInfo(t){return I(this,void 0,void 0,function*(){var e=t.map(e=>e.revoker);try{let s=yield this._fetchUserInfos(e);s&&t.forEach(e=>{var t=e["revoker"];s[t]&&(e.revokerInfo.nick=s[t].nick||"",e.revokerInfo.avatar=s[t].avatar||"",e.revokerInfo.userID=t)})}catch(e){console.debug(e)}})}_fetchUserInfos(t){return I(this,void 0,void 0,function*(){var e=yield null==(e=this._core.user.userProfile)?void 0:e.getUserProfile({userIDList:t});return null!=e&&e.data?null==(e=e.data)?void 0:e.reduce((e,{userID:t,nick:s,avatar:r})=>(e[t]={nick:s||"",avatar:r||""},e),{}):null})}}var ai=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 ii(e),this._messageHelper=new oi(e);e=e.helper;e.registerApi({apiName:"deleteMessage",context:this}),e.registerApi({apiName:"revokeMessage",context:this}),e.registerApi({apiName:"resendMessage",context:this}),e.registerApi({apiName:"findMessage",context:this})}deleteMessage(t){return I(this,void 0,void 0,function*(){let u=[],l=[],{conversationID:c,conversationType:d}=t[0],e=c.replace(d,"");if("@TIM#SYSTEM"===d)throw new this._core.helper.ChatError({code:2116});if(t.forEach(e=>{var{conversationID:t,conversationType:s,status:r,_onlineOnlyFlag:i,sequence:n,random:o,time:a}=e||{};if("success"===r&&t===c&&s===d){if(!i){let e="C2C"===s?n+`_${o}_`+a:String(n);u.push(e)}l.push(e)}}),0===u.length)return this._handleDeleteMessageSuccess(l),{code:0,data:{messageList:l}};30<u.length&&(u=u.slice(0,30),l=l.slice(0,30));try{return"C2C"===d?yield this._c2cMessageAction.deleteMessage({to:e,messageIdentifiers:u}):yield this._groupMessageAction.deleteMessage({to:e,messageIdentifiers:u}),this._handleDeleteMessageSuccess(l),{code:0,data:{messageList:l}}}catch(e){let t=e["errorCode"];throw new this._core.helper.ChatError({functionName:"deleteMessage",code:t})}})}revokeMessage(l){return I(this,void 0,void 0,function*(){var s;let{conversationType:e,isRevoked:t,ID:r,type:i,from:n,to:o}=l;var a,u=`type:${i} from:${n} to:${o} ID:`+r;if("@TIM#SYSTEM"===e)throw new this._core.helper.ChatError({message:"system message cannot be revoked"});if(t)throw new this._core.helper.ChatError({message:"message has been revoked",moreMessage:u});try{if(a="C2C"===e?yield this._c2cMessageAction.revokeMessage(l):yield this._groupMessageAction.revokeMessage(l)){let e=a["RecallRetList"],t=(null==(s=null==e?void 0:e[0])?void 0:s.RetCode)||0;if(0!==t)throw new this._core.helper.ChatError({code:t,moreMessage:u});return l.isRevoked=!0,yield this._handleRevokeMessageSuccess(l),{code:0,data:{message:l},successLog:{message:u}}}}catch(e){let t=e["errorCode"];throw new this._core.helper.ChatError({functionName:"revokeMessage",code:t,moreMessage:u})}})}resendMessage(t,s){return I(this,void 0,void 0,function*(){var e;return t.isResend=!0,t.status="unSend",null==(e=null==(e=this._core)?void 0:e.apiMap)?void 0:e.sendMessage(t,s)})}findMessage(e){return this._core.message.messageDataHandler.findMessage(e)}_handleDeleteMessageSuccess(i){if(0!==i.length){let{message:{messageDataHandler:s},common:{isTopic:e},notificationCenter:t,InnerEvent:r}=this._core;i.forEach(t=>{t.isDeleted=!0;var e=s.getLocalMessageList(t.conversationID);null!=e&&e.forEach(e=>{e.ID===t.ID&&(e.isDeleted=!0)})});var{conversationID:i=""}=i[0];e(i)?t.emitInnerEvent(r.TOPIC_MESSAGE_DELETED,i):t.emitInnerEvent(r.MESSAGE_DELETED,i)}}_handleRevokeMessageSuccess(i){return I(this,void 0,void 0,function*(){var e=null==(e=this._core.store.get("login"))?void 0:e.userId,{conversationID:t,sequence:s,random:r}=i;this._core.message.messageDataHandler.revokeMessage({conversationID:t,sequence:s,random:r,revoker:e}),yield this._messageHelper.updateRevokerInfo([i])})}};class ui{static parseServerPushElement(e){var{MsgContent:e={}}=e,{Index:e,Data:t}=e;return new ui({index:e,data:t})}constructor(e){this.type=Or.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 li{static parseServerPushElement(e){var{MsgContent:e={}}=e,{Desc:e,Longitude:t,Latitude:s}=e;return new li({description:e,longitude:t,latitude:s})}constructor(e){this.type=Or.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 ci=new class{init(e){(this._core=e).message.messageFactory.registerElementClass(Or.MSG_FACE,ui),e.message.messageFactory.registerElementClass(Or.MSG_LOCATION,li),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 ui({index:t,data:s}),s=this._core.common.getCurrentUserID(),(e=this._core.message.messageFactory.createMessage(Object.assign(Object.assign({},e),{from:s}))).setElement(t),e):null}createTextAtMessage(e){let r=((null==e?void 0:e.payload)||{})["atUserList"],i=this._core.apiMap.createTextMessage(e),n=this._core["OuterConstant"];if(!i)return null;if(Array.isArray(r)){let t=[],s=[];r.forEach(e=>{e!==n.MSG_AT_ALL?(t.push({GroupAtAllFlag:0,GroupAt_Account:e}),s.push(e)):(t.push({GroupAtAllFlag:1}),s.push(n.MSG_AT_ALL))}),i._groupAtInfoList=t,i.atUserList=s}return i}createForwardMessage(e){var{helper:t,OuterConstant:s}=this._core,{to:e,conversationType:r,priority:i,payload:n,needReadReceipt:o,receiverList:a,cloudCustomData:u="",isSupportExtension:l=!1}=e;if(!Array.isArray(n._elements))throw new t.ChatError({functionName:"createForwardMessage",code:2454});if(n.type===s.MSG_GRP_TIP)throw new t.ChatError({functionName:"createForwardMessage",code:2453});s=this._core.common.getCurrentUserID(),t=this._core.message.messageFactory.createMessage({to:e,from:s,conversationType:r,isPlaceMessage:0,priority:i,payload:n,needReadReceipt:o,isSupportExtension:l,cloudCustomData:u,receiverList:a});return t.setRelayFlag(!0),t.setElement(n._elements[0]),t}createLocationMessage(e){var t,s,r;return e?({description:t,longitude:s,latitude:r}=(null==e?void 0:e.payload)||{},t=new li({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 di=class{init(e){this._messageHelper=new oi(e);var{notificationCenter:e,InnerEvent:{MESSAGE_PUSH:t},InnerEventSubType:{C2C_REVOKED_MESSAGE:s},helper:{registerWorkflowStep:r},constants:{WORKFLOW_NAME:i,WORKFLOW_STEP:n}}=this._core=e;e.subscribeInnerEvent(t,s,this._handleC2CNotifyMessage,this),r(i.SYNC_SERVER_INFO_AFTER_RE_ONLINE,n.HANDLE_C2C_REVOKED_MESSAGE_FROM_SYNC_UNREAD,this._handleC2CRevokeMessagesFromUnreadMessageSync,this)}_handleC2CNotifyMessage(e){e=e.C2cNotifyMsgArray;null!=e&&e.forEach(e=>{Object.keys(e).includes("WithdrawC2cMsgNotify")&&this._handleC2CRevokeMessage(e)})}_handleC2CRevokeMessage(t){return I(this,void 0,void 0,function*(){try{var{C2cWithdrawInfoArray:e}=t["WithdrawC2cMsgNotify"];yield this._parseAndEmitC2CRevokedMessages(e)}catch(e){console.debug(e)}})}_parseAndEmitC2CRevokedMessages(s){return I(this,void 0,void 0,function*(){let a=[],{notificationCenter:e,OuterEvent:t,common:{getCurrentUserID:u}}=this._core;s.forEach(e=>{var{MsgRand:t,MsgSeq:s,To_Account:r,From_Account:i,RevokerInfo:{Revoker_Account:n,Revoke_Reason:o}}=e,r=u()===i?"C2C"+r:"C2C"+i,e=(null==(i=null==e?void 0:e.RevokerInfo)?void 0:i.Reason)||o,i=this._messageHelper.generateRevokeMessage({conversationID:r,sequence:s,random:t,revoker:n,revokeReason:e});a.push(i)}),0<a.length&&(yield this._messageHelper.updateRevokerInfo(a),e.emitOuterEvent(t.MESSAGE_REVOKED,{name:t.MESSAGE_REVOKED,data:a}))})}_handleC2CRevokeMessagesFromUnreadMessageSync(t){return I(this,void 0,void 0,function*(){var e=t.result["revokedMessageList"];yield this._parseAndEmitC2CRevokedMessages(e)})}dispose(){var{notificationCenter:e,InnerEvent:{MESSAGE_PUSH:t},InnerEventSubType:{C2C_REVOKED_MESSAGE:s}}=this._core;e.unSubscribeInnerEvent(t,s,this._handleC2CNotifyMessage,this)}},pi=class{init(e){this._messageHelper=new oi(e);var{notificationCenter:e,InnerEvent:{MESSAGE_PUSH:t},InnerEventSubType:{GROUP_MESSAGE_REVOKED:s}}=this._core=e;e.subscribeInnerEvent(t,s,this._handleGroupNotifyMessage,this)}_handleGroupNotifyMessage(e){e=e.GroupTips;null!=e&&e.forEach(e=>{var t;Array.isArray(null==(t=null==e?void 0:e.MsgBody)?void 0:t.GroupWithdrawInfoArray)&&this._handleGroupRevokeMessage(e)})}_handleGroupRevokeMessage(n){return I(this,void 0,void 0,function*(){try{let{RevokerInfo:u,MsgBody:{GroupWithdrawInfoArray:e},GroupInfo:l}=n,c=[],d=[],{notificationCenter:t,OuterEvent:s,utils:{isEmpty:r},common:{isCommunity:i}}=this._core,p=!1;l&&(p=i({groupID:l.GroupId})||!r(l.TopicId)),e.forEach(e=>{var{Random:e,MsgSeq:t,GroupId:s,MsgClientTime:r,TinyId:i,TopicId:n,RevokerInfo:{Revoker_Account:o=(null==u?void 0:u.Revoker_Account)||"",Reason:a=(null==u?void 0:u.Reason)||""}}=e,n=this._messageHelper.generateRevokeMessage({conversationID:n?"GROUP"+n:"GROUP"+s,sequence:t,random:e,tinyID:i,clientTime:r,revoker:o,revokeReason:a});(p?(n.revokerInfo.nick=l.From_AccountNick,n.revokerInfo.avatar=l.From_AccountHeadurl,c):d).push(n)}),0<d.length&&(yield this._messageHelper.updateRevokerInfo(d),c.push(...d)),0!==c.length&&t.emitOuterEvent(s.MESSAGE_REVOKED,{name:s.MESSAGE_REVOKED,data:c})}catch(e){console.debug(e)}})}dispose(){var{notificationCenter:e,InnerEvent:{MESSAGE_PUSH:t},InnerEventSubType:{GROUP_MESSAGE_REVOKED:s}}=this._core;e.unSubscribeInnerEvent(t,s,this._handleGroupNotifyMessage,this)}};var hi=new class{constructor(){this._c2cMessageReceiver=new di,this._groupMessageReceiver=new pi}init(e){this._c2cMessageReceiver.init(e),this._groupMessageReceiver.init(e)}dispose(){this._c2cMessageReceiver.dispose(),this._groupMessageReceiver.dispose()}};class gi{constructor(e){var t=(this._core=e)["constants"];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){let{recoverRevokeNoticeGroupIDList:t=[]}=e.result,r=this._filterValidGroupIDList(t);0!==r.length&&(e=Math.min(Math.ceil(r.length/10),5),Promise.all(Array.from({length:e},(e,t)=>{var t=10*t,s=Math.min(10+t,r.length);return this._fetchGroupRevokeNotice(r.slice(t,s))})).catch(e=>console.error(e)))}_fetchGroupRevokeNotice(s){return I(this,void 0,void 0,function*(){var e;try{var t=yield function(n){return I(this,void 0,void 0,function*(){let{appStore:e,constants:{OuterConstant:s},common:r}=E.core,i=e.groupStore.getGroupMap(),t={NotifyReqList:n.map(e=>{var t=i.get(e);return{NotifyType:1,Limit:20,Type:r.isCommunity({type:t.type,groupID:e})?s.GRP_COMMUNITY:void 0,GroupId:e,BeginTime:(null==t?void 0:t._lastRevokedTime)||0,EndTime:1e3*E.core.common.timeManager.getServerTimeMs()}})||[]};return r.buildAndSendPacket({servcmd:"group_open_http_svc.batch_get_group_notify",data:t})})}(s);if(t){let s=[];null!=(e=null==t?void 0:t.NotifyRspList)&&e.forEach(e=>{var{GroupId:e,NotifyMsgList:t}=e,e=this._parseServerRevokeMessageList({groupID:e,serverRevokeMessageList:t});s.push(...e)}),0!==s.length&&(yield this._emitMessageRevokedEvent(s))}}catch(e){console.error(e)}})}_parseServerRevokeMessageList(e){let{serverRevokeMessageList:t,groupID:o}=e,a=[];return null!=t&&t.forEach(e=>{var{ClientTime:e,MsgSeq:t,Random:s,RevokerInfo:{Revoker_Account:r="",Reason:i=""}}=e,n="GROUP"+o,n=this._messageHelper.generateRevokeMessage({conversationID:n,sequence:t,random:s,clientTime:e,revoker:r,revokeReason:i});a.push(n)}),a}_filterValidGroupIDList(e){let{OuterConstant:t}=this._core["constants"],s=this._core.appStore.groupStore.getGroupMap();return(null==e?void 0:e.filter(e=>{return!(!s.has(e)||(null==(e=s.get(e))?void 0:e.type)===t.GRP_AVCHATROOM||null!=e&&e.isSupportTopic)}))||[]}_emitMessageRevokedEvent(s){return I(this,void 0,void 0,function*(){var{notificationCenter:e,OuterEvent:t}=this._core;yield this._messageHelper.updateRevokerInfo(s),e.emitOuterEvent(t.MESSAGE_REVOKED,{name:t.MESSAGE_REVOKED,data:s})})}}class _i{constructor(e){this._historyMessageListFetchAnchors=new Map,this._core=e,this._messageHelper=new oi(e)}getRoamingMessagesByAnchor(g){return I(this,void 0,void 0,function*(){var i;try{var{conversationID:n,count:e,messageID:r,time:o,direction:a}=g;let t=o,s="";if(!o){let e=r?this._core.message.messageDataHandler.findMessage(r):null;if(t=(null==e?void 0:e.time)||0,r&&this._historyMessageListFetchAnchors.has(n)){let e=this._historyMessageListFetchAnchors.get(n);t=e.lastMessageTime,s=e.messageKey}}var u=n.replace(Br,""),l=yield function(n){return I(this,void 0,void 0,function*(){var{peerAccount:e,count:t,lastMessageTime:s,messageKey:r,direction:i}=n,e={Peer_Account:e,MaxCnt:t,WithRecalledMsg:1,LastMsgTime:s,MsgKey:r,GetDirection:i};return E.core.common.buildAndSendPacket({servcmd:"openim.getroammsg",data:e})})}({count:e,lastMessageTime:t,messageKey:s,peerAccount:u,direction:a});if(l){let{MsgList:t=[],Complete:e,MsgKey:s,LastMsgTime:r}=l;this._historyMessageListFetchAnchors.set(n,{messageKey:s,lastMessageTime:r});var c=[];for(let e=0;e<t.length;e++){var d=t[e],p=this._parseMessage(d);c.push(p)}var h=this._core.message.messageHelper.filterValidMessages(c);return{messageList:h,nextReqMessageIDFromServer:null==(i=h[0])?void 0:i.ID,lastMessageTime:r,hasNoMoreHistoryMessage:1===e}}}catch(e){throw new this._core.helper.ChatError({code:null==e?void 0:e.code})}})}clearHistoryMessageListFetchAnchors(e){this._historyMessageListFetchAnchors.delete(e)}reset(){this._historyMessageListFetchAnchors.clear()}_parseMessage(e){Br;var e=this._core.message.messageHelper.parseServerPushMessage(e),t=this._core.message.messageFactory.createMessage(Object.assign(Object.assign({},e),{conversationType:"C2C",flow:"in"}));return t.setElement(e.elements),t}}var mi=new class{constructor(){this._clearedConversations=new Set,this._fetchedCompleteConversations=new Set}init(e){this._core=e,this._groupMessageHistory=new gi(e),this._c2cMessageHistory=new _i(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 I(this,void 0,void 0,function*(){try{var{conversationID:t,nextReqMessageID:s}=e;if("@TIM#SYSTEM"===t)return{code:0,data:{messageList:[],isCompleted:!1,nextMessageSeq:""}};var r=this._getAvailableLocalMessagesCount({conversationID:t,nextReqMessageID:s});if(this._needFetchHistoryMessageList({conversationID:t,availableLocalMessagesCount:r,targetCount:20})){let e=null;if(t.startsWith(jr)?e=yield this._groupMessageHistory.getRoamingMessagesByAnchor({conversationID:t,sequence:Number(s),count:20,direction:Dr.FORWARD}):t.startsWith(Br)&&(e=yield this._c2cMessageHistory.getRoamingMessagesByAnchor({conversationID:t,messageID:s,count:20,direction:Dr.FORWARD})),e){var{nextReqMessageIDFromServer:i,hasNoMoreHistoryMessage:n,messageList:o}=e,a=this._core.message.messageDataHandler.prependLocalMessageList({messageList:o,conversationID:t}),u=t,{appStore:l,message:c,OuterConstant:d}=E.core,l=l.conversationStore.getConversation(u),p=c.messageDataHandler.getLocalMessageList(u);if(l&&0!==p.length&&u!==d.CONV_SYSTEM){var h=[];for(let e=0;e<p.length;e++)"in"!==p[e].flow?"out"!==p[e].flow||p[e].isRead||p[e].setIsRead(!0):h.push(p[e]);let t=0;if(l.type===d.CONV_C2C){let e=h.slice(-l.unreadCount).filter(e=>e.isRevoked).length;t=h.length-l.unreadCount-e}else t=h.length-l.unreadCount;for(let e=0;e<t&&!h[e].isRead;e++)h[e].setIsRead(!0)}yield Wr(t),t.startsWith(Br)&&(yield Kr({messageList:o,conversationID:t}));var g=this._core.message.messageDataHandler.getLocalMessageList(t).slice(0,a.length+r),_=g.filter(e=>e.isRevoked),m=(yield this._messageHelper.updateRevokerInfo(_),n&&this._fetchedCompleteConversations.add(t),{nextReqMessageID:n?"":String(i),messageList:g,isCompleted:n}),v=g.map(e=>e.sequence);return{code:0,data:m,successLog:{message:`conversationID: ${t} nextReqMessageID: ${s} availableLocalMessagesCount: ${r} sequenceList: `+JSON.stringify(v)}}}return{code:0,data:{messageList:[],isCompleted:!1,nextReqMessageID:""}}}return{code:0,data:yield this._getMessageListFromMemory({conversationID:t,nextReqMessageID:s,count:20}),successLog:{message:`conversationID: ${t} nextReqMessageID: ${s} availableLocalMessagesCount: ${r}}`}}}catch(e){throw new this._core.helper.ChatError({code:null==e?void 0:e.code})}})}getMessageListHopping(r){return I(this,void 0,void 0,function*(){var n,o;let{conversationID:e,sequence:a,time:t,direction:u=Dr.FORWARD}=r,l=this._core.helper["isEmpty"];if(![Dr.BACKWARD,Dr.FORWARD].includes(u))throw new this._core.helper.ChatError({message:"direction must be 0 or 1"});let{count:s=20}=r,c=(s=20<s?20:s,null);if(e.startsWith(jr)){if(c=yield this._groupMessageHistory.getRoamingMessagesByAnchor({conversationID:e,sequence:a,count:s,direction:u})){let{nextReqMessageIDFromServer:t,hasNoMoreHistoryMessage:s,messageList:r,invisibleSequenceList:i}=c;if(this._core.message.messageDataHandler.storeSparseMessageList(r),u===Dr.FORWARD){let e=s&&t<1;return{code:0,data:{messageList:r,isCompleted:e,nextMessageSeq:e?"":t}}}if(u!==Dr.BACKWARD)return{code:0,data:c};{if(l(r)&&l(i))return{code:0,data:{messageList:[],isCompleted:!0,nextMessageSeq:""}};let e=(null==(n=null==r?void 0:r[r.length-1])?void 0:n.sequence)||0,t=(null==(o=null==i?void 0:i[i.length-1])?void 0:o.sequence)||0;return{code:0,data:{messageList:r.filter(e=>e.sequence>=a),isCompleted:!s,nextMessageSeq:s?Math.max(e,t)+1:""}}}}}else if(e.startsWith(Br)&&(c=yield this._c2cMessageHistory.getRoamingMessagesByAnchor({conversationID:e,count:s+1,time:t,direction:u}))){let{messageList:e,lastMessageTime:t,hasNoMoreHistoryMessage:s}=c;return s||(u===Dr.FORWARD?e.shift():e.pop()),this._core.message.messageDataHandler.storeSparseMessageList(e),{code:0,data:{messageList:e,isCompleted:s,nextMessageTime:s?"":t}}}})}clearHistoryMessage(d){return I(this,void 0,void 0,function*(){let t,{appStore:e,common:{ChatError:s,getCurrentUserID:r},OuterConstant:{CONV_C2C:i,CONV_GROUP:n},message:o,apiMap:a}=this._core,u=e.conversationStore.getConversation(d);if(!u)throw new s({code:2500});var l={fromAccount:r()},c=u["type"];c===i?(l.type=1,l.toAccount=d.replace(i,"")):c===n&&(l.type=2,l.toGroupID=d.replace(n,""));try{yield null==(t=null==a?void 0:a.setMessageRead)?void 0:t.call(a,{conversationID:d});let e=yield function(i){return I(this,void 0,void 0,function*(){var{fromAccount:e,type:t,toAccount:s,toGroupID:r}=i,e={From_Account:e,Type:t,To_Account:s,ToGroupid:r};return E.core.common.buildAndSendPacket({servcmd:"recentcontact.clear_msg",data:e})})}(l);return e&&(o.messageDataHandler.deleteConversationMessageList(d),this._clearedConversations.add(d),this._fetchedCompleteConversations.delete(d),this._c2cMessageHistory.clearHistoryMessageListFetchAnchors(d),this._updateConversationLastMessage(d)),{code:0,data:{conversationID:d},successLog:{message:"convID:"+d}}}catch(t){let e=t["errorCode"];throw new this._core.helper.ChatError({functionName:"clearHistoryMessage",code:e,moreMessage:"convID:"+d})}})}_updateConversationLastMessage(e){var t=this._core["appStore"];t.conversationStore.updateConversation(e,{lastMessage:this._generateLastMessage()},{needSort:!0})}_getAvailableLocalMessagesCount({conversationID:e,nextReqMessageID:t}){var s=this._core.message.messageDataHandler.getLocalMessageList(e),r=s["length"];if(!t)return r;let i=-1;return null!=e&&e.startsWith(Br)?i=s.findIndex(e=>e.ID===t):null!=e&&e.startsWith(jr)&&(i=s.findIndex(e=>t.includes("-")?e.ID===t:String(e.sequence)===t)),-1===i?0:i}_needFetchHistoryMessageList({conversationID:e,availableLocalMessagesCount:t,targetCount:s}){return!!this._clearedConversations.has(e)||t<s&&!this._fetchedCompleteConversations.has(e)}_getMessageListFromMemory(e){return I(this,arguments,void 0,function*({conversationID:t,nextReqMessageID:s,count:e}){var r=this._core.message.messageDataHandler.getLocalMessageList(t),i=r.length;let n=i,o={isCompleted:!1,nextReqMessageID:"",messageList:[]},a=0,u=i;return s?(u=r.findIndex(e=>t.startsWith(Br)?e.ID===s:String(e.sequence)===s),a=u>e?u-e:0,n=u):a=e<i?i-e:0,o.nextReqMessageID=0===a?"":this._generateNextReqMessageID({conversationID:t,targetIndex:a}),o.messageList=r.slice(a,u),o.isCompleted=n<=e,t.startsWith(Br)&&(yield Wr(t),yield Kr({messageList:o.messageList,conversationID:t})),o})}_generateNextReqMessageID({conversationID:e,targetIndex:t}){var s=this._core.message.messageDataHandler.getLocalMessageList(e);return e.startsWith("C2C")?s[t].ID:String(s[t].sequence)}_generateLastMessage(){return{lastTime:0,lastSequence:0,fromAccount:"",messageForShow:"",payload:null,type:"",isRevoked:!1,cloudCustomData:"",onlineOnlyFlag:!1,nick:"",nameCard:"",version:0,isPeerRead:!1,revoker:null}}reset(){this._clearedConversations.clear(),this._fetchedCompleteConversations.clear(),this._c2cMessageHistory.reset()}dispose(){this.reset()}},vi=new class{constructor(){this._core=null}init(e){e=(this._core=e).helper;e.registerApi({apiName:"translateText",context:this})}translateText(i){return I(this,void 0,void 0,function*(){try{var{sourceLanguage:t,sourceTextList:s,targetLanguage:e}=i,r=yield function(n,o){return I(this,void 0,void 0,function*(){var{sourceTextList:s,sourceLanguage:e,targetLanguage:t}=n,{store:r,common:i}=o,t={SourceText:s,Source:e,Target:t,FromAccount:null==(s=r.get("login"))?void 0:s.tinyID,SDKAppID:null==(e=r.get("instance"))?void 0:e.sdkAppId},s=yield i.buildAndSendPacket({servcmd:"im_open_translate.ws_batch_trans_text",data:t});if(s){let{CmdErrorCode:e,TargetText:t}=s;return{cmdErrorCode:e,translatedTextList:t}}})}({sourceLanguage:t,sourceTextList:s,targetLanguage:e},this._core);if(r){let{cmdErrorCode:{ErrorCode:e,ErrorInfo:t},translatedTextList:s}=r;if(0===e)return{code:0,data:{translatedTextList:s}};throw{errorCode:e,errorInfo:t,message:t}}}catch(e){var{errorCode:t,errorInfo:s}=e||{};throw new this._core.helper.ChatError({functionName:"translateText",code:t,message:s})}})}},fi=new class{init(e){(this._core=e).helper.registerApi({apiName:"convertVoiceToText",context:this})}convertVoiceToText(n){return I(this,void 0,void 0,function*(){var e,{message:t,language:s=kr.ZH_PY}=n;let r=(t.payload||{})["url"];var i=null==(i=this._core.store.get("login"))?void 0:i.userID,i=(t.from===i&&"out"===t.flow&&(r=t.payload.remoteAudioUrl),this._validateVoiceFormat(r),(null==(e=xr.exec(r))?void 0:e[1])||"mp3"),t=qr[s]||Fr;try{let s=yield function(e){var{store:t,common:s}=E.core,{url:e,format:r,serverLanguageType:i}=e,i={BytesUrl:e,BytesEngServiceType:i,BytesVoiceFormat:r,Uint32Sdkappid:null==(e=t.get("instance"))?void 0:e.sdkAppId,Uint64SourceType:0};return s.buildAndSendPacket({servcmd:"im_open_speech.ws_sentence_recognition",data:i})}({url:r,format:i,serverLanguageType:t});if(s){let{CmdErrorCode:e,BytesResult:t}=s;if(0===e.ErrorCode)return{code:0,data:{result:t}};throw{code:e.ErrorCode,message:e.ErrorInfo}}}catch(e){let{code:t,message:s}=e||{};throw new this._core.common.ChatError({functionName:"convertVoiceToText",code:t,message:s})}})}_validateVoiceFormat(e){if(!xr.test(e))throw new this._core.common.ChatError({code:2119})}};class Ii{constructor(e){var{constants:t,common:s,utils:r}=E.core,{CONV_C2C:t,CONV_GROUP:i}=t.OuterConstant,{ID:e,tinyID:n,from:o,to:a,clientTime:s=s.timeManager.getServerTimeSeconds()||0,random:u,sequence:l,cloudCustomData:c="",nick:d="",avatar:p="",clientSequence:h,conversationType:g,groupID:_,_elements:m,time:v}=e,n=(this.ID=e||n+`-${s}-`+u,this.messageRandom=u,this.from=o,this.messageSender=o,this.time=v,this.messageSequence=l,this.clientSequence=h||l,this.clientTime=s,this.cloudCustomData=c,this.messageReceiver=a,this.avatar=p,this.nick=d,r.deepCopyWithMethods(m));n.forEach(e=>{e.payload=e.content,delete e.content}),this.messageBody=n,e?g.startsWith(t)?this.receiverUserID=a:g.startsWith(i)&&(this.receiverGroupID=a):_?(this.receiverGroupID=_,this.messageReceiver=_):a&&(this.receiverUserID=a,this.messageReceiver=a)}transformElementsToServerFormat(){return this.messageBody?Array.isArray(this.messageBody)?this.messageBody.map(e=>e.transformToServerFormat({isMergerMessage:!0})):this.messageBody.transformToServerFormat({isMergerMessage:!0}):null}}class Ei{static parseServerPushElement(e){var e=e["MsgContent"],{MsgList:e=[],CompatibleText:t,AbstractList:s,Title:r,PbMsgKey:i,JsonMsgKey:n}=e||{},e=e.map(e=>$r(e));return new Ei({messageList:e,title:r,abstractList:s,compatibleText:t,pbDownloadKey:i,downloadKey:n})}constructor(e){this.type=E.core.constants.OuterConstant.MSG_MERGER;let{messageList:t,title:s,abstractList:r,compatibleText:i,pbDownloadKey:n="",downloadKey:o="",version:a=0,layersOverLimit:u=!1}=e,l=[];t.forEach(e=>{e&&(e=new Ii(e),l.push(e))}),this.content={messageList:l,title:s,abstractList:r,compatibleText:i,version:a,downloadKey:o,pbDownloadKey:n,layersOverLimit:u}}validateBeforeSend(){var e=E.core.helper["isEmpty"];return e(this.content.messageList)?{isValid:!1,error:{message:"content is invalid"}}:{isValid:!0}}transformToServerFormat(e){var{isMergerMessage:e=!1}=e||{},{abstractList:e,compatibleText:t,downloadKey:s,layersOverLimit:r,pbDownloadKey:i,title:n,version:o,messageList:a}=e?this.payload:this.content;return{MsgType:this.type,MsgContent:{AbstractList:e,CompatibleText:t,JsonMsgKey:s,LayersOverLimit:r,PbMsgKey:i,Title:n,Version:o,MsgList:Yr(a)}}}}var Ci=new class{init(e){let{message:t,helper:s,constants:{OuterConstant:r}}=this._core=e;t.messageFactory.registerElementClass(r.MSG_MERGER,Ei),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 Ei(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,u){return I(this,void 0,void 0,function*(){var e,t,s;try{var n=function(t){let e="utf-8";E.core.helper.IN_BROWSER&&document&&(e=document.charset.toLowerCase());let s,r=0,i;if(i=t.length,"utf-8"===e||"utf8"===e)for(let e=0;e<i;e++)(s=t.codePointAt(e))<=127?r+=1:s<=2047?r+=2:s<=65535?r+=3:(r+=4,e++);else if("utf-16"===e||"utf16"===e)for(let e=0;e<i;e++)(s=t.codePointAt(e))<=65535?r+=2:(r+=4,e++);else r=t.replace(/[^\x00-\xff]/g,"aa").length;return r}(JSON.stringify(a));let r=a,i=null;if(11264<n){r=this._core.utils.deepCopyWithMethods(a);try{let{JsonMsgKey:e,PbMsgKey:t}=yield function(t){return I(this,void 0,void 0,function*(){var e=t["payload"]["messageList"],e={MsgList:Yr(e)};return E.core.common.buildAndSendPacket({servcmd:"im_long_msg.save_relay_json_msg",data:e})})}(r),s=r["payload"];i=new Ei(Object.assign(Object.assign({},s),{messageList:[],downloadKey:e,pbDownloadKey:t})),r.setElement(i)}catch(e){console.error(e)}}var{message:o}=(yield null==(s=null==(t=null==(e=this._core)?void 0:e.message)?void 0:t.messageSender)?void 0:s.sendMessage(r,u))["data"];return i&&o.setElement(a._elements),{code:0,data:{message:o}}}catch(e){let t=e["errorCode"];throw new this._core.helper.ChatError({code:t})}})}downloadMergerMessage(o){return I(this,void 0,void 0,function*(){let r=this._core["ssoLog"],e=o.payload,{downloadKey:i,pbDownload:t,type:s}=e,n=f(e,["downloadKey","pbDownload","type","messageList"]);try{let e=yield function(e){return I(this,void 0,void 0,function*(){return E.core.common.buildAndSendPacket({servcmd:"im_long_msg.get_relay_json_msg",data:{JsonMsgKey:e}})})}(i),t=(e||{})["MsgList"],s=null==t?void 0:t.map(e=>{e=$r(e);return new Ii(e)});return"function"==typeof o.isOnlineMessage?o.setElement({type:o.type,content:Object.assign({messageList:s},n)}):(o.payload.messageList=s,o.payload.downloadKey="",o.payload.pbDownloadKey=""),r.info("downloadMergerMessage"," success downloadKey:"+i),o}catch(e){let t=e["errorCode"];throw new this._core.helper.ChatError({functionName:"downloadMergerMessage",code:t,moreMessage:i})}})}},Si=new class{init(e){this._core=e,this._core.helper.registerExperimentalAPI("sendComboMessage",this)}sendComboMessage(a){return I(this,void 0,void 0,function*(){let{appStore:t,message:e,common:{getCurrentUserID:s},utils:{isArray:r}}=this._core,{GroupId:i,To_Account:n}=a,o=(a.From_Account=a.From_Account||s(),null);if(i){o=this._generateGroupMessage(Object.assign(Object.assign({},a),{ToGroupId:i}));let e=t.userStore.getUserProfile(s());o.level=(null==e?void 0:e.level)||0,r(n)&&0<n.length&&(o._receiverList=n)}else n&&(o=this._generateC2CMessage(a));return e.messageSender.sendMessage(o,a)})}_generateC2CMessage(e){var{message:t,OuterConstant:{CONV_C2C:s}}=this._core,e=t.messageHelper.parseServerPushMessage(e),t=t.messageFactory.createMessage(Object.assign(Object.assign({},e),{conversationType:s,flow:Rr.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:Rr.OUT})),s=e["elements"];return t.setElement(s),t}},Mi=new class{init(e){var{helper:e,notificationCenter:t,InnerEvent:{MESSAGE_PUSH:s},InnerEventSubType:{GROUP_MESSAGE_PINNED:r}}=this._core=e;t.subscribeInnerEvent(s,r,this._handleGroupMessagePinned,this),e.registerApi({apiName:"pinGroupMessage",context:this}),e.registerApi({apiName:"getPinnedGroupMessageList",context:this})}pinGroupMessage(o){return I(this,void 0,void 0,function*(){let{ssoLog:e,common:{isTopic:t},OuterConstant:{},helper:{ChatError:r}}=this._core;var{groupID:s,message:i,isPinned:n}=o,i=i["sequence"];try{return yield function(o){return I(this,void 0,void 0,function*(){var{buildAndSendPacket:e,getCurrentUserID:t}=E.core["common"],{groupID:s,sequence:r,isPinned:i}=o,t=t(),n=i?"group_open_http_svc.pin_message":"group_open_http_svc.unpin_message",s={GroupId:s,MsgSeq:r};return i?s.Pinner_Account=t:s.UnPinner_Account=t,e({servcmd:n,data:s})})}({groupID:s,sequence:i,isPinned:n}),{code:0,data:{}}}catch(e){let{errorCode:t,errorInfo:s}=e||{};throw new r({code:t,message:s})}})}getPinnedGroupMessageList(r){return I(this,void 0,void 0,function*(){let e=[];try{var t,s=yield function(s){return I(this,void 0,void 0,function*(){var e=s["groupID"],{buildAndSendPacket:t}=E.core["common"];return t({servcmd:"group_open_http_svc.get_pinned_messages",data:{GroupId:e}})})}({groupID:r});return s&&({PinnedMsgList:t=[]}=s,e=yield this._updatePinnedMessageInfo({serverPinnedMessageList:t,groupID:r})),{code:0,data:{messageList:e}}}catch(e){throw e}})}_handleGroupMessagePinned(e){let{message:{messageHelper:l,messageFactory:c},notificationCenter:d,OuterEvent:p,OuterConstant:h}=this._core;e.GroupTips.forEach(e=>{var{ToGroupId:e,MsgBody:{PinnedMsg:t,OpType:s,MsgOperatorMemberExtraInfo:r,SdkGroupMessageId:n}}=e,{UserId:r,NickName:i="",ImageUrl:o=""}=r;let a=null,u=!1;if(16===s){u=!0;let e=l.parseServerGroupMessage(t);(a=c.createMessage(Object.assign(Object.assign({},e),{conversationType:h.CONV_GROUP,flow:"in"}))).setElement(e.elements),a.pinnerInfo={userID:r,nick:i,avatar:o}}else if(17===s){let{ClientTime:e,Random:t,SenderTinyId:s,ServerTime:r,MsgSeq:i}=n;a={ID:`${s}-${e}-`+t,sequence:i,random:t,time:r,clientTime:e}}a&&d.emitOuterEvent(p.PINNED_GROUP_MESSAGE_UPDATED,{name:p.PINNED_GROUP_MESSAGE_UPDATED,data:{groupID:e,message:a,isPinned:u,operatorInfo:{userID:r,nick:i,avatar:o}}})})}_findMessageBySequence(e,t){var{messageDataHandler:s}=this._core["message"];return[...s.getLocalMessageList(e),...s.getSparseMessageList(e)].find(e=>e.sequence===t)}_updatePinnedMessageInfo(e){return I(this,arguments,void 0,function*({serverPinnedMessageList:n,groupID:e}){let{OuterConstant:{CONV_GROUP:t},utils:{isEmpty:s}}=this._core,o=[],a=[],u=[],l=new Map,c=""+t+e;for(let i=0;i<n.length;i++){let e=n[i],{Pinner_Account:t,MsgSeq:s}=e,r=this._findMessageBySequence(c,s);a.push(t),l.set(s,t),r?o.push(r):u.push(s)}let r=yield this._fetchPinnedMessageInfo({conversationID:c,messageSequenceList:u,pinnerIDList:a});if(r){let{pinnerInfoMap:s,messageList:e}=r;return o.push(...e),o.forEach(e=>{var t=e["sequence"],t=l.get(t),t=s[t]||{userID:t,nick:"",avatar:""};e.pinnerInfo=t}),o.sort((e,t)=>e.sequence-t.sequence),o}return[]})}_fetchPinnedMessageInfo(n){return I(this,void 0,void 0,function*(){var{message:{},user:{userProfile:e},utils:{isArray:t}}=this._core,{conversationID:s,messageSequenceList:i,pinnerIDList:r}=n,s=yield Promise.all([this._fetchMessageBySequence({conversationID:s,messageSequenceList:i}),null==e?void 0:e.getUserProfile({userIDList:r})]);if(t(s)){let r={};return((null==(i=s[1])?void 0:i.data)||[]).forEach(e=>{var{userID:e,nick:t="",avatar:s=""}=e;r[e]={userID:e,nick:t,avatar:s}}),{messageList:(null==(e=s[0])?void 0:e.messageList)||[],pinnerInfoMap:r}}})}_fetchMessageBySequence(i){return I(this,void 0,void 0,function*(){var{utils:{isEmpty:e},message:{messageHistory:t}}=this._core,{conversationID:s,messageSequenceList:r}=i;return e(r)?[]:t.getGroupRoamingMessagesByAnchor({conversationID:s,messageSequenceList:r,getType:3})})}},yi=new class{constructor(){this.name="MessageEnhancer"}install(e){this._core=e,E.init(e),ai.init(e),ci.init(e),hi.init(e),mi.init(e),zr.init(e),vi.init(e),fi.init(e),Jr.init(e),Ci.init(e),Zr.init(e),Si.init(e),Mi.init(e),e.helper.registerValidateConfig({auth:ri,params:si}),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),hi.dispose(),mi.dispose(),Jr.dispose(),Zr.dispose()}_reset(){mi.reset()}},Ti=new class{constructor(){this._name="WebRequest"}init(e){this._core=e}request(g,_){return I(this,void 0,void 0,function*(){let e,t=(null==(e=this._core)?void 0:e.utils).isEmpty,{downloadUrl:s="",method:r="PUT",url:i,qs:n,headers:o={},resources:a,dataType:u="text",uploadByIP:l,uploadIP:c}=g,d=i;if(n){let e=this._queryString(n);e&&(d+=(d.includes("?")?"&":"?")+e)}let p=new XMLHttpRequest;p.open(r.toUpperCase(),d,!0),p.responseType=u;var h=Object.assign({},o);if(l&&c&&(h.host=c),!t(h))for(let e in h)h.hasOwnProperty(e)&&!["content-length","user-agent","origin","host"].includes(e.toLowerCase())&&p.setRequestHeader(e,h[e]);return p.onload=()=>{var e=this._getResponseBody(p,s,l&&c),e=this._buildResponse(p,e);if(200===p.status)_(null,e);else{if(c&&!d.includes(c))return g.url=this._domainName2IP(d,c),g.uploadByIP=!0,this.request(g,_);_({code:p.status,message:JSON.stringify(p.responseText)},e)}},p.onerror=()=>{var e=this._getResponseBody(p,s,l&&c),e=this._buildResponse(p,e),t={code:p.status,message:0===p.status?"CORS blocked or network error":JSON.stringify(p.responseText)};_(t,e)},g.onProgress&&p.upload&&(p.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})}),p.send(a),p})}_buildResponse(e,t){let s={};return e.getAllResponseHeaders().trim().split("\n").forEach(e=>{var t;e&&([e,t]=e.split(":").map(e=>e.trim()),s[e.toLowerCase()]=t)}),{statusCode:e.status,statusMessage:e.statusText,headers:s,data:t}}_getResponseBody(e,t,s){return 200===e.status&&t?{location:t,uploadIP:s}:{response:e.responseText,uploadIP:s}}_queryString(s,r="&",i="="){var{isEmpty:e,isPlainObject:t}=null==(e=this._core)?void 0:e.utils;return e(s)?"":t(s)?Object.keys(s).map(e=>{let t=encodeURIComponent(e)+i;return Array.isArray(s[e])?s[e].map(e=>t+encodeURIComponent(e)).join(r):t+encodeURIComponent(s[e])}).filter(Boolean).join(r):void 0}_domainName2IP(e,t){return e.replace(/^http(s)?:\/\/(.*?)\//,`https://${t}/`)}};let Ai=["unknown","image","video","audio","log"];var Oi,Di=new class{init(e){this._core=e}request(s,r){let e,{MINI_APP_NAMESPACE:i,IN_ALIPAY_MINI_APP:n,IN_UNI_IOS_APP:o}=null==(e=this._core)?void 0:e.utils,{resources:a="",headers:u={},url:l,downloadUrl:c=""}=s,d=l,p=null;var h=c?c.match(/^(https?:\/\/[^/]+\/)([^/]*\/?)(.*)$/):null;if(h){var h=decodeURIComponent(h[3]),h=h.includes("?")?h.split("?")[0]:h||"",h={key:s.fileKey||h,success_action_status:200,"Content-Type":""},g={};if(o){let[e,t]=l.split("?sign=");t&&(d=e+"?sign="+encodeURIComponent(t),g.sign=decodeURIComponent(t),g.signature=decodeURIComponent(t))}let t={url:d,header:u,name:"file",filePath:a,formData:Object.assign(Object.assign({},h),g),timeout:s.timeout||3e5};if(n){let e=f(t,["name"]);t=Object.assign(Object.assign({},e),{fileName:"file",fileType:s.fileType?Ai[s.fileType]:"image"})}return(p=i.uploadFile(Object.assign(Object.assign({},t),{success:e=>{this._handleResponse({response:e,downloadUrl:c,callback:r})},fail:e=>{this._handleResponse({response:e,downloadUrl:c,callback:r})}}))).onProgressUpdate&&p.onProgressUpdate(e=>{s.onProgress&&s.onProgress({total:e.totalBytesExpectedToSend||0,loaded:e.totalBytesSent||0,percent:e.progress?Math.floor(e.progress)/100:0})}),p}console.warn("message Invalid download URL format")}_handleResponse(e){var{downloadUrl:e,response:t,callback:s}=e,r={};if(t.header)for(let e in t.header)t.header.hasOwnProperty(e)&&(r[e.toLowerCase()]=t.header[e]);var i=+t.statusCode;200==i?s(null,{statusCode:i,headers:r,data:Object.assign(Object.assign({},t.data),{location:e})}):s({code:i,message:JSON.stringify(t.data)},{statusCode:i,headers:r,data:void 0})}};function Ri(e){return"file"===Object.prototype.toString.call(e).match(/^\[object (.*)\]$/)[1].toLowerCase()}function Li(e){e=e||99999999;return Math.round(Math.random()*e)}function Ni(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 bi(e){return Array.from({length:8},()=>Math.floor(65536*(1+Math.random())).toString(16).substring(1)).join("")+"-"+e}function Gi(e,t){return Math.round(Number(e)*10**t)/10**t}function Pi(e){return e<1024?e+"B":e<1048576?Math.floor(e/1024)+"KB":Math.floor(e/1048576)+"MB"}function wi(e){return e<=1048576?Gi(e/1024,1)+"KB/s":Gi(e/1048576,1)+"MB/s"}let Ui="TIMImageElem",ki="TIMSoundElem",Fi="TIMFileElem",qi="TIMVideoFileElem",xi="RichMediaMessagePlugin",Vi=["rich.my-imcloud.com","imrich.qcloud.com"],Bi=((n=Oi=Oi||{}).UNSENT="unSend",n.SUCCESS="success",n.FAIL="fail",{wechat:/^(wxfile:\/\/tmp_|http:\/\/temp\/|cloud:\/\/temp-)/,alipay:/^(https:\/\/resource\/|alipayfile:\/\/tmp\/)/,baidu:/^(http:\/\/tmp\/|swanfile:\/\/tmp_)/,bytedance:/^(ttfile:\/\/tmp_|\/(var|tmp)\/|tttemp:\/\/)/,qq:/^(qqfile:\/\/tmp_|http:\/\/qtemp\/)/});var C=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(Bi).some(e=>e.test(t))}extractFileFromInput(e){var{isArray:t}=this._core["utils"];return Ri(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 I(this,void 0,void 0,function*(){var{IN_MINI_APP:e,IN_BROWSER:t}=(null==(e=this._core)?void 0:e.utils)||{};return this._shouldSkipProbing()?{width:0,height:0}:t?this._probeImageDimensionsWeb(s):e?this._probeImageDimensionsMiniApp(s):void 0})}isSimpleCos(){var e=((null==(e=this._core)?void 0:e.store.get("cloudConfig"))||{})["simple_cos"];return"0"!==e}getFileDNList(){let e,t=Vi;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=Vi}return t}getPlatform(){var e;return null==(e=this._core)?void 0:e.utils.platform}generateUUID(e,t){let s,r=`${this.getSDKAppID()}-${this.getCurrentUserID()}-`+(null==(s=this._core)?void 0:s.utils.randomString());return t?r+"."+t:(e=(t=e.name||e.value||e.url||e.tempFilePath)&&t.slice(t.lastIndexOf(".")+1),r=e?r+"."+e:r)}processResourceUrl(e){if(!e)return"";let t=e;var s=this.getFileDownloadProxy(),r=this.getAuthKey(),i=this.getFileDNList(),e=(s&&(e.startsWith("http://")?t=e.replace(/^http:\/\/[^/]+/,s):e.startsWith("https://")&&(t=e.replace(/^https:\/\/[^/]+/,s))),r&&-1===t.indexOf("authKey=")&&function(e,t){let s=!1;if(e){var e=e.match(/:\/\/([0-9]?\.)?(.[^/:]+)/),r=e&&e[2]||"";if(r.includes("rich-dev"))return!0;for(let e=0;e<t.length;e++)if(r.endsWith(t[e])){s=!0;break}}return s}(t,i));return t=e?-1<t.indexOf("?")?t+"&authKey="+r:t+"?authKey="+r:t}getCurrentUserID(){var e;return null==(e=null==(e=this._core)?void 0:e.store.get("login"))?void 0:e.userId}getSDKAppID(){var e;return null==(e=null==(e=this._core)?void 0:e.store.get("instance"))?void 0:e.sdkAppId}getFileDownloadProxy(){var e;return(null==(e=null==(e=this._core)?void 0:e.store.get("instance"))?void 0:e.fileDownloadProxy)||""}getFileUploadProxy(){var e;return(null==(e=null==(e=this._core)?void 0:e.store.get("instance"))?void 0:e.fileUploadProxy)||""}getAuthKey(){var e;return(null==(e=null==(e=this._core)?void 0:e.store.get("login"))?void 0:e.authKey)||""}isPrivateNetWork(){var e;return null==(e=null==(e=this._core)?void 0:e.store.get("instance"))?void 0:e.proxyServer}getPlatformFlags(){var{IN_BROWSER:e,IN_MINI_APP:t,IN_RN_APP:s,IN_UNI_NATIVE_APP:r}=null==(e=this._core)?void 0:e.utils;return{IN_BROWSER:e,IN_MINI_APP:t,IN_RN_APP:s,IN_UNI_NATIVE_APP:r}}isEmpty(e){var t=(null==(t=this._core)?void 0:t.utils)["isEmpty"];return t(e)}_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})}},ji=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?Di:Ti,null!=(t=this.httpRequest)&&t.init(e)}uploadToCOS(l){return I(this,void 0,void 0,function*(){let r=xi+" uploadToCOS",{ssoLog:i,utils:{safeStringify:e}}=this._core,n=l["file"];this.uploadFileType=l.uploadFileType,i.debug("uploadToCOS",r+" options:"+e(l));try{let e=Date.now(),t=yield this._createCosOptions(l),s=yield this._uploadFile(t);this._handleUploadError(s,l);var o=this._createUploadResult(n,s),a=Date.now()-e,u=`size:${Pi(n.size)} time:${a}ms speed:`+wi(1e3*n.size/a);return i.debug("uploadToCOS",r+` ok. name:${n.name} `+u),{uploadOptions:t,response:o}}catch(e){throw console.warn(r+" failed, error:",e),e}})}_handleUploadError(e,t){var s=(null==(s=this._core)?void 0:s.helper)["ChatError"];if(403===e.statusCode)throw Ni(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:Ni(Date.now(),!1),uploadSpeed:wi(1e3*e.size/Ni(Date.now(),!1))}}_createCosOptions(p){return I(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 i=yield this._fetchCosSignatureUrl({fileType:this.uploadFileType,fileName:e,uploadMethod:s,duration:this.duration,userID:p.message.from,conversationType:r}),{uploadUrl:n,downloadUrl:o,requestSnapshotUrl:a,thumbUrl:u,largeUrl:l,fileKey:c}=i,d=!C.isPrivateNetWork()&&i.uploadIP;return{url:this._getRawOrUploadProxyUrl(n),fileType:this.uploadFileType,fileName:e,resources:t,downloadUrl:o,requestSnapshotUrl:a,thumbUrl:u,largeUrl:l,fileKey:c,uploadIP:d||"",onProgress:e=>this._handleUploadProgress(e,p)}}catch(e){throw console.error("Failed to create COS pre-signed URL options:",e),e}})}_prepareUploadParams(e){var{ssoLog:t,utils:{safeStringify:s}}=this._core,t=(t.debug("_prepareUploadParams"," prepareUploadParams:"+s(e)),e)["file"],{IN_MINI_APP:s,IN_RN_APP:r}=C.getPlatformFlags(),s=s||r,r=s&&e.message.type!==Fi,e=t["name"],e=e.slice(e.lastIndexOf(".")),e=""+Li(999999)+e;return{fileName:bi(r?t.name:e),resources:s?t.url:t,uploadMethod:s?1:0}}_handleUploadProgress(e,t){if("function"==typeof t.onProgress)try{t.onProgress(e.percent)}catch(e){throw console.warn("Upload progress callback error:",e),e}}_fetchCosSignatureUrl(e){return I(this,void 0,void 0,function*(){var{ssoLog:t,utils:{safeStringify:s}}=this._core,r=C.isSimpleCos(),i=this._prepareCosRequestData(e),n=r?"im_cos_msg.simple_sig":"im_cos_msg.pre_sig";try{let e=yield function(i,n,o){return I(this,void 0,void 0,function*(){try{var{helper:e,channel:t}=o,s=e.generateCosSpecifiedData({servcmd:i,data:n}),r=s.head.seq+i;return yield t.sendPacket(s,{requestId:r})}catch(e){throw console.warn("getCosSig error:",e),e}})}(n,i,this._core);this.fetchCosTryCount=0;var o=this._processResponse(e);return t.debug("_fetchCosSignatureUrl",` ok. isSimpleCos:${r} data:`+s(o)),o||{}}catch(t){if(this.fetchCosTryCount<1)return this.fetchCosTryCount++,this._fetchCosSignatureUrl(e);throw this.fetchCosTryCount=0,t}})}_processResponse(e){var t;let s=C.isSimpleCos(),u=s?null==(t=null==e?void 0:e.rpt_pre_sig)?void 0:t[0]:e;if(!u)return{};if(s){let{str_final_ip:e,rpt_pre_sig:t,uint32_file_id:s,uint32_exist_flag:r,str_download_url:i,str_upload_url:n,str_snapshot_url:o,str_file_key:a}=u;return{uploadIP:e,preSig:t,fileID:s,existFlag:r,downloadUrl:i,uploadUrl:n,requestSnapshotUrl:o,fileKey:a}}let{upload_url:r,download_url:i,snapshot_url:n,thumb_url:o,large_url:a,file_key:l}=u;return{uploadUrl:r,downloadUrl:i,requestSnapshotUrl:n,thumbUrl:o,largeUrl:a,fileKey:l}}_prepareCosRequestData(e){return C.isSimpleCos()?{uint32_upload_method:e.uploadMethod,uint32_platform:C.getPlatform(),uint32_sdkappid:C.getSDKAppID(),str_user_id:e.userID,uint32_scene:e.conversationType,rpt_upload_object:[{uint32_file_id:1,uint32_file_type:e.fileType,str_file_name:e.fileName}]}:{file_type:e.fileType,file_name:e.fileName,upload_method:e.uploadMethod,Duration:e.duration}}_uploadFile(i){return I(this,void 0,void 0,function*(){return new Promise((s,r)=>{this.httpRequest.request(i,(e,t)=>{e&&this.uploadFileTryCount<this.maxRetries&&this.shouldRetry(e)?(this.uploadFileTryCount++,this._uploadFile(i).then(s).catch(r)):(this.uploadFileTryCount=0,e?r(e):s(t))})})})}shouldRetry(e){return!(!e||5!==Math.floor(e.statusCode/100)&&(!this.isTimeRelatedError(e)||!this._isClockOutOfSync(e)||(this._syncSystemClock(e),0)))}isTimeRelatedError(e){var t,s;try{var r=null==(t=e.error)?void 0:t.Code,i=null==(s=e.error)?void 0:s.Message;return"RequestTimeTooSkewed"===r||"AccessDenied"===r&&"Request has expired"===i}catch(e){return!1}}_isClockOutOfSync(e){var t,e=(null==(t=e.headers)?void 0:t.date)||(null==(t=e.headers)?void 0:t.Date)||(null==(t=e.error)?void 0:t.ServerTime);return!!e&&(t=Date.now(),e=Date.parse(e),3e4<=Math.abs(t+this.systemClockOffset-e))}_syncSystemClock(e){var t,s=(null==(t=e.headers)?void 0:t.date)||(null==(t=e.headers)?void 0:t.Date)||(null==(t=e.error)?void 0:t.ServerTime);if(s){let e=Date.now(),t=Date.parse(s);this.systemClockOffset=t-e}}_getRawOrUploadProxyUrl(e){var t=C.getFileUploadProxy();let s=e;return s=t?e.replace(/^https:\/\/[^/]+/,t):s}_isC2CConversation(e){return"C2C"===e.slice(0,3)}};let Ki=["jpg","jpeg","gif","png","bmp","image","webp"],Wi={JPG:1,JPEG:1,GIF:2,PNG:3,BMP:4,UNKNOWN:255};class Hi{constructor(e,t){this.instanceID=Li(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=C.addAuthToUrl(e.imageUrl||e.url||""),this.url=C.addAuthToUrl(e.url||t)}setSizeType(e){this.sizeType=e}setType(e){this.type=e}setImageUrl(e){e&&(this.imageUrl=C.addAuthToUrl(e))}getImageUrl(){return this.imageUrl}}function Yi(e){var{originUrl:t,originWidth:e,originHeight:s,min:r=198}=e,i=parseInt(e)||0,s=parseInt(s)||0,n={url:void 0,width:0,height:0};if((i<=s?i:s)<=r)n.url=t,n.width=i,n.height=s;else{s<=i?(n.width=Math.ceil(i*r/s),n.height=r):(n.width=r,n.height=Math.ceil(s*r/i));let e=t&&-1<t.indexOf("?")?t+"&":t+"?";n.url=198===r?e+"imageView2/3/w/198/h/198":e+"imageView2/3/w/720/h/720"}return void 0===t?f(n,["url"]):n}class $i{constructor(e){this._imageMemoryURL="",this._percent=0,this.type=Ui;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:i}=t,n=r.map(e=>({size:e.Size,type:e.Type,width:e.Width,height:e.Height,url:e.URL}));return new $i({imageFormat:s,imageInfoArray:n,uuid:i})}createImageDataAsURL(e){let t="";var{IN_MINI_APP:s,IN_RN_APP:r,IN_BROWSER:i}=C.getPlatformFlags();return t=e&&((s||r)&&(t=e.url),i)?window.URL.createObjectURL(e):t}initImageInfoArray(t=[]){var s={type:0,size:0,width:0,height:0,url:""};for(let e=0;e<3;e++){var r=t[e]||Object.assign({},s),r=new Hi(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=Wi[e.toUpperCase()]||Wi.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],Yi({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:C.removeAuthToUrl(e.imageUrl)}))}}var zi=new class{constructor(){this._messageOptionsMap=new Map}init(e){var{notificationCenter:e,helper:t,InnerEvent:s,message:r}=this._core=e;t.registerApi({apiName:"createImageMessage",context:this}),null!=(t=null==r?void 0:r.messageFactory)&&t.registerElementClass(Ui,$i),e.subscribeInnerEvent(s.DESTROY,this._dispose,this)}createImageMessage(e){var t,s,r;try{var i=null==(t=this._core.store.get("login"))?void 0:t.userId,n=null==(r=null==(s=this._core)?void 0:s.message.messageFactory)?void 0:r.createMessage(Object.assign(Object.assign({},e),{from:i})),o=this._processImage(e),a=(e.payload.file=o,{imageFormat:Wi.UNKNOWN,uuid:C.generateUUID(o),file:o,imageInfoArray:[]}),u=new $i(a);return n.setElement(u),this._messageOptionsMap.set(n.clientSequence,e),n}catch(e){throw e}}upload(r){return I(this,void 0,void 0,function*(){var e=r.getElements()[0],t=this._messageOptionsMap.get(r.clientSequence).payload["file"],t=(this._validateBeforeUploadImage(t),yield this._performImageUpload(e,r,t)),s=this._generateImageInfo(t);return e.updateImageFormat(null==t?void 0:t.fileType),e.updateImageInfoArray(s),r})}_performImageUpload(r,i,s){return I(this,void 0,void 0,function*(){var e=i["to"],{uploadOptions:e,response:t}=yield ji.uploadToCOS({uploadFileType:1,file:s,to:e,message:i,onProgress:e=>{var t,s;r.updatePercent(e),null!=(s=null==(t=this._messageOptionsMap.get(i.clientSequence))?void 0:t.onProgress)&&s.call(t,e)}});return this._parseResponse(e,t)})}_generateImageInfo(e){var{location:e,fileSize:t,width:s,height:r,smallImageUrl:i,smallImageWidth:n,smallImageHeight:o,largeImageUrl:a,largeImageWidth:u,largeImageHeight:l,imageInfoArray:c}=e,e=C.addAuthToUrl(e),d={size:t,url:e,width:s,height:r};return 0<(null==c?void 0:c.length)?this._processImageInfoArray(c,t):i&&a?[Object.assign({},d),{largeImageUrl:a,largeImageWidth:u,largeImageHeight:l},{smallImageUrl:i,smallImageWidth:n,smallImageHeight:o}]:[Object.assign({},d),this._generateThumbInfo(e,s,r,720),this._generateThumbInfo(e,s,r,198)]}_generateThumbInfo(e,t,s,r){return Yi({originUrl:e,originWidth:t,originHeight:s,min:r})}_processImageInfoArray(e,t){let s,r,i;for(var n of e)1===n.type?(r=n,r.size=t):2===n.type?(i=n,i.size=t):(s=n,s.size=t);return[Object.assign({},s),Object.assign({},i),Object.assign({},r)]}_parseResponse(r,i){return I(this,void 0,void 0,function*(){try{var{thumbUrl:e,largeUrl:t,downloadUrl:s}=r;if(e&&t&&(yield this._getImageInfoByUrl(e,i,"thumb"),yield this._getImageInfoByUrl(t,i,"large")),C.isSimpleCos()&&!C.isPrivateNetWork()&&(yield this._getImageInfoArray(s,i),null!=i)&&i.uploadIP){let e=this._extractDomainFromUrl(s);e&&(yield this._getDownloadIP(e,i))}return i}catch(e){throw e}})}_extractDomainFromUrl(t){var e;try{let e=t.match(/:\/\/([^\/]+)/);return e?e[1]:null}catch(t){return null!=(e=this._core)&&e.ssoLog.warn("_extractDomainFromUrl","Failed to extract domain from URL:"+t.message),null}}_getImageInfoByUrl(r,i,n){return I(this,void 0,void 0,function*(){var t;try{let e=C.addAuthToUrl(r),{width:t=0,height:s=0}=yield C.probeImageWidthHeight(e);i.width=t,i.height=s,"thumb"===n?(i.smallImageUrl=r,i.smallImageWidth=t,i.smallImageHeight=s):(i.largeImageUrl=r,i.largeImageWidth=t,i.largeImageHeight=s)}catch(e){null!=(t=this._core)&&t.ssoLog.warn("_getImageInfoByUrl",`Failed to get ${n} image info:`+e.message)}})}_validateBeforeUploadImage(e){var t=(null==(t=this._core)?void 0:t.helper)["ChatError"];if(!e)throw new t({code:2251});this._checkImageType(e),this._checkImageSize(e)}_processImage(e){var t;try{var s=(null==(t=this._core)?void 0:t.utils)["IN_MINI_APP"],r=e.payload["file"];return s?this._processMiniAppImageFile(r):this._processWebImageFile(r)}catch(e){throw e}}_processMiniAppImageFile(e){Ri(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=C.extractFileFromInput(e);if(e)return e;throw new t({message:"Invalid file. Pass either `e.target` (from file input) or a File object"})}_getDownloadIP(r,i){return I(this,void 0,void 0,function*(){var e=xi+" getDownloadIP domainName: "+r;try{var t,s=yield function(o,a){return I(this,void 0,void 0,function*(){try{var{helper:e,channel:t}=a,s="im_cos_msg.get_final_ip",r={str_domain:o},i=e.generateProtocolData({servcmd:s,data:r}),n=i.head.seq+s;return yield t.sendPacket(i,{requestId:n})}catch(e){throw console.warn("getFinalIP error:",e),e}})}(r,this._core);s&&s.str_final_ip&&(console.log(e+" ok. downloadIP:"+s),(t=i.location.split("/"))[0]=s.str_final_ip,i.location=t.join("/"))}catch(e){console.warn(e)}})}_getImageInfoArray(t,s){return I(this,void 0,void 0,function*(){try{var e=yield function(o,a){return I(this,void 0,void 0,function*(){try{var{helper:e,channel:t}=a,s="im_cos_msg.get_imageinfo",r={str_image_url:o},i=e.generateProtocolData({servcmd:s,data:r}),n=i.head.seq+s;return yield t.sendPacket(i,{requestId:n})}catch(e){throw console.warn("getImageInfo error:",e),e}})}(t,this._core);return s.imageInfoArray=this._processImageInfoResponse(e),s}catch(e){throw s.imageInfoArray=void 0,e}})}_processImageInfoResponse(e){return e?(e=e["rpt_msg_image_info"],e.map(e=>({type:e.uint32_image_type,url:e.str_url,width:e.uint32_width,height:e.uint32_height,imageFormat:e.str_image_format}))):[]}_checkImageType(e){var{utils:t,helper:s}=this._core;let r="";if(t.IN_MINI_APP&&(r=e.url.slice(e.url.lastIndexOf(".")+1)),t.IN_BROWSER&&(r=e.name.slice(e.name.lastIndexOf(".")+1)),Ki.indexOf(r.toLowerCase())<0)throw new s.ChatError({code:2252})}_checkImageSize(e){var{utils:t,helper:s}=this._core,r=0;if(t.IN_MINI_APP,0===(r=e.size))throw new s.ChatError({code:2108});if(20971520<=r)throw new s.ChatError({message:"File size exceeds limit: "+Pi(20971520)})}_reset(){this._messageOptionsMap.clear()}_dispose(){this._reset();var{notificationCenter:e,InnerEvent:t}=this._core;e.unSubscribeInnerEvent(t.DESTROY,this._dispose,this)}};let Ji=104857600;function Qi(e,t){let r=e.split("."),i=t.split("."),n=Math.max(r.length,i.length);for(;r.length<n;)r.push("0");for(;i.length<n;)i.push("0");for(let s=0;s<n;s++){let e=parseInt(r[s]),t=parseInt(i[s]);if(e>t)return 1;if(e<t)return-1}return 0}let Xi=new class{init(e){this.core=e}};class Zi{constructor(e){this.type=Fi,this.uploadProgress=0;var t=this._getFileInfo(e);this.content={downloadFlag:2,fileUrl:C.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:i}=e;return new Zi({downloadFlag:e,url:t,fileName:s,fileSize:r,uuid:i})}updatePercent(e){this.uploadProgress=Math.min(e,1)}updateFileUrl(e){this.content.fileUrl=e}validateBeforeSend(){var e=""!==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:i}=e?this.payload:this.content;return{MsgType:this.type,MsgContent:{Download_Flag:t,Url:C.removeAuthToUrl(s),FileName:r,FileSize:i,UUID:e}}}_getFileInfo(e){var t=Xi.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=Li(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 en=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(Fi,Zi),e.subscribeInnerEvent(s.DESTROY,this._dispose,this)}createFileMessage(e){var t,s,r;try{this._checkVersion();var i=this._processFile(e.payload.file),n=(e.payload.file=i,null==(t=this._core.store.get("login"))?void 0:t.userId),o=null==(r=null==(s=this._core)?void 0:s.message.messageFactory)?void 0:r.createMessage(Object.assign(Object.assign({},e),{from:n})),a={uuid:C.generateUUID(i),file:i},u=new Zi(a);return o.setElement(u),this._messageOptionsMap.set(o.clientSequence,e),o}catch(e){throw e}}upload(s){return I(this,void 0,void 0,function*(){var e=this._messageOptionsMap.get(s.clientSequence).payload["file"],t=(this._validateBeforeUploadFile(e),s.getElements()[0]),e=yield this._performFileUpload(t,s,e),e=C.addAuthToUrl(null==e?void 0:e.location);return t.updateFileUrl(e),s})}_validateBeforeUploadFile(e){var t=(null==(t=this._core)?void 0:t.helper)["ChatError"];if(!e)throw new t({code:2401});if(e.size>Ji)throw new t({message:"File size exceeds limit: "+Pi(Ji)});if(0===e.size)throw new t({code:2108})}_performFileUpload(r,i,t){return I(this,void 0,void 0,function*(){var e=i["to"],e=(yield ji.uploadToCOS({uploadFileType:255,file:t,to:e,message:i,onProgress:e=>{var t,s;r.updatePercent(e),null!=(s=null==(t=this._messageOptionsMap.get(i.clientSequence))?void 0:t.onProgress)&&s.call(t,e)}}))["response"];return e})}_processFile(t){var{IN_BROWSER:e,IN_RN_APP:s,IN_WX_MINI_APP:r,IN_QQ_MINI_APP:i,IN_UNI_NATIVE_APP:n}=null==(e=this._core)?void 0:e.utils,o=(null==(o=this._core)?void 0:o.helper)["ChatError"];if(e||n){let e=C.extractFileFromInput(t);if(e)return e;throw new o({message:"Invalid file. Pass either `e.target` (from file input) or a File object"})}if(r||i){let e=t["tempFiles"];return Object.assign(Object.assign({},e[0]),{url:e[0].path})}return s?Object.assign(Object.assign({},t),{url:t.uri}):t}_checkVersion(){var{MINI_APP_NAMESPACE:t,IN_MINI_APP:e,IN_WX_MINI_APP:s,IN_QQ_MINI_APP:r,IN_UNI_NATIVE_APP:i}=null==(e=this._core)?void 0:e.utils,n=(null==(n=this._core)?void 0:n.helper)["ChatError"];if(e){if(!(s||r||i))throw new n({message:"Unsupported mini app environment"});let e=t.getSystemInfoSync().SDKVersion;if(s&&Qi(e,"2.5.0")<0)throw new n({message:"WXChooseMessageFile requires SDK version 2.5.0 or higher"});if(r&&Qi(e,"1.18.0")<0)throw new n({message:"QQChooseMessageFile requires SDK version 1.18.0 or higher"})}}_reset(){this._messageOptionsMap.clear()}_dispose(){this._reset();var{notificationCenter:e,InnerEvent:t}=this._core;e.unSubscribeInnerEvent(t.DESTROY,this._dispose,this)}};let tn=["mp4","quicktime","mov"],sn=104857600;class rn{constructor(e){this.type=qi,this.uploadProgress=0;var t="number"==typeof(null==e?void 0:e.videoSecond)?null==e?void 0:e.videoSecond:0;this.content={remoteVideoUrl:C.addAuthToUrl(e.remoteVideoUrl||e.videoUrl||""),videoFormat:e.videoFormat,videoSecond:parseInt(null==t?void 0:t.toString(),10),videoSize:e.videoSize,videoUrl:C.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:C.addAuthToUrl(e.thumbUrl),snapshotUrl:C.addAuthToUrl(e.thumbUrl)}}static parseServerPushElement(e){var e=e["MsgContent"],{VideoUrl:e,VideoFormat:t,VideoSecond:s,VideoSize:r,VideoDownloadFlag:i,VideoUUID:n,ThumbUUID:o,ThumbFormat:a,ThumbWidth:u,SnapshotWidth:l,ThumbHeight:c,SnapshotHeight:d,ThumbSize:p,SnapshotSize:h,ThumbDownloadFlag:g,ThumbUrl:_,SnapshotUrl:m}=e;return new rn({videoUrl:e,videoFormat:t,videoSecond:s,videoSize:r,videoDownloadFlag:i,videoUUID:n,thumbUUID:o,thumbFormat:a,thumbWidth:u,snapshotWidth:l,thumbHeight:c,snapshotHeight:d,thumbSize:p,snapshotSize:h,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;C.isEmpty(e)||(this.content.thumbUrl=this.content.snapshotUrl=e),C.isEmpty(t)||(this.content.thumbWidth=this.content.snapshotWidth=Number(t)),C.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:i,videoUUID:n,thumbUUID:o,thumbFormat:a,thumbWidth:u,snapshotWidth:l,thumbHeight:c,snapshotHeight:d,thumbSize:p,snapshotSize:h,thumbDownloadFlag:g,thumbUrl:_,snapshotUrl:m}=e?this.payload:this.content;return{MsgType:this.type,MsgContent:{VideoUrl:C.removeAuthToUrl(e),VideoFormat:t,VideoSecond:s,VideoSize:r,VideoDownloadFlag:i,VideoUUID:n,ThumbUUID:o,ThumbFormat:a,ThumbWidth:u,SnapshotWidth:l,ThumbHeight:c,SnapshotHeight:d,ThumbSize:p,SnapshotSize:h,ThumbDownloadFlag:g,ThumbUrl:C.removeAuthToUrl(_),SnapshotUrl:C.removeAuthToUrl(m)}}}}var nn=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(qi,rn),e.subscribeInnerEvent(s.DESTROY,this._dispose,this)}createVideoMessage(e){var t,s,r;try{var i=this._processVideo(e),n=(e.payload.file=i,null==(t=this._core.store.get("login"))?void 0:t.userId),o=null==(r=null==(s=this._core)?void 0:s.message.messageFactory)?void 0:r.createMessage(Object.assign(Object.assign({},e),{from:n})),a={videoFormat:i.videoFile.type,videoSecond:Gi(i.videoFile.second,0),videoSize:i.videoFile.size,remoteVideoUrl:"",videoUrl:i.videoFile.url,videoUUID:C.generateUUID(i.videoFile),thumbUUID:C.generateUUID(i.videoFile,"jpg"),thumbWidth:i.width||200,thumbHeight:i.height||200,thumbUrl:i.thumbUrl,thumbSize:i.thumbSize,thumbFormat:"jpg"},u=new rn(a);return o.setElement(u),this._messageOptionsMap.set(o.clientSequence,e),o}catch(e){throw e}}upload(r){return I(this,void 0,void 0,function*(){var e=r.getElements()[0],t=this._messageOptionsMap.get(r.clientSequence).payload["file"],t=(this._validateBeforeUploadVideo(t),yield this._performVideoUpload(e,r,t)),{location:t,snapshotInfo:s}=t,t=C.addAuthToUrl(t);return e.updateVideoUrl(t),C.isEmpty(s)||e.updateSnapshotInfo(s),r})}_validateBeforeUploadVideo(e){var t=(null==(t=this._core)?void 0:t.helper)["ChatError"];if(e.videoFile.size>sn)throw new t({message:"File size exceeds limit: "+Pi(sn)});if(0===e.videoFile.size)throw new t({code:2108});if(-1===tn.indexOf(e.videoFile.type))throw new t({code:2352})}_performVideoUpload(r,i,s){return I(this,void 0,void 0,function*(){var e=i["to"],{response:e,uploadOptions:t}=yield ji.uploadToCOS({uploadFileType:2,file:s,to:e,message:i,onProgress:e=>{var t,s;r.updatePercent(e),null!=(s=null==(t=this._messageOptionsMap.get(i.clientSequence))?void 0:t.onProgress)&&s.call(t,e)}});return{snapshotInfo:yield this._getSnapshotInfoByUrl(t.requestSnapshotUrl),location:e.location}})}_processVideo(e){var r,i;try{var n=(null==(r=this._core)?void 0:r.helper)["ChatError"],{IN_MINI_APP:o,IN_BROWSER:a}=null==(i=this._core)?void 0:i.utils;let t=e.payload["file"],s={};if(o&&(s=this._processMiniVideoFile(t),t.name=s.name,t.url=s.url,t.type=s.type),a){let e=C.extractFileFromInput(t);if(!e)throw new n({message:"Invalid file. Pass either `e.target` (from file input) or a File object"});t=e,s=this._processWebVideoFile(t)}return t.videoFile=s,t.thumbUrl="",t.thumbSize=0,t}catch(e){throw console.warn(xi+" _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(Ri(e))throw new r({message:"FileUnsupportedInMiniApp"});let i=(e=Array.isArray(e.tempFiles)?e.tempFiles[0]:e).tempFilePath.slice(e.tempFilePath.lastIndexOf(".")+1).toLowerCase();return s&&(i=e.fileType||i),{url:e.tempFilePath,name:e.tempFilePath.slice(e.tempFilePath.lastIndexOf("/")+1),size:e.size||1,second:e.duration||0,type:i}}_processWebVideoFile(e){var{name:t,size:s=1,duration:r=0,type:i}=e,i=i.split("/")[1];return{url:window.URL.createObjectURL(e),name:t,size:s,second:r,type:i}}_getSnapshotInfoByUrl(n){return I(this,void 0,void 0,function*(){var e=this._core["ssoLog"];try{e.debug("_getSnapshotInfoByUrl",xi+" _getSnapshotInfoByUrl url:"+n);var t,s,r,i=((yield function(n,o){return I(this,void 0,void 0,function*(){try{var e="im_cos_msg.video_cover",{helper:t,channel:s}=o,r=t.generateCosSpecifiedData({servcmd:e,data:n}),i=r.head.seq+e;return yield s.sendPacket(r,{requestId:i})}catch(e){throw console.warn("getSnapshotInfo error:",e),e}})}({version:1,platform:C.getPlatform(),cover_name:bi(Li(99999)),snapshot_url:n},this._core))||{})["download_url"];return(e.debug("_getSnapshotInfoByUrl",xi+" _getSnapshotInfoByUrl OK snapshotUrl:"+i),C.isEmpty(i))?{}:(t=C.addAuthToUrl(i),{width:s=0,height:r=0}=yield C.probeImageWidthHeight(t),{snapshotUrl:t,snapshotWidth:s,snapshotHeight:r})}catch(e){throw e}})}_reset(){this._messageOptionsMap.clear()}_dispose(){this._reset();var{notificationCenter:e,InnerEvent:t}=this._core;e.unSubscribeInnerEvent(t.DESTROY,this._dispose,this)}};class on{constructor(e){this.uploadProgress=0,this.type=ki,this.content={downloadFlag:2,second:e.second,size:e.size,url:C.addAuthToUrl(e.url),remoteAudioUrl:C.addAuthToUrl(e.url||""),uuid:e.uuid}}static parseServerPushElement(e){var e=e["MsgContent"],{Url:e,Download_Flag:t,Second:s,Size:r,UUID:i}=e;return new on({url:e,downloadFlag:t,second:s,size:r,uuid:i})}updatePercent(e){this.uploadProgress=Math.min(e,1)}updateAudioUrl(e){this.content.remoteAudioUrl=e}validateBeforeSend(){var e=""!==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:i}=e?this.payload:this.content;return{MsgType:this.type,MsgContent:{Url:C.removeAuthToUrl(s),Download_Flag:t,Second:i,Size:r,UUID:e}}}}var an,un,ln,cn=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(ki,on),e.subscribeInnerEvent(s.DESTROY,this._dispose,this)}createAudioMessage(e){var t,s,r;try{var i=e.payload["file"],i=this._processAudioFile(e.payload.file),n=(e.payload.file=i,null==(t=this._core.store.get("login"))?void 0:t.userId),o=null==(r=null==(s=this._core)?void 0:s.message.messageFactory)?void 0:r.createMessage(Object.assign(Object.assign({},e),{from:n})),a={second:Math.floor((i.duration||i.second)/1e3),size:i.fileSize||i.size||1,url:i.tempFilePath||i.uri||i.url,uuid:C.generateUUID(i)},u=new on(a);return o.setElement(u),this._messageOptionsMap.set(o.clientSequence,e),o}catch(e){throw new this._core.helper.ChatError({code:null==e?void 0:e.code})}}upload(s){return I(this,void 0,void 0,function*(){var{ssoLog:e,utils:{safeStringify:t}}=this._core,e=(e.debug("upload",xi+" uploadAudio message:"+t(s)),this._messageOptionsMap.get(s.clientSequence).payload)["file"],t=(this._validateBeforeUploadAudio(e),s.getElements()[0]),e=yield this._performAudioUpload(t,s,e),e=C.addAuthToUrl(null==e?void 0:e.location);return t.updateAudioUrl(e),s})}_validateBeforeUploadAudio(e){var t=(null==(t=this._core)?void 0:t.helper)["ChatError"];if(!e)throw new t({code:2300});if(20971520<e.size)throw new t({message:"File size exceeds limit: "+Pi(20971520)});if(0===e.size)throw new t({code:2108})}_performAudioUpload(r,i,t){return I(this,void 0,void 0,function*(){var e=i["to"],e=(yield ji.uploadToCOS({uploadFileType:3,file:t,to:e,message:i,onProgress:e=>{var t,s;r.updatePercent(e),null!=(s=null==(t=this._messageOptionsMap.get(i.clientSequence))?void 0:t.onProgress)&&s.call(t,e)}}))["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 dn={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}},pn={createImageMessage:dn,createAudioMessage:dn,createVideoMessage:dn,createFileMessage:dn},hn={createImageMessage:!0,createAudioMessage:!0,createVideoMessage:!0,createFileMessage:!0},gn={TIMImageElem:zi,TIMFileElem:en,TIMVideoFileElem:nn,TIMSoundElem:cn},_n=new class{constructor(){this.name="RichMediaMessage"}install(e){let{OuterConstant:{MSG_AUDIO:t,MSG_FILE:s,MSG_IMAGE:r,MSG_VIDEO:i}}=(this._core=e)["constants"];Xi.init(e),zi.init(e),en.init(e),nn.init(e),cn.init(e),ji.init(e),C.init(e),e.helper.registerApi({apiName:"sendMessage",context:this,matcher:e=>[t,s,r,i].includes(e[0].type)}),e.helper.registerValidateConfig({auth:hn,params:pn})}sendMessage(r,i){return I(this,void 0,void 0,function*(){var e,t,s;try{return yield this._upload(r),yield null==(s=null==(t=null==(e=this._core)?void 0:e.message)?void 0:t.messageSender)?void 0:s.sendMessage(r,i)}catch(e){throw e}})}_upload(s){return I(this,void 0,void 0,function*(){let{ssoLog:t,utils:{safeStringify:e}}=this._core;if(t.debug("_upload"," uploadFile message:"+e(s)),!0!==s._relayFlag)try{let e=gn[s.type];e&&(yield e.upload(s),t.info("_upload"," type:"+s.type))}catch(t){throw s.status=Oi.FAIL,t instanceof Error&&(t.data={message:s}),this._core.message.messageDataHandler.storeConversationMessage(s),t}})}},M=new class{init(e){this.core=e}},mn=e=>{var{OuterConstant:t,utils:{isString:s}}=M["core"];return s(e)&&e.slice(0,3)===t.CONV_C2C},vn=e=>{var{OuterConstant:t,utils:{isString:s}}=M["core"];return s(e)&&e.slice(0,5)===t.CONV_GROUP},fn=e=>{var{OuterConstant:t,utils:{isString:s}}=M["core"];return s(e)&&e===t.CONV_SYSTEM},In=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:M.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 En(e){var t=M.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 Cn(e,t){var s=M.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 Sn{constructor(e){this.conversationID=e.conversationID||"",this.unreadCount=e.unreadCount||0,this.type=e.type||"",this.lastMessage=In(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}}=M["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}}=M["core"],{nextUnreadCount:e,isFromGetConversations:r,isUnreadC2CMessage:i}=e;s(e)||(this.subType!==t.GRP_AVCHATROOM?r&&this.type===t.CONV_GROUP||i&&this.type===t.CONV_C2C?this.unreadCount=e:this.unreadCount+=e:this.unreadCount=0)}updateLastMessage(e){this.lastMessage=In(e)}reduceUnreadCount(){return 1<=this.unreadCount&&(--this.unreadCount,!0)}isLastMessageRevoked(e){var t=M["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}}=M["core"];t(e,this.groupAtInfoList)}clearGroupAtInfoList(){this.groupAtInfoList.length=0}getProfileCompleted(){return this._isInfoCompleted}setProfileCompleted(){this._isInfoCompleted=!0}}(b=an=an||{})[b.OFF=0]="OFF",b[b.ON=1]="ON",un=un||{},un[un.ONLY_CONVERSATIONID=1]="ONLY_CONVERSATIONID",(N=ln=ln||{})[N.CONV_NOT_FOUND=2500]="CONV_NOT_FOUND",N[N.USER_OR_GRP_NOT_FOUND=2501]="USER_OR_GRP_NOT_FOUND",N[N.CONV_UN_RECORDED_TYPE=2502]="CONV_UN_RECORDED_TYPE";var y=new class{constructor(){this._name="ConversationDataHandler",this._totalUnreadCount=0,this._groupAtTipsList=[]}init(e){var{helper:t,notificationCenter:s,appStore:{conversationStore:r},constants:{WORKFLOW_NAME:i,WORKFLOW_STEP:n},InnerEvent:{SYNC_CONVERSATION_LIST:o,MESSAGE_PUSH:a,NEW_MESSAGE:u,MESSAGE_DELETED:l,MESSAGE_REVOKED:c,MESSAGE_MODIFIED:d,CONVERSATION_UPDATED:p,LOGOUT:h,DESTROY:g}}=this._core=e,r=(this._conversationStore=r,t.registerWorkflowStep(i.SYNC_SERVER_INFO_AFTER_LOGIN,n.CONVERSATION_UPDATE_AFTER_UNREAD_SYNC_FINISHED,this._handleUnreadSyncFinished,this),t.registerWorkflowStep(i.SYNC_SERVER_INFO_AFTER_LOGIN,n.CONVERSATION_UPDATE_AFTER_GROUP_LIST_SYNC_FINISHED,this._handleGroupListSyncFinished,this),t.registerWorkflowStep(i.RECEIVE_C2C_NEW_MESSAGE,n.CREATE_OR_UPDATE_CONVERSATION_BY_RECEIVE_NEW_MESSAGE,this._handleNewMessage,this),t.registerWorkflowStep(i.RECEIVE_C2C_NEW_MESSAGE,n.CONVERSATION_UPDATE_AFTER_UNREAD_SYNC_FINISHED,this._handleUnreadSyncFinished,this),t.registerWorkflowStep(i.RECEIVE_GROUP_NEW_MESSAGE,n.CREATE_OR_UPDATE_CONVERSATION_BY_RECEIVE_NEW_MESSAGE,this._handleNewMessage,this),t.registerWorkflowStep(i.SYNC_SERVER_INFO_AFTER_RE_ONLINE,n.CONVERSATION_UPDATE_AFTER_UNREAD_SYNC_FINISHED,this._handleUnreadSyncFinished,this),t.registerWorkflowStep(i.RECEIVE_GROUP_TIPS_NOTIFICATION,n.CREATE_OR_UPDATE_CONVERSATION_BY_RECEIVE_NEW_MESSAGE,this._handleNewMessage,this),s)["InnerEventSubType"]["GROUP_AT_TIPS"];s.subscribeInnerEvent(o,this._handleConversationSynced,this),s.subscribeInnerEvent(u,this._handleNewMessage,this),s.subscribeInnerEvent(a,r,this._handleNewGroupAtTips,this),s.subscribeInnerEvent(l,this._handleMessageDeleted,this),s.subscribeInnerEvent(c,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),e.ssoLog.debug(this._name+".init")}_handleConversationSynced(e){this.updateLocalConversationList({conversationUpdateFieldList:e.conversationUpdateFieldList||[],isFromGetConversations:!0,updateUnreadCount:!0}),this.emitConversationListUpdate()}_handleUnreadSyncFinished(e){let{WORKFLOW_STEP:t}=this._core["constants"],{conversationUpdateFieldList:s=[],groupTipList:r=[],isUnreadC2CMessage:i}=e.result[t.UNREAD_MESSAGE_SYNC]||{},n=!1;s.forEach(e=>{var{conversationID:e,unreadCount:t}=e,e=this.getLocalConversation(e);e&&e.unreadCount!==t&&(e.updateUnreadCount({nextUnreadCount:t,isUnreadC2CMessage:i}),n=!0)}),n&&this.emitConversationListUpdate(),this._handleGroupAtTipsSynced(r)}_handleGroupAtTipsSynced(t){var s;for(let e=0;e<t.length;e++)if(12===t[e].Event){if(null!=(s=t[e].GroupTips[0].MsgBody)&&s.TopicId)continue;this._handleNewGroupAtTips(t[e])}}_handleGroupListSyncFinished(e){let r,{WORKFLOW_STEP:t}=this._core.constants,i=e.result[t.GROUP_LIST_SYNC]||[],{CONV_GROUP:n}=this._core.OuterConstant,o=!1;for(let s=0;s<i.length;s++){let e=i[s],t=""+n+e.groupID;var a;this.hasLocalConversation(t)&&((a=this.getLocalConversation(t)).groupProfile=JSON.parse(JSON.stringify(e)),a.lastMessage.lastSequence<e.nextMessageSeq&&(a.lastMessage.lastSequence=e.nextMessageSeq-1),a.subType||(a.subType=e.type),0<(null==(r=e._groupAtInfoList)?void 0:r.length)&&this._handleNewGroupAtTips({GroupTips:e._groupAtInfoList}),o=!0)}o&&this.emitConversationListUpdate()}_handleNewMessage(e){var t,{conversationUpdateFieldList:e=[],isInstantMessage:s=!0,isUnreadC2CMessage:r=!1,updateUnreadCount:i=!0}=e.result||{};0===e.length||({isTopic:t}=this._core["common"],t(e[0].conversationID))||(this.updateLocalConversationList({conversationUpdateFieldList:e,isInstantMessage:s,isUnreadC2CMessage:r,isFromGetConversations:!1,updateUnreadCount:i}),0<e.filter(e=>this._isConversationNeedShow(e.conversationID)).length&&this.emitConversationListUpdate())}_handleNewGroupAtTips(e){var{GroupTips:e=[]}=e;e.forEach(e=>{var{GroupAtTips:t,MsgBody:s,MsgRandom:r,ClientSeq:i}=e;let n={};t?n=this._convertGroupAtTipsKey(t):s?n=Object.assign({},this._convertGroupAtTipsKey(s)):e.groupAtType&&(n=Object.assign({},e)),n.__random=r,n.__sequence=i,this._groupAtTipsList.push(n)}),console.log(this._name+"._handleNewGroupAtTips groupAtTipsList: "+JSON.stringify(this._groupAtTipsList)),this._updateGroupAtInfoList()}_convertGroupAtTipsKey(e){var{From_Account:e,GroupId:t,MsgSeq:s,GroupAtType:r}=e;return{from:e,groupID:t,sequence:s,groupAtType:r}}_updateGroupAtInfoList(){if(0!==this._groupAtTipsList.length){let{common:e,OuterConstant:r}=this._core,i=e.getCurrentUserID(),n=!1;this._groupAtTipsList.forEach(t=>{var{groupID:s,from:e}=t;if(e!==i){let e=this.getLocalConversation(""+r.CONV_GROUP+s);e&&(e.updateGroupAtInfoList(t),n=!0)}}),n&&this.emitConversationListUpdate(),this._groupAtTipsList.length=0}}_handleMessageDeleted(t){console.log(this._name+"._handleMessageDeleted, conversationID:",t);var s,{message:{messageDataHandler:r},OuterConstant:i}=this._core,n=(null==r?void 0:r.getLocalMessageList(t))||[];let o={};for(let e=(n.length||0)-1;0<=e;e--)if(!n[e].isDeleted){o=n[e];break}r=this.getLocalConversation(t);if(r){let e=!1;r.lastMessage.lastSequence===o.sequence&&r.lastMessage.lastTime===o.time||(null!=(s=null==(s=this._core)?void 0:s.helper)&&s.isEmpty(o)&&(o=void 0),r.updateLastMessage(o),e=!0),t.startsWith(i.CONV_C2C)&&this.updateUnreadCount(t),e&&(this.emitConversationListUpdate(),console.log(this._name+`._handleMessageDeleted. update conversationID:${t} with lastMessage:`,r.lastMessage))}}_handleMessageRevoked(e){let{messageList:r=[],updateUnreadCount:i=!0}=e;if(console.log(this._name+"._handleMessageRevoked messageList:"+r.length),0!==r.length){let t=null,s=!1;r.forEach(e=>{(t=this.getLocalConversation(e.conversationID))&&(i&&t.reduceUnreadCount()&&(s=!0),t.isLastMessageRevoked({sequence:e.sequence,time:e.time}))&&(t.setLastMessageRevoked(!0),t.setLastMessageRevoker(e.revoker),s=!0)}),s&&this.emitConversationListUpdate()}}_handleMessageModified(e){console.log(this._name+"._handleMessageModified",JSON.stringify(e));var{conversationID:t,messageList:s}=e,e=this.getLocalConversation(t),{utils:{isEmpty:r},common:{getMessagePreviewText:i}}=this._core;if(!r(e)){r=e["lastMessage"];if(r){let e=(null==s?void 0:s[0])||{};r.lastTime===e.time&&r.lastSequence===e.sequence&&r.version!==e.version&&(r.type=e.type,r.payload=e.payload,r.messageForShow=i(e.type,e.payload),r.cloudCustomData=e.cloudCustomData,r.version=e.version,this.emitConversationListUpdate(),console.log(this._name+` conversationID:${t} lastMessage updated`))}}}_handleConversationUpdated(e){this.emitConversationListUpdate(null==e?void 0:e.needSort)}updateLocalConversationList(e){var t=e["isFromGetConversations"],e=this._getTmpConversationListMapping(e)["newConversationList"];this._sortConversationList(),t||this._updateNewConversationProfile(e),this._core.ssoLog.debug("updateLocalConversationList"," newConversationList: "+e.length)}_getTmpConversationListMapping(e){let n=this._core["OuterConstant"],{conversationUpdateFieldList:o,isFromGetConversations:a,isInstantMessage:u,isUnreadC2CMessage:l=!1,updateUnreadCount:c}=e,d=[],t=null==o?void 0:o.length;for(let i=0;i<t;i++){let t=new Sn(o[i]),{conversationID:s,type:r}=t;if(!function(e){var t=M.core["OuterConstant"];let s;return"@TLS#ERROR"===(s=e.startsWith(t.CONV_C2C)?e.replace(t.CONV_C2C,""):s)||"@TLS#NOT_FOUND"===s}(s))if(this.hasLocalConversation(s)){let e=this.getLocalConversation(s);a?(this.setLocalConversation(s,t),r===n.CONV_C2C?t.unreadCount=(null==e?void 0:e.unreadCount)||0:r===n.CONV_GROUP&&(t.groupProfile=JSON.parse(JSON.stringify(null==e?void 0:e.groupProfile)))):(this._mergeConversationInfo({conversationID:s,tmpConversation:t,lastMessage:o[i].lastMessage,isFromGetConversations:a,isInstantMessage:u}),this._patchLastMessage({conversationID:s,lastMessage:o[i].lastMessage,isInstantMessage:u}),!0===c&&null!=e&&e.updateUnreadCount({nextUnreadCount:t.unreadCount,isFromGetConversations:a,isUnreadC2CMessage:l}))}else d.push(t),this.setLocalConversation(s,t)}return{newConversationList:d}}_mergeConversationInfo(e){var{conversationID:e,tmpConversation:t,lastMessage:s,isFromGetConversations:r,isInstantMessage:i}=e,e=this.getLocalConversation(e),n=["unreadCount","allowType","adminForbidType","payload"],{utils:{isUndefined:r,isEmpty:o},common:{deepMerge:a}}=(!1===i&&n.push("lastMessage"),r&&n.push("isPinned"),this._core);r(i)&&s&&null===(null==e?void 0:e.lastMessage.payload)&&(e.lastMessage.payload=s.payload),o(null==e?void 0:e.lastMessage.revoker)||(e.lastMessage.revoker=null),a(e,t,n,[null,void 0,"",0,NaN])}_patchLastMessage(e){let i=this._core["OuterConstant"],{conversationID:t,lastMessage:n,isInstantMessage:o}=e,a=this.getLocalConversation(t);if(a&&n){let{payload:e,nameCard:t,nick:s,cloudCustomData:r=""}=n;o&&(e&&(a.lastMessage.payload=e),a.type===i.CONV_GROUP)&&(a.lastMessage.nameCard=t,a.lastMessage.nick=s),a.lastMessage.cloudCustomData!==r&&(a.lastMessage.cloudCustomData=r)}}_sortConversationList(){let{isEmpty:t}=this._core["utils"],e=[...this._conversationStore.getConversationMap()],s=[],r=[],i=[],n=[];e.forEach(e=>{(!0===e[1].isPinned?t(e[1].lastMessage.lastTime)?r:s:t(e[1].lastMessage.lastTime)?n:i).push(e)});var o=s.sort((e,t)=>t[1].lastMessage.lastTime-e[1].lastMessage.lastTime).concat(r).concat(i.sort((e,t)=>t[1].lastMessage.lastTime-e[1].lastMessage.lastTime)).concat(n);this._updateConversationMapFromList(o)}_updateNewConversationProfile(e){if(0!==e.length){let s=[],r=[],{CONV_GROUP:i,CONV_C2C:n}=this._core["OuterConstant"];e.forEach(e=>{var{conversationID:t,type:e}=e;if(e===n){let e=t.replace(n,"");s.push(e)}else if(e===i){let e=t.replace(i,"");r.push(e)}}),0<s.length&&this._updateC2CConversation(s),0<r.length&&this._updateGroupConversation(r)}}_updateC2CConversation(e){let t,{OuterConstant:{CONV_C2C:i},appStore:{userStore:n},user:s}=this._core,o=!1;null!=(t=s.userProfile)&&t.getUserProfile({userIDList:e}).then(e=>{((null==e?void 0:e.data)||[]).forEach(t=>{var s=t["userID"],r=this.getLocalConversation(""+i+s);if(r){let e=(null==(s=n.getFriend(s))?void 0:s.remark)||"";r.remark=e,r.userProfile=t,o=!0}}),o&&this.emitConversationListUpdate()}).catch(e=>{})}_updateGroupConversation(e){let{OuterConstant:{CONV_GROUP:s},appStore:{groupStore:r}}=this._core,i=!1;e.forEach(e=>{var t=r.getGroup(e),e=this.getLocalConversation(""+s+e);t&&e&&(e.groupProfile=t,i=!0)}),i&&this.emitConversationListUpdate()}_isConversationNeedShow(e){var{OuterConstant:{CONV_GROUP:t,GRP_ROOM:s,GRP_LIVE:r},utils:{isUndefined:i}}=this._core,e=this.getLocalConversation(e);return!(!i(e)&&(i=e.type===t&&(null==(i=e.groupProfile)?void 0:i.type)===s,t=e.type===t&&(null==(s=e.groupProfile)?void 0:s.type)===r,i||t))}updateUnreadCount(e,t=!0){let s,r,i=!1;var n,o=this.getLocalConversation(e),a=null==(r=null==(s=this._core)?void 0:s.message.messageDataHandler)?void 0:r.getLocalMessageList(e);return o&&(n=o.unreadCount,a=null==a?void 0:a.filter(e=>!e.isRead&&!e._onlineOnlyFlag&&!e.isDeleted).length,console.log(this._name+`._updateUnreadCount conversationID:${e} currentUnreadCount:${n} newUnreadCount:`+a),n!==a)&&(o.unreadCount=a,(i=!0)===t)&&this.emitConversationListUpdate(),i}emitConversationListUpdate(e=!1){e&&this._sortConversationList();var e=this._core["OuterEvent"]["CONVERSATION_LIST_UPDATED"],t=this.getLocalConversationList();this._emitEvent({name:e,data:t}),this._emitTotalUnreadCountUpdate()}_emitTotalUnreadCountUpdate(){var e,t=this.getTotalUnreadMessageCount();this._totalUnreadCount!==t&&(this._core.ssoLog.debug("_emitTotalUnreadCountUpdate",` from ${this._totalUnreadCount} to `+t),this._totalUnreadCount=t,this._emitEvent({name:null==(e=this._core)?void 0:e.OuterEvent.TOTAL_UNREAD_MESSAGE_COUNT_UPDATED,data:t}))}_emitEvent(e){var t;null!=(t=this._core)&&t.notificationCenter.emitOuterEvent(e.name,e)}getTotalUnreadMessageCount(){let{OuterConstant:t,utils:{isEmpty:s}}=this._core,e=this.getLocalConversationList(),r=0;return e.forEach(e=>{e.type===t.CONV_SYSTEM||!s(e.messageRemindType)&&e.messageRemindType!==t.MSG_REMIND_ACPT_AND_NOTE||(r+=e.unreadCount)}),r}getLocalConversationList(){return[...this._conversationStore.getConversationMap().values()].filter(e=>this._isConversationNeedShow(e.conversationID))}hasLocalConversation(e){return this._conversationStore.getConversationMap().has(e)}getLocalConversation(e){return this._conversationStore.getConversationMap().get(e)}setLocalConversation(e,t){return this._conversationStore.getConversationMap().set(e,t)}deleteLocalConversation(e){this._conversationStore.getConversationMap().delete(e)}_updateConversationMapFromList(e){this._clearConversationMap();for(var[t,s]of e)this.setLocalConversation(t,s)}_clearConversationMap(){this._conversationStore.getConversationMap().clear()}patchMessageRemindType(e,t){let s=!1;e.forEach(e=>{e=this.getLocalConversation(e);(null==e?void 0:e.messageRemindType)!==t&&(e.messageRemindType=t,s=!0)}),console.log(this._name+`.patchMessageRemindType conversationIDList:${e} messageRemindType:${t} hasUpdated:`+s),s&&this.emitConversationListUpdate()}markMessageAsRead(e){let{messageDataHandler:t}=this._core["message"],{conversationID:s,lastReadTime:i=0,lastReadSequence:n=0}=e,o=null==t?void 0:t.getLocalMessageList(s);if(0!==o.length){let e=o["length"];for(let r=e-1;0<=r;r--){let e=o[r],t=i&&e.time>i,s=n&&e.sequence>n;if(!t&&!s){if("in"===e.flow&&e.isRead)break;e.setIsRead(!0)}}}}appendToPinnedConversation(e){var t=[...this._conversationStore.getConversationMap().entries()],s=t.findIndex(e=>!1===e[1].isPinned);t.splice(s,0,[e.conversationID,e]),this._updateConversationMapFromList(t),this.emitConversationListUpdate()}_reset(){this._clearConversationMap(),this._totalUnreadCount=0,this._groupAtTipsList=[]}_dispose(){var{notificationCenter:e,InnerEvent:{NEW_MESSAGE:t,MESSAGE_DELETED:s,MESSAGE_REVOKED:r,MESSAGE_MODIFIED:i,CONVERSATION_UPDATED:n,LOGOUT:o,DESTROY:a,SYNC_CONVERSATION_LIST:u}}=this._core,{GROUP_AT_TIPS:l}=e["InnerEventSubType"];e.unSubscribeInnerEvent(t,this._handleNewMessage,this),e.unSubscribeInnerEvent(t,l,this._handleNewGroupAtTips,this),e.unSubscribeInnerEvent(s,this._handleMessageDeleted,this),e.unSubscribeInnerEvent(r,this._handleMessageRevoked,this),e.unSubscribeInnerEvent(i,this._handleMessageModified,this),e.unSubscribeInnerEvent(n,this._handleConversationUpdated,this),e.unSubscribeInnerEvent(u,this._handleConversationSynced,this),e.unSubscribeInnerEvent(o,this._reset,this),e.unSubscribeInnerEvent(a,this._dispose,this)}},Mn=new class{constructor(){this._name="GetConversationList"}init(e){e=(this._core=e).helper;e.registerApi({apiName:"getConversationList",context:this})}getConversationList(e){return I(this,void 0,void 0,function*(){return{code:0,data:{conversationList:this._getConversationList(e),isSyncCompleted:this._core.conversation.syncConversationHandler.isSyncCompleted()}}})}_getConversationList(o){let{isUndefined:e,isArray:t,isPlainObject:s}=this._core["utils"];if(e(o))return y.getLocalConversationList();if(t(o))return 0===o.length?[]:y.getLocalConversationList().filter(e=>o.includes(e.conversationID));if(s(o)){let{type:t,markType:s,groupName:r,hasUnreadCount:i,hasGroupAtInfo:n}=o;return y.getLocalConversationList().filter(e=>this._filterType(e,t)&&this._filterMarkType(e,s)&&this._filterGroupName(e,r)&&this._filterUnreadCount(e,i)&&this._filterGroupAtInfo(e,n))}return[]}_filterType(e,t){var s=this._core["OuterConstant"];return t!==s.CONV_C2C&&t!==s.CONV_GROUP||e.type===t}_filterGroupName(e,t){var{isString:s}=this._core["utils"];return!s(t)||(""===t?0===e.conversationGroupList.length:e.conversationGroupList.includes(t))}_filterMarkType(e,t){var{isNumber:s}=this._core["utils"];return!s(t)||(0===t?0===e.markList.length:e.markList.includes(t))}_filterUnreadCount(e,t){let s=!0;return!0===t?s=1<=e.unreadCount:!1===t&&(s=0===e.unreadCount),s}_filterGroupAtInfo(e,t){let s=!0;return!0===t?s=1<=e.groupAtInfoList.length:!1===t&&(s=0===e.groupAtInfoList.length),s}},yn=new class{constructor(){this._name="GetC2CMessageRemindType"}init(e){this._core=e}get(r){return I(this,void 0,void 0,function*(){try{var e=this._core["common"],t=yield function(s,r){return I(this,void 0,void 0,function*(){var{toAccount:e,userIDList:t}=s;return r.common.buildAndSendPacket({servcmd:"openim.get_c2c_peer_mute_notifications",data:{To_Account:e,Peer_Account:t}})})}({toAccount:e.getCurrentUserID(),userIDList:r},this._core),{MuteNotificationsList:s=[]}=t||{};s.forEach(e=>{var{Peer_Account:e,MuteNotifications:t}=e,e=""+this._core.OuterConstant.CONV_C2C+e,t=En(t);y.patchMessageRemindType([e],t)})}catch(e){console.error(this._name+".get fail:",e)}})}},Tn=new class{constructor(){this._name="GetGroupMessageRemindType"}init(e){this._core=e}get(s){return I(this,void 0,void 0,function*(){if(0!==s.length)try{var e=yield function(s,r){return I(this,void 0,void 0,function*(){var{groupIDList:e,responseFilter:t}=s;return r.common.buildAndSendPacket({servcmd:"group_open_http_svc.get_group_self_member_info",data:{GroupIdList:e,ResponseFilter:t}})})}({groupIDList:s,responseFilter:{MemberInfoFilter:["MsgFlag"]}},this._core),{GroupInfo:t=[]}=e||{};t.forEach(e=>{var{GroupId:e,MemberList:t}=e,t=(null==(t=t[0])?void 0:t.MsgFlag)||"",e=""+this._core.OuterConstant.CONV_GROUP+e;y.patchMessageRemindType([e],t)})}catch(e){console.error(this._name+".get fail:",e)}})}},An=new class{constructor(){this._name="GetConversationProfile"}init(e){e=(this._core=e).helper;e.registerApi({apiName:"getConversationProfile",context:this})}getConversationProfile(l){return I(this,void 0,void 0,function*(){let{OuterConstant:{CONV_C2C:s,CONV_GROUP:r,GRP_AVCHATROOM:i},appStore:{groupStore:n},utils:{isEmpty:e}}=this._core,o={code:0,data:{}},a=y.getLocalConversation(l);if(fn(l))o.data.conversation=a;else{let t=!1;var u=mn(l)?s:r;if(e(a)&&(t=!0,a=new Sn({conversationID:l,type:u})),console.log(this._name+`.getConversationProfile conversationID:${l} isNewConversation:`+t),null==(o.data.conversation=a)||!a.getProfileCompleted()){if(u===s){let e=l.replace(s,"");yield this._handleC2CConversation(a,e),t&&(yield yn.get([e]))}if(u===r){let e=l.replace(r,"");if(!n.getGroup(e))return o;yield this._handleGroupConversation(a,e),t&&a.groupProfile.type!==i&&(yield Tn.get([e]))}}}return o})}_handleC2CConversation(o,a){return I(this,void 0,void 0,function*(){var{user:e,helper:t,utils:{isEmpty:s},appStore:{conversationStore:r,userStore:i}}=this._core,n=o["conversationID"],e=yield null==(e=e.userProfile)?void 0:e.getUserProfile({userIDList:[a]});if(0===(null==e?void 0:e.data.length))throw new t.ChatError({code:ln.USER_OR_GRP_NOT_FOUND});o.userProfile=null==e?void 0:e.data[0];e=null==(t=i.getFriend(a))?void 0:t.remark,s(e)||o.remark===e||(o.remark=e),o.setProfileCompleted(),i=y.hasLocalConversation(n);console.log(this._name+`._handleC2CConversation conversationID:${n} hasLocalConversation: `+i),i?r.updateConversation(n,o):y.appendToPinnedConversation(o)})}_handleGroupConversation(r,i){return I(this,void 0,void 0,function*(){var{apiMap:{getGroupProfile:e},appStore:{conversationStore:t}}=this._core,s=r["conversationID"],e=yield e({groupID:i}),e=(r.groupProfile=null==e?void 0:e.data.group,r.setProfileCompleted(),y.hasLocalConversation(s));console.log(this._name+`._handleGroupConversation conversationID:${s} hasLocalConversation: `+e),e?t.updateConversation(s,r):y.appendToPinnedConversation(r)})}},On=new class{init(e){e=e.helper;e.registerApi({apiName:"getTotalUnreadMessageCount",context:this})}getTotalUnreadMessageCount(){return y.getTotalUnreadMessageCount()}},Dn=new class{constructor(){this._serverGroupConversationLastReadSeqMap=new Map,this._name="SetMessageRead"}init(e){let{helper:t,common:{isTopic:s},notificationCenter:r,InnerEvent:{MESSAGE_PUSH:i},InnerEventSubType:{ALL_MESSAGE_READ:n}}=this._core=e;t.registerApi({apiName:"setMessageRead",context:this,matcher:e=>!s(e[0].conversationID)}),t.registerApi({apiName:"setAllMessageRead",context:this}),r.subscribeInnerEvent(i,n,this._handleAllMessageRead,this)}handleC2CMessageReadSync(e){let{helper:{isEmpty:s},OuterConstant:r}=this._core;e.forEach(e=>{var t=e["ReadC2cMsgNotify"];if(!s(t)){let{UinPairReadArray:e=[]}=t;e.forEach(e=>{var{From_Account:e,LastReadTime:t}=e,e=""+r.CONV_C2C+e;console.log(this._name+`.handleC2CMessageReadSync conversationID:${e} lastReadTime:`+t),y.markMessageAsRead({conversationID:e,lastReadTime:t}),y.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),y.markMessageAsRead({conversationID:e,lastReadSequence:t}),y.updateUnreadCount(e),this._clearGroupAtInfoList(e)})})}setMessageRead(u){return I(this,void 0,void 0,function*(){var e,t=this._core["OuterConstant"],s=u["conversationID"],r={code:0,data:{}},i=y.getLocalConversation(s);let n=this._name+`.setMessageRead conversationID:${s} unreadCount:`+((null==i?void 0:i.unreadCount)||0);if(r.successLog={message:n},!i)return r;var o=!(null!=(e=null==(o=this._core)?void 0:o.helper)&&e.isEmpty(i.groupAtInfoList));if(i.type===t.CONV_GROUP&&o&&this._deleteGroupAtTips(s),0===i.unreadCount)return r;var a=this._core["helper"]["ChatError"];try{if(i.type===t.CONV_C2C){let e=this._getLocalMessageMaxTime(i);yield this._setC2CMessageRead(s,e),n+="lastMessageTime:"+e}if(i.type===t.CONV_GROUP){let e=this._getLocalMessageMaxSequence(i);yield this._setGroupMessageRead(s,e),n+="lastMessageSequence:"+e}}catch(e){let{errorCode:t,errorInfo:s}=e;throw new a({functionName:"setMessageRead",code:t,message:s,moreMessage:n})}return i.type===t.CONV_SYSTEM&&(i.unreadCount=0),y.emitConversationListUpdate(),Object.assign(Object.assign({},r),{successLog:{message:n}})})}setAllMessageRead(){return I(this,arguments,void 0,function*(t={}){let{OuterConstant:{READ_ALL_MSG:e},utils:{safeStringify:i}}=this._core,n="scope:"+t.scope,s=(t.scope||(t.scope=e),t)["scope"],o=this._generateSetAllMessageReadRequestData(s);if(0===o.allC2CMessageReadStatus&&0===o.groupMessageReadInfoList.length)return{code:0};try{let r=yield function(s){return I(this,void 0,void 0,function*(){var{allC2CMessageReadStatus:e,groupMessageReadInfoList:t}=s,e={C2CReadAllMsg:e,GroupReadInfo:t};return M.core.common.buildAndSendPacket({servcmd:"openim.read_all_unread_msg",data:e})})}(o);if(r){let{GroupReadInfoArray:e,C2CReadAllMsg:t}=r,s=this._parseGroupReadInfo(e);0<this._updateAllConversationReadStatus({allC2CMessageReadStatus:t})&&y.emitConversationListUpdate(),n+="failureGroupInfoList:"+i(s)}return{code:0,successLog:{message:n}}}catch(t){let e=t["errorCode"];throw new this._core.helper.ChatError({functionName:"setAllMessageRead",code:e,moreMessage:n})}})}_handleAllMessageRead(e){var{GroupReadInfoArray:e,C2CReadAllMsg:t}=e;this._parseGroupReadInfo(e),0<this._updateAllConversationReadStatus({allC2CMessageReadStatus:t})&&y.emitConversationListUpdate()}_updateAllConversationReadStatus(e){let{OuterConstant:{CONV_C2C:r,CONV_GROUP:i},appStore:t}=this._core,n=t.conversationStore.getConversationMap(),o=e["allC2CMessageReadStatus"],a=0;for(let[s,t]of n)if(1<=t.unreadCount){if(1===o&&t.type===r){let e=this._getLocalMessageMaxTime(t);y.markMessageAsRead({conversationID:s,lastReadTime:e})}else if(t.type===i){let t=s.replace(i,"");if(this._serverGroupConversationLastReadSeqMap.has(t)){let e=this._serverGroupConversationLastReadSeqMap.get(t);y.markMessageAsRead({conversationID:s,lastReadSequence:e})}}y.updateUnreadCount(s,!1)&&(a+=1)}return a}_generateSetAllMessageReadRequestData(r){let{OuterConstant:{CONV_C2C:i,CONV_GROUP:n,READ_ALL_C2C_MSG:o},appStore:e}=this._core,a={allC2CMessageReadStatus:0,groupMessageReadInfoList:[]},t=e.conversationStore.getConversationMap();for(let[,s]of t){let{type:e,unreadCount:t}=s;if(this._shouldSetAllMessageRead({scope:r,type:e,unreadCount:t}))if(e===i&&0===a.allC2CMessageReadStatus){if(a.allC2CMessageReadStatus=1,r===o)break}else if(e===n){let e=this._getLocalMessageMaxSequence(s),t=s.groupProfile["groupID"];a.groupMessageReadInfoList.push({GroupId:t,MsgSeq:e})}}return a}_parseGroupReadInfo(e){let{isUndefined:i}=this._core["utils"],n=[];return null!=e&&e.forEach(e=>{var{GroupId:e,MsgSeq:t,RetCode:s,LastReadMsgSeq:r}=e;i(s)?this._serverGroupConversationLastReadSeqMap.set(e,r):(this._serverGroupConversationLastReadSeqMap.set(e,t),0!==s&&n.push(e+`-${t}-`+s))}),n}_deleteGroupAtTips(o){return I(this,void 0,void 0,function*(){console.log(this._name+"._deleteGroupAtTips conversationID:"+o);let e=y.getLocalConversation(o);if(e){var n=(null==e?void 0:e.groupAtInfoList)||[];if(0!==n.length)try{let{common:{getCurrentUserID:t,isCommunity:e},OuterConstant:{CONV_GROUP:s,CONV_AT_ALL:r}}=this._core,i=[...n];e({groupID:o.replace(s,"")})&&0===(i=n.filter(e=>!e.atTypeArray.includes(r))).length?this._clearGroupAtInfoList(o,!1):(yield function(t,s){return I(this,void 0,void 0,function*(){var e=t["messageListToDelete"];return s.common.buildAndSendPacket({servcmd:"openim.deletemsg",data:{DelMsgList:e}})})}({messageListToDelete:i.map(e=>({From_Account:e.from,To_Account:t(),MsgSeq:e.__sequence,MsgRandom:e.__random,GroupId:e.groupID}))},this._core),console.log(this._name+"._deleteGroupAtTips ok. count:"+n.length),this._clearGroupAtInfoList(o))}catch(e){console.error(this._name+"._deleteGroupAtTips fail:",e)}}})}_clearGroupAtInfoList(e,t=!0){var s=y.getLocalConversation(e);s&&(0<s.groupAtInfoList.length&&(s.clearGroupAtInfoList(),console.log(this._name+`._clearGroupAtInfoList conversationID:${e} needEmitConversationUpdate:`+t)),t)&&y.emitConversationListUpdate()}_getLocalMessageMaxTime(e){var t=e["conversationID"],t=this._core.message.messageDataHandler.getLocalMessageList(t),t=Math.max(...t.map(e=>e.time));let s=(null==(e=null==e?void 0:e.lastMessage)?void 0:e.lastTime)||0;return t>s&&(console.log(`${this._name}._getLocalMessageMaxTime update lastMessageTime from ${s} to `+t),s=t),s}_getLocalMessageMaxSequence(e){var t=e["conversationID"],t=this._core.message.messageDataHandler.getLocalMessageList(t),t=Math.max(...t.map(e=>e.sequence));let s=(null==(e=null==e?void 0:e.lastMessage)?void 0:e.lastSequence)||0;return t>s&&(console.log(`${this._name}._getLocalMessageMaxSequence update lastMessageSequence from ${s} to `+t),s=t),s}_setC2CMessageRead(e,t){return I(this,void 0,void 0,function*(){try{yield function(e,t){return I(this,void 0,void 0,function*(){return t.common.buildAndSendPacket({servcmd:"openim.msgreaded",data:e})})}({C2CMsgReaded:{Cookie:"",C2CMsgReadedItem:[{To_Account:e.replace("C2C",""),LastedMsgTime:t,Receipt:1}]}},this._core),console.log(this._name+"._setC2CMessageRead ok, lastReadTime:"+t),y.markMessageAsRead({conversationID:e,lastReadTime:t}),y.updateUnreadCount(e)}catch(e){throw console.warn(this._name+"._setC2CMessageRead fail:",e),e}})}_setGroupMessageRead(e,t){return I(this,void 0,void 0,function*(){try{yield function(s,r){return I(this,void 0,void 0,function*(){var{groupID:e,lastMessageSequence:t}=s;return r.common.buildAndSendPacket({servcmd:"group_open_http_svc.msg_read_report",data:{GroupId:e,MsgReadedSeq:t}})})}({groupID:e.replace("GROUP",""),lastMessageSequence:t},this._core),console.log(this._name+"._setGroupMessageRead ok, lastReadSequence:"+t),y.markMessageAsRead({conversationID:e,lastReadSequence:t}),y.updateUnreadCount(e)}catch(e){throw console.warn(this._name+"._setGroupMessageRead fail:",e),e}})}_shouldSetAllMessageRead(e){var{CONV_C2C:t,CONV_GROUP:s,READ_ALL_MSG:r,READ_ALL_C2C_MSG:i,READ_ALL_GROUP_MSG:n}=this._core["OuterConstant"],{type:e,scope:o,unreadCount:a}=e;return!(a<=0||(e!==t||![r,i].includes(o))&&(e!==s||![r,n].includes(o)))}},Rn=new class{constructor(){this._name="PinConversation"}init(e){e=(this._core=e).helper;e.registerApi({apiName:"pinConversation",context:this})}handleConversationPinned(e,o){var{isArray:t}=this._core["utils"];if(t(e)){let i=this._core["OuterConstant"],n=!1;e.forEach(e=>{var{Type:e,To_Account:t,GroupId:s}=e;let r;1===e?r=y.getLocalConversation(""+i.CONV_C2C+t):2===e&&(r=y.getLocalConversation(""+i.CONV_GROUP+s)),r&&(console.log(`${this._name}.handleConversationPinned conversationID:${r.conversationID} localPinned:${r.isPinned} remotePinned:`+o),o&&!r.isPinned&&(r.isPinned=!0,n=!0),!o)&&r.isPinned&&(r.isPinned=!1,n=!0)}),n&&y.emitConversationListUpdate(!0)}}pinConversation(e){return I(this,void 0,void 0,function*(){let{OuterConstant:s,common:r,helper:{ChatError:i}}=this._core,{conversationID:n,isPinned:o}=e,a={code:0,data:{conversationID:n}},u=y.getLocalConversation(n);if(u&&u.isPinned===o)return a;if(fn(n))return u&&(u.isPinned=o),y.emitConversationListUpdate(!0),a;var l=`conversationID:${n} isPinned:`+o;try{let e=null,t=(mn(n)?e={Type:1,To_Account:n.replace(s.CONV_C2C,"")}:vn(n)&&(e={Type:2,GroupId:n.replace(s.CONV_GROUP,"")}),yield function(r,i){return I(this,void 0,void 0,function*(){var{fromAccount:e,operationType:t,itemList:s}=r;return i.common.buildAndSendPacket({servcmd:"recentcontact.top",data:{From_Account:e,OperationType:t,RecentContactItem:s}})})}({fromAccount:r.getCurrentUserID(),operationType:!0===o?1:2,itemList:[e]},this._core));if(t){if(u)u.isPinned!==o&&(u.isPinned=o);else{let e=new Sn({conversationID:n,type:mn(n)?s.CONV_C2C:s.CONV_GROUP,isPinned:o});y.setLocalConversation(n,e)}y.emitConversationListUpdate(!0)}return Object.assign(Object.assign({},a),{successLog:{message:l}})}catch(e){let{errorCode:t,errorInfo:s}=e;throw new i({functionName:"pinConversation",code:t,message:s,moreMessage:l})}})}},Ln=new class{constructor(){this._name="DeleteConversation"}init(e){e=(this._core=e).helper;e.registerApi({apiName:"deleteConversation",context:this})}handleConversationDeleted(e){var{isArray:t}=this._core["utils"];if(t(e)){let r=this._core["OuterConstant"],i=[];e.forEach(e=>{var{Type:e,Peer_Account:t,GroupId:s}=e;1===e&&i.push(""+r.CONV_C2C+t),2===e&&i.push(""+r.CONV_GROUP+s)}),console.log(this._name+".handleConversationDeleted conversationIDList:"+i),this._deleteLocalConversationList(i)}}deleteConversation(t){return I(this,void 0,void 0,function*(){var e=this._core["utils"]["isString"];e(t)?yield this._deleteConversation({conversationIDList:[t],flag:un.ONLY_CONVERSATIONID}):(100<(e=Object.assign({},t)).conversationIDList.length&&(e.conversationIDList=e.conversationIDList.slice(0,100)),yield this._deleteConversation(e))})}_deleteConversation(e){return I(this,void 0,void 0,function*(){let{conversationIDList:s,clearHistoryMessage:r=!0,flag:i=0}=e,{ChatError:n}=this._core["helper"],o=`conversationIDList:${s} clearHistoryMessage:`+r;try{let e=yield Promise.all([this._deleteConversationFromLocal(s),this._deleteConversationFromServer(s,r)]),t=[...e[0],...e[1]];if(0===t.length)throw new this._core.helper.ChatError({code:ln.CONV_NOT_FOUND});return{code:0,data:i===un.ONLY_CONVERSATIONID?{conversationID:t[0]}:{conversationIDList:t},successLog:{message:o}}}catch(e){let{errorCode:t,errorInfo:s}=e;throw new n({code:t,message:s,moreMessage:o})}})}_deleteConversationFromLocal(e){let s=this._core["OuterConstant"];return e.filter(e=>{var t;return!!y.hasLocalConversation(e)&&((t=null==(t=y.getLocalConversation(e))?void 0:t.type)===s.CONV_GROUP&&!this._hasLocalGroup(e)||t===s.CONV_SYSTEM)&&(this._deleteLocalConversation(e),!0)})}_deleteConversationFromServer(t,n){return I(this,void 0,void 0,function*(){let{OuterConstant:r,common:e}=this._core,i={fromAccount:e.getCurrentUserID(),conversationList:[],clearHistoryMessage:n?1:0};if(t.forEach(e=>{var t,s;y.hasLocalConversation(e)&&(t=(null==(t=y.getLocalConversation(e))?void 0:t.type)||"",s=e.replace(t,""),t===r.CONV_C2C?i.conversationList.push({To_Account:s,Type:1}):t===r.CONV_GROUP&&this._hasLocalGroup(e)&&i.conversationList.push({ToGroupid:s,Type:2}))}),0!==i.conversationList.length){var s=yield function(r,i){return I(this,void 0,void 0,function*(){var{fromAccount:e,conversationList:t,clearHistoryMessage:s}=r;return i.common.buildAndSendPacket({servcmd:"recentcontact.batch_delete",data:{From_Account:e,ContactItem:t,ClearRamble:s}})})}(i,this._core);if(s){let{ResultItem:e=[]}=s,t=[];return 0<e.length&&e.forEach(e=>{0===e.ResultCode&&(e=1===e.Type?""+r.CONV_C2C+e.To_Account:""+r.CONV_GROUP+e.ToGroupid,t.push(e))}),this._deleteLocalConversationList(t),t}}return[]})}_deleteLocalConversationList(e){let t=!1;e.forEach(e=>{y.hasLocalConversation(e)&&(this._deleteLocalConversation(e,!1),t=!0)}),console.log(this._name+"._deleteLocalConversationList isUpdate:"+t),t&&y.emitConversationListUpdate()}_deleteLocalConversation(e,t=!0){var s=y.hasLocalConversation(e);console.log(this._name+`._deleteLocalConversation conversationID:${e} has:`+s),s&&(y.deleteLocalConversation(e),this._deleteConversationLocalMessage(e),t)&&y.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)}},Nn=new class{constructor(){this._name="SetConversationDraft"}init(e){e=(this._core=e).helper;e.registerApi({apiName:"setConversationDraft",context:this})}setConversationDraft(s){return I(this,void 0,void 0,function*(){var{conversationID:e,draftText:t}=s;if(console.log(this._name+` conversationID:${e} draftText:`+t),y.hasLocalConversation(e))return null!=(e=y.getLocalConversation(e))&&e.setDraftText(t),y.emitConversationListUpdate(),{code:0,data:{conversation:e}};throw new this._core.helper.ChatError({code:ln.CONV_NOT_FOUND})})}},bn=new class{constructor(){this._name="SetC2CMessageRemindType"}init(e){this._core=e}set(a,u){return I(this,void 0,void 0,function*(){30<a.length&&(console.warn(`${this._name}.set userIDList length:${a.length} exceeds limit 30`),a.splice(30));let e=function(){var{MSG_REMIND_ACPT_AND_NOTE:e,MSG_REMIND_DISCARD:t,MSG_REMIND_ACPT_NOT_NOTE:s}=M.core.OuterConstant;return{[e]:0,[t]:1,[s]:2}}()[u],t=yield function(s,r){return I(this,void 0,void 0,function*(){var{userIDList:e,receiveMessageOption:t}=s;return r.common.buildAndSendPacket({servcmd:"openim.set_c2c_peer_mute_notifications",data:{Peer_Account:e,Mute_Notifications:t}})})}({userIDList:a,receiveMessageOption:e},this._core),{ErrorList:s=[]}=t||{},r=[],i=(s.forEach(e=>{var{Peer_Account:e,ErrorCode:t}=e,t=(r.push({userID:e,code:t}),a.indexOf(e));-1<t&&a.splice(t,1)}),[]),n=[],o=this._core["OuterConstant"];return a.forEach(e=>{n.push(""+o.CONV_C2C+e),i.push({userID:e})}),y.patchMessageRemindType(n,u),{code:0,data:{successUserIDList:i,failureUserIDList:r}}})}},Gn=new class{constructor(){this._name="SetGroupMessageRemindType"}init(e){this._core=e}set(r,i){return I(this,void 0,void 0,function*(){let{common:{getCurrentUserID:e,isTopic:t},OuterConstant:s}=this._core;if(yield function(r,i){return I(this,void 0,void 0,function*(){var{groupID:e,userID:t,receiveMessageOption:s}=r;return i.common.buildAndSendPacket({servcmd:"group_open_http_svc.modify_group_member_info",data:{GroupId:e,Member_Account:t,MsgFlag:s}})})}({groupID:r,userID:e(),receiveMessageOption:i},this._core),!t(r)){let e=""+s.CONV_GROUP+r;y.patchMessageRemindType([e],i)}return{code:0,data:{groupID:r,messageRemindType:i}}})}},Pn=new class{constructor(){this._name="SetMessageRemindType"}init(e){e=(this._core=e).helper;e.registerApi({apiName:"setMessageRemindType",context:this})}handleC2CMessageRemindTypeSync(e){let{helper:{isEmpty:t},OuterConstant:n,ssoLog:o}=this._core;e.forEach(e=>{var i=e["MuteNotificationsSync"];if(!t(i)){let{To_Account:e,MuteNotifications:t}=i,s=e.map(e=>""+n.CONV_C2C+e),r=En(t);o.debug(this._name+`.handleC2CMessageRemindTypeSync conversationIDList:${s} messageRemindType:`+r),y.patchMessageRemindType(s,r)}})}setMessageRemindType(a){return I(this,void 0,void 0,function*(){let s="setMessageRemindType",{groupID:e,userIDList:t,messageRemindType:r}=a,{helper:i,utils:{isUndefined:n},ssoLog:o}=this._core;try{if(!n(e))return o.debug(`${this._name}.${s} groupID:${e} messageRemindType:`+r),yield Gn.set(e,r);if(n(t))throw new i.ChatError({functionName:s,message:"userIDList or groupID is required"});return o.debug(this._name+`.${s} userIDList:${t} messageRemindType:`+r),yield bn.set(t,r)}catch(e){let t=new i.ChatError({functionName:s,code:null==e?void 0:e.errorCode,message:null==e?void 0:e.errorInfo});throw console.error(this._name+`.${s} fail:`,t),t}})}},wn=new class{init(e){e.ssoLog.debug("ConversationAction.init"),this._core=e,Mn.init(e),An.init(e),On.init(e),Dn.init(e),Rn.init(e),Ln.init(e),Nn.init(e),Pn.init(e);var{notificationCenter:e,InnerEvent:{MESSAGE_PUSH:t,DESTROY:s}}=this._core,{CONV_MODIFIED:r,C2C_MESSAGE_READ_SYNC:i,GROUP_MESSAGE_READ_SYNC:n,C2C_REMIND_TYPE_SYNC:o}=e["InnerEventSubType"];e.subscribeInnerEvent(t,r,this._onConversationModified,this),e.subscribeInnerEvent(t,i,this._onC2CMessageReadSync,this),e.subscribeInnerEvent(t,o,this._onC2CMessageRemindTypeSync,this),e.subscribeInnerEvent(t,n,this._onGroupMessageReadSync,this),e.subscribeInnerEvent(s,this._dispose,this)}_onConversationModified(e){let{ConvModifyPushType:s}=this._core["constants"],{RecentContactMod:t=[]}=e;t.forEach(t=>{var e=t["PushType"];if(e===s.CONV_DELETED){let e=t.RecentContactDeleteItem["RecentContactList"];Ln.handleConversationDeleted(e)}if(e===s.CONV_PINED){let e=t.RecentContactTopItem["RecentContactList"];Rn.handleConversationPinned(e,!0)}if(e===s.CONV_UNPINED){let e=t.RecentContactTopItem["RecentContactList"];Rn.handleConversationPinned(e,!1)}})}_onC2CMessageReadSync(e){var{C2cNotifyMsgArray:e=[]}=e;Dn.handleC2CMessageReadSync(e)}_onC2CMessageRemindTypeSync(e){var{C2cNotifyMsgArray:e=[]}=e;Pn.handleC2CMessageRemindTypeSync(e)}_onGroupMessageReadSync(e){var{GroupTips:e=[]}=e;Dn.handleGroupMessageReadSync(e)}_dispose(){var{notificationCenter:e,InnerEvent:{MESSAGE_PUSH:t,DESTROY:s}}=this._core,{CONV_MODIFIED:r,C2C_MESSAGE_READ_SYNC:i,GROUP_MESSAGE_READ_SYNC:n,C2C_REMIND_TYPE_SYNC:o}=e["InnerEventSubType"];e.unSubscribeInnerEvent(t,r,this._onConversationModified,this),e.unSubscribeInnerEvent(t,i,this._onC2CMessageReadSync,this),e.unSubscribeInnerEvent(t,o,this._onC2CMessageRemindTypeSync,this),e.unSubscribeInnerEvent(t,n,this._onGroupMessageReadSync,this),e.unSubscribeInnerEvent(s,this._dispose,this)}},Un=new class{init(e){e=(this._core=e).helper;e.registerApi({apiName:"setAllReceiveMessageOpt",context:this})}setAllReceiveMessageOpt(o){return I(this,void 0,void 0,function*(){try{var{MSG_REMIND_ACPT_NOT_NOTE:e}=this._core["OuterConstant"],{messageRemindType:t=e,isRepeated:s=!0}=o,{startTime:r=0,endTime:i=0}=this._calcStartAndEndTime(o),n=yield function(n){return I(this,void 0,void 0,function*(){var e=M.core["common"],{startTime:t,endTime:s,isRepeated:r,messageRemindType:i}=n;return e.buildAndSendPacket({servcmd:"im_msg_db_logic.ws_set_do_not_disturb",data:{StartTime:t,EndTime:s,IsRepeated:r,Level:i}})})}({messageRemindType:this._getType(t),startTime:r,endTime:i,isRepeated:s?an.ON:an.OFF});return{code:0,data:{errorCode:n.ErrorCode,errorInfo:n.ErrorInfo}}}catch(e){Cn("setAllReceiveMessageOpt",e)}})}_calcStartAndEndTime(e){var{startHour:e=0,startMinute:t=0,startSecond:s=0,duration:r=0,isRepeated:i=!0}=e,n=new Date,n=new Date(n.getFullYear(),n.getMonth(),n.getDate(),e,t,s),e=Math.round(n.getTime()/1e3);let o=i&&86400<=r?e+86400:e+r;return{startTime:e,endTime:o}}_getType(e){var t=this._core["OuterConstant"];return{[t.MSG_REMIND_ACPT_AND_NOTE]:0,[t.MSG_REMIND_DISCARD]:1,[t.MSG_REMIND_ACPT_NOT_NOTE]:2}[e]}},kn=new class{init(e){var{helper:e,notificationCenter:t,InnerEvent:s}=this._core=e;e.registerApi({apiName:"getAllReceiveMessageOpt",context:this}),t.subscribeInnerEvent(s.MESSAGE_PUSH,t.InnerEventSubType.ALL_RECEIVE_MESSAGE_OPTION,this.onAllReceiveMsgOptionNotify,this)}onAllReceiveMsgOptionNotify(e){var e=this._handleResult(e),{notificationCenter:t,OuterEvent:{ALL_RECEIVE_MESSAGE_OPT_UPDATED:s}}=this._core;t.emitOuterEvent(s,{name:s,data:e})}getAllReceiveMessageOpt(){return I(this,void 0,void 0,function*(){try{var e=yield function(){return I(this,void 0,void 0,function*(){var e=M.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){Cn("getAllReceiveMessageOpt",e)}})}_handleResult(e){var t=this._core["OuterConstant"],{MSG_REMIND_ACPT_AND_NOTE:t,MSG_REMIND_DISCARD:s,MSG_REMIND_ACPT_NOT_NOTE:r}=t,{Level:e,StartTime:i,EndTime:n,IsRepeated:o}=e;return{messageRemindType:{0:t,1:s,2:r}[e]||t,startTime:i,endTime:n,isRepeated:o===an.ON}}},Fn=new class{init(e){e.ssoLog.debug("ReceiveMessageOptions.init"),this._core=e,bn.init(e),Gn.init(e),yn.init(e),Tn.init(e),Un.init(e),kn.init(e)}};let qn=e=>!mn(e)&&!vn(e)&&!fn(e),xn={getConversationProfile:[{key:"conversationID",required:!0,rules:["string"],allowEmpty:!1,customValidator:e=>!qn(e)||"conversationID is invalid."}],setMessageRead:{conversationID:{required:!0,rules:["string"],allowEmpty:!1,customValidator:e=>!qn(e)||"conversationID is invalid."}},pinConversation:{conversationID:{required:!0,rules:["string"],allowEmpty:!1,customValidator:e=>!qn(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}}=M["core"];if(!r(e)&&!s(e))return"options is String or Object.";if(r(e)&&qn(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(qn(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=>!(!mn(e)&&!vn(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}}},Vn={getConversationList:!0,getConversationProfile:!0,getTotalUnreadCount:!0,setMessageRead:!0,pinConversation:!0,deleteConversation:!0,setConversationDraft:!0,setMessageRemindType:!0,getAllReceiveMessageOpt:!0,setAllReceiveMessageOpt:!0},Bn=new class{constructor(){this.name="Conversation"}install(e){M.init(e),wn.init(e),Fn.init(e),y.init(e),e.helper.registerValidateConfig({auth:Vn,params:xn})}},jn=new class{init(e){this.core=e}},Kn="AVChatRoom",Wn="GRP_COUNTER",Hn=["Type","Name","Introduction","Notification","FaceUrl","Owner_Account","CreateTime","InfoSeq","LastInfoTime","LastMsgTime","MemberNum","MaxMemberNum","ApplyJoinOption","NextMsgSeq","ShutUpAllMember","InviteJoinOption","LastRecallTime"],Yn=["Type","Name","Introduction","Notification","FaceUrl","CreateTime","Owner_Account","LastInfoTime","LastMsgTime","NextMsgSeq","MemberNum","MaxMemberNum","ApplyJoinOption","InviteJoinOption"],$n=["Role","JoinTime","MsgFlag","MsgSeq"],zn=["Role","JoinTime","MsgSeq","MsgFlag","NameCard"],Jn="notStart",Qn="resolved",Xn="rejected",Zn=["Owner","Admin","Member"],eo=["Role","JoinTime","NameCard","ShutUpUntil","OnlineStatus"],to={from:!0,groupID:!0,groupName:!0,to:!0},so={from:!0,groupID:!0,groupName:!0,to:!0,type:!0},ro=e=>e===jn.core.OuterConstant.GRP_PUBLIC,io=e=>e===jn.core.OuterConstant.GRP_AVCHATROOM,no=(r,e)=>{var t=jn.core.utils["isArray"];if(!t(r)||!t(e))return!1;let i=!1;return e.forEach(({key:t,value:e})=>{var s=r.find(e=>e.key===t);s?s.value!==e&&(s.value=e,i=!0):(r.push({key:t,value:e}),i=!0)}),i},oo=s=>{var r=[];if(s)for(let e=0,t=s.length;e<t;e++){var{Key:i,Value:n}=s[e];r.push({key:i,value:n})}return r},ao=s=>{var r=[];for(let e=0,t=s.length;e<t;e++){var{key:i,value:n}=s[e];r.push({Key:i,Value:n})}return r};function uo(e,t){var s=jn.core["helper"];if(!s.checkBusinessCapabilityBits(t))throw new s.ChatError({functionName:e,code:3122,replacement1:e})}function lo(e,t){var s=jn.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 co=["groupID","name","avatar","type","introduction","notification","ownerID","selfInfo","createTime","infoSequence","lastInfoTime","lastMessage","nextMessageSeq","memberCount","maxMemberCount","memberList","joinOption","groupCustomField","muteAllMembers","isSupportTopic","inviteOption","_lastRevokedTime","_groupAtInfoList"];class po{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}=jn.core["utils"];for(t in e)co.indexOf(t)<0||("selfInfo"!==t?"isSupportTopic"!==t?"muteAllMembers"===t&&s(e[t])?this.muteAllMembers="On"===e[t]:this[t]=e[t]:this.isSupportTopic=1===e[t]:this.updateSelfInfo(e[t]))}updateGroup(e){let{utils:{isArray:t,isUndefined:s,isNumber:r,isString:i},common:{deepMerge:n}}=jn.core;e.appid=void 0,e.grossTopicNextMsgSeq=void 0,e.selfInfo&&(e.selfInfo.grossTopicReadSeq=void 0);e=JSON.parse(JSON.stringify(e));e.lastMsgTime&&(this.lastMessage.lastTime=e.lastMsgTime),i(e.muteAllMembers)&&(e.muteAllMembers="On"===e.muteAllMembers),e.groupCustomField&&no(this.groupCustomField,e.groupCustomField),s(e.isSupportTopic)||(this.isSupportTopic=r(e.isSupportTopic)?1===e.isSupportTopic:e.isSupportTopic),n(this,e,["members","errorCode","lastMsgTime","groupCustomField","isSupportTopic"]),t(e.members)&&0<e.members.length&&e.members.forEach(e=>{e.userID===this.selfInfo.userID&&n(this.selfInfo,e,["sequence"])})}updateSelfInfo(e){var{nameCard:e,joinTime:t,role:s,messageRemindType:r,readedSequence:i,excludedUnreadSequenceList:n}=e,o=jn.core["common"]["deepMerge"];o(this.selfInfo,{nameCard:e,joinTime:t,role:s,messageRemindType:r,readedSequence:i,excludedUnreadSequenceList:n},[],["",null,void 0,0,NaN])}setSelfNameCard(e){this.selfInfo.nameCard=e}}var T=new class{constructor(){this._name="GroupDataHandler"}init(e){var e=(this._core=e)["appStore"]["groupStore"];this._groupMap=e.getGroupMap()}hasLocalGroup(e){return this._groupMap.has(e)}getLocalGroup(e){return this._groupMap.get(e)}updateLocalGroup(e){var{getCurrentUserID:t}=this._core["common"];let s;e.forEach(e=>{var t;s=e.groupID,this.hasLocalGroup(s)?null!=(t=this.getLocalGroup(s))&&t.updateGroup(e):this._groupMap.set(s,new po(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 ho(o,a){return I(this,void 0,void 0,function*(){var{type:e,limit:t,offset:s,supportTopic:r=0,memberAccount:i,responseFilter:n}=o;return a.common.buildAndSendPacket({servcmd:"group_open_http_svc.get_joined_group_list",data:{Type:e,Limit:t,Offset:s,Member_Account:i,ResponseFilter:n,SupportTopic:r,NeedAppDefineData:1}})})}function A(e,t){return{code:0,data:e||{},successLog:t}}var go=new class{constructor(){this._name="GetGroupList",this._pagingStatus=Jn,this.PAGING_GRP_COUNT_LIMIT=200}init(e){var{helper:e,constants:{WORKFLOW_NAME:t,WORKFLOW_STEP:s}}=this._core=e;e.registerApi({apiName:"getGroupList",context:this}),e.registerWorkflowStep(t.SYNC_SERVER_INFO_AFTER_LOGIN,s.GROUP_LIST_SYNC,this._syncGroupList,this)}getGroupList(){return I(this,arguments,void 0,function*(e=!1){if(e){let e=[];return yield this._pagingGetJoinedCommunityList({limit:this.PAGING_GRP_COUNT_LIMIT,offset:0,groupList:e}),T.updateLocalGroup(e),T.getLocalGroupList()}return this._core.ssoLog.debug("getGroupList",this._name+".getGroupList pagingStatus:"+this._pagingStatus),this._pagingStatus===Xn||this._pagingStatus===Jn?this._syncGroupList().then(()=>{var e=T.getLocalGroupList();return A({groupList:e,isSyncCompleted:this._isSyncCompleted()})}).catch(e=>{throw e}):(e=T.getLocalGroupList(),A({groupList:e,isSyncCompleted:this._isSyncCompleted()},{message:"return group count:"+e.length}))})}_syncGroupList(){return I(this,void 0,void 0,function*(){this._pagingStatus===Jn&&T.clearLocalGroup();var e=this.PAGING_GRP_COUNT_LIMIT,t=[];try{yield this._pagingGetGroupList({limit:e,offset:0,groupList:t}),this._pagingStatus=Qn,this._groupListTreeShaking(t),T.updateLocalGroup(t);var s=T.getLocalGroupList();return this._core.ssoLog.debug("_syncGroupList",this._name+"._syncGroupList ok, count:"+s.length),T.emitGroupListUpdate(),s}catch(e){throw this._pagingStatus=Xn,e}})}_pagingGetGroupList(e){return I(this,void 0,void 0,function*(){var i=this._core["ssoLog"],{isCommunityRelay:n=!1,groupList:o}=e;let a,{limit:u,offset:l}=e;var c=[...Hn];n&&(a=this._core.OuterConstant.GRP_COMMUNITY,c.push("AtInfoList"));try{let e=yield ho({type:a,limit:u,offset:l,memberAccount:this._core.store.get("login").userId,responseFilter:{GroupBaseInfoFilter:c,SelfInfoFilter:[...$n]}},this._core),{GroupIdList:t=[],TotalCount:s=0}=e||{},r=this._convertGroupKey(t);o.push(...r);var d=l+u,p=!(d<s),h=`offset:${l} limit:${u} total:${s} isCompleted:${p} current:${o.length} isCommunityRelay:`+n;return i.debug("_pagingGetGroupList",this._name+"._pagingGetGroupList ok. "+h),n?p?o:(l=d,this._pagingGetGroupList({isCommunityRelay:!0,limit:u,offset:l,groupList:o})):p?(i.debug("_pagingGetGroupList",this._name+"._pagingGetGroupList start to get community list"),l=0,this._pagingGetGroupList({isCommunityRelay:!0,limit:u,offset:l,groupList:o})):(l=d,this._pagingGetGroupList({limit:u,offset:l,groupList:o}))}catch(e){if(10018===e.ErrorCode)return i.warn("_pagingGetGroupList",this._name+"._pagingGetGroupList response size exceeds the limit, request count:"+u),this._pagingGetGroupList({isCommunityRelay:n,limit:50,offset:l,groupList:o});if(n)return 11e3===e.code&&i.debug("_pagingGetGroupList",this._name+"._pagingGetGroupList ok. community unavailable"),o;throw e}})}_pagingGetJoinedCommunityList(e){return I(this,void 0,void 0,function*(){var{common:{getCurrentUserID:i},OuterConstant:n,ssoLog:o}=this._core,a=e["groupList"];let{limit:u,offset:l}=e;try{let e=yield ho({limit:u,offset:l,type:n.GRP_COMMUNITY,memberAccount:i(),supportTopic:1,responseFilter:{GroupBaseInfoFilter:[...Hn],SelfInfoFilter:[...$n]}},this._core),{GroupIdList:t=[],TotalCount:s=0}=e||{},r=this._convertGroupKey(t);a.push(...r);var c=l+u,d=!(c<s),p=`offset:${l} limit:${u} total:${s} isCompleted:${d} current:`+a.length;return o.debug("_pagingGetJoinedCommunityList",this._name+"._pagingGetJoinedCommunityList ok. "+p),d?a:(l=c,this._pagingGetJoinedCommunityList({limit:u,offset:l,groupList:a}))}catch(e){if(10018===e.code)return o.warn("_pagingGetJoinedCommunityList",this._name+"._pagingGetJoinedCommunityList response size exceeds the limit, request count:"+u),this._pagingGetJoinedCommunityList({limit:50,offset:l,groupList:a});throw e}})}_groupListTreeShaking(s){var r=new Map([...T.getLocalGroupList()]);for(let e=0,t=s.length;e<t;e++)r.delete(s[e].groupID);var i=[...r.keys()];for(let e=0,t=i.length;e<t;e++)T.deleteLocalGroup(i[e])}_isSyncCompleted(){return this._pagingStatus===Qn}_convertGroupKey(s){var r=[];for(let e=0,t=s.length;e<t;e++){var{AppDefinedData:i,ApplyJoinOption:n,CreateTime:o,FaceUrl:a,GroupId:u,Introduction:l,InviteJoinOption:c,LastInfoTime:d,LastMsgTime:p,MemberNum:h,MaxMemberNum:g,MuteAllMember:_,Name:m,NextMsgSeq:v,Notification:f,Owner_Account:I,Type:E,LastRecallTime:C,SelfInfo:S,AtInfoList:M=[],SupportTopic:y}=s[e],i=oo(i),S=this._convertSelfInfo(S),M=this._convertAtInfoList(u,M);r.push({groupCustomField:i,joinOption:n,createTime:o,avatar:a,groupID:u,introduction:l,inviteOption:c,lastInfoTime:d,lastMsgTime:p,memberCount:h,maxMemberCount:g,muteAllMembers:_,name:m,nextMessageSeq:v,notification:f,ownerID:I,type:E,selfInfo:S,_lastRevokedTime:C,_groupAtInfoList:M,isSupportTopic:y})}return r}_convertSelfInfo(e){var{JoinTime:e,MsgFlag:t,MsgSeq:s,NoUnreadSeqList:r,Role:i}=e;return{joinTime:e,messageRemindType:t,readedSequence:s,excludedUnreadSequenceList:r,role:i}}_convertAtInfoList(r,e){if(0===e.length)return[];let i=[];return e.forEach(e=>{var{AtFlagList:e,AtMsgSeq:t,From_Account:s}=e;i.push({groupID:r,groupAtType:e,sequence:t,from:s})}),i}},_o=new class{constructor(){this._name="CreateGroup"}init(e){e=(this._core=e).helper;e.registerApi({apiName:"createGroup",context:this})}createGroup(u){return I(this,void 0,void 0,function*(){var o;this._preCheckParams(u);let e=this._core["helper"]["ChatError"];try{let{utils:{isEmpty:e},common:{getCurrentUserID:t}}=this._core,s=yield function(h,g){return I(this,void 0,void 0,function*(){var{name:e,type:t,groupID:s,introduction:r,notification:i,avatar:n,maxMemberNum:o,joinOption:a,inviteOption:u,memberList:l,groupCustomField:c,isSupportTopic:d}=h;let p;e={Name:e,Type:t,GroupId:s,Introduction:r,Notification:i,FaceUrl:n,MaxMemberCount:o,ApplyJoinOption:a,InviteJoinOption:u,MemberList:p=l?l.map(e=>{var{userID:e,memberCustomField:t}=e;return{Member_Account:e,AppMemberDefinedData:t?ao(t):void 0}}):p,AppDefinedData:c,SupportTopic:d,webPushFlag:1};return g.common.buildAndSendPacket({servcmd:"group_open_http_svc.create_group",data:e})})}(Object.assign(Object.assign({},u),{ownerID:t()}),this._core),{GroupId:r,OverJoinedGroupLimit_Account:i=[]}=s||{},n=`${this._name}.createGroup ok, type:${u.type} groupID:${r} overLimitUserIDList:`+i;e(u.memberList)||e(i)||(u.memberList=null==(o=u.memberList)?void 0:o.filter(e=>i.includes(e.userID))),T.updateLocalGroup([Object.assign(Object.assign({},u),{groupID:r})]);var a=T.getLocalGroup(r);return this._notNeedSendCustomMessage(u)||(this._sendCustomMessage(r,u.type),T.emitGroupListUpdate()),A({group:a},{message:n})}catch(o){var{errorCode:a,errorInfo:t}=o;throw new e({functionName:"createGroup",code:a,message:t,moreMessage:" groupID:"+u.groupID})}})}_preCheckParams(e){var{type:t,groupID:s}=e,{utils:{isEmpty:r,isUndefined:i},common:{isCommunity:n}}=this._core,r=!r(s);if(!(()=>{var{GRP_PUBLIC:e,GRP_WORK:t,GRP_MEETING:s,GRP_AVCHATROOM:r,GRP_COMMUNITY:i}=jn.core.OuterConstant;return[e,t,s,r,i]})().includes(t))throw new this._core.helper.ChatError({code:2600});if(!n({type:t})){if(r&&n({groupID:s}))throw new this._core.helper.ChatError({code:2602});i(e.isSupportTopic)||(e.isSupportTopic=void 0)}if(this._canIUseMemberList(t)||i(e.memberList)||(e.memberList=void 0),this._canIUseJoinOption(t)||i(e.joinOption)||(e.joinOption=void 0),n({type:t})){if(r&&!n({groupID:s}))throw new this._core.helper.ChatError({code:2602});e.isSupportTopic=this._canIUseTopic(e)?1:0}}_canIUseMemberList(e){return!io(e)}_canIUseJoinOption(e){return ro(e)||this._core.common.isCommunity({type:e})}_canIUseTopic(e){e=e.isSupportTopic;return!0===e}_notNeedSendCustomMessage(e){var{type:e,isSupportTopic:t}=e,{GRP_AVCHATROOM:s,GRP_COMMUNITY:r}=this._core["OuterConstant"];return e===s||e===r&&1===t}_sendCustomMessage(e,t){var s=this._core["OuterConstant"];let r="Create Group",i=0;t===s.GRP_COMMUNITY&&(r="Create Community",i=1);var t={to:e,conversationType:"GROUP",payload:{data:JSON.stringify({businessID:"group_create",content:r,cmd:i,opUser:this._core.store.get("login").userId,version:4})}},e=null==(s=null==(e=null==(s=this._core)?void 0:s.message)?void 0:e.messageFactory)?void 0:s.createCustomMessage(t);null!=(s=null==(t=null==(s=this._core)?void 0:s.message)?void 0:t.messageSender)&&s.sendMessage(e,{})}},O=new class{constructor(){this._name="AttributesDataHandler",this._groupAttributesCache=new Map,this._groupAttributesCacheValuesCopy={}}init(e){var{helper:e,constants:t}=this._core=e;e.registerWorkflowStep(t.WORKFLOW_NAME.SYNC_SERVER_INFO_AFTER_RE_ONLINE,t.WORKFLOW_STEP.GROUP_ATTRIBUTE_CACHE_CLEAR,this.clearLocalMainSequence,this)}clearLocalMainSequence(){this._groupAttributesCache.forEach(e=>{e.localMainSequence=0})}isGroupAttributesUpdated(e){var e=e["elements"]["newGroupProfile"],{isEmpty:t,isUndefined:s}=this._core["utils"];return!s(e)&&!t(e.groupAttributeOption)}handleGroupAttributesUpdated(e){var{groupID:e,groupAttributeOption:t}=e,{serverMainSequence:t,groupAttributeList:s=[],operation:r}=t,i=(this._core.ssoLog.debug("handleGroupAttributesUpdated",this._name+`.handleGroupAttributesUpdated groupID:${e} operation:`+r),this._core)["utils"]["isUndefined"];i(r)||(this.refreshGroupAttributesCache({groupID:e,serverMainSequence:t,groupAttributeList:s,operation:r}),this.emitGroupAttributesUpdated(e))}initGroupAttributesCache(e){var{groupID:e,avChatRoomKey:t}=e;this._groupAttributesCache.set(e,{lastUpdateTime:0,localMainSequence:0,serverMainSequence:0,avChatRoomKey:t,values:new Map}),this._core.ssoLog.debug("initGroupAttributesCache",this._name+`.initGroupAttributesCache. groupID:${e} avChatRoomKey:`+t)}hasGroupAttributesCache(e){return this._groupAttributesCache.has(e)}getGroupAttributesCache(e){return this.hasGroupAttributesCache(e)||this.initGroupAttributesCache({groupID:e}),this._groupAttributesCache.get(e)}deleteGroupAttributesCache(e){this.hasGroupAttributesCache(e)&&this._groupAttributesCache.delete(e)}refreshGroupAttributesCache(e){var{groupID:s,serverMainSequence:r,groupAttributeList:i,operation:n}=e;if(this.hasGroupAttributesCache(s)){let e=this.getGroupAttributesCache(s),t=e["localMainSequence"];5!==n&&r-t!=1||(e.serverMainSequence=r,e.localMainSequence=r,e.lastUpdateTime=Date.now(),this._updateGroupAttributesCacheValues({groupAttributes:e,groupAttributeList:i,operation:n})),1<r-t&&(e.serverMainSequence=r),this._groupAttributesCache.set(s,e),this._core.ssoLog.debug("refreshGroupAttributesCache",this._name+`.refreshGroupAttributesCache. operation:${n} localMainSequence:${t} serverMainSequence:`+r)}}_updateGroupAttributesCacheValues(e){let{groupAttributes:r,groupAttributeList:t=[],operation:s}=e;3!==s?4!==s?(1===s&&r.values.clear(),t.forEach(e=>{var{key:e,value:t,sequence:s}=e;r.values.set(e,{value:t,sequence:s})})):t.forEach(e=>{r.values.delete(e.key)}):r.values.clear()}getGroupAttributesCacheValues(e){let s,{groupID:r,keyList:i=[]}=e,n={};if(this.hasGroupAttributesCache(r)){let t=this.getGroupAttributesCache(r)["values"];if(0===i.length)for(let e of t.keys())n[e]=(null==(s=t.get(e))?void 0:s.value)||"";else i.forEach(e=>{t.has(e)&&(n[e]=(null==(e=t.get(e))?void 0:e.value)||"")})}return n}saveGroupAttributesCacheValuesCopy(e){this._groupAttributesCacheValuesCopy=this.getGroupAttributesCacheValues({groupID:e})}emitGroupAttributesUpdated(e){var t,s=this.getGroupAttributesCacheValues({groupID:e}),{updatedKeyList:r,deletedKeyList:i}=this._computeValuesChangedData(s);this._core.ssoLog.debug("emitGroupAttributesUpdated",`${this._name}.emitGroupAttributesUpdated update count:${r.length}, delete count:`+i.length),0===r.length&&0===i.length||this._emitEvent({name:null==(t=this._core)?void 0:t.OuterEvent.GROUP_ATTRIBUTES_UPDATED,data:{groupID:e,groupAttributes:s,updatedKeyList:r,deletedKeyList:i}})}_computeValuesChangedData(t){let{isUndefined:s}=this._core["utils"],r=[],i=[];return Object.keys(t).forEach(e=>{t[e]!==this._groupAttributesCacheValuesCopy[e]&&r.push(e)}),Object.keys(this._groupAttributesCacheValuesCopy).forEach(e=>{s(t[e])&&i.push(e)}),this._groupAttributesCacheValuesCopy={},{updatedKeyList:r,deletedKeyList:i}}_emitEvent(e){var t;null!=(t=this._core)&&t.notificationCenter.emitOuterEvent(e.name,e)}convertKeyValueMapToList(t){let s=[];return Object.keys(t).forEach(e=>{s.push({key:e,value:t[e]})}),s}reset(){this._groupAttributesCache.clear(),this._groupAttributesCacheValuesCopy={}}},mo=new class{constructor(){this._name="DismissGroup"}init(e,t){e=(this._core=e).helper;e.registerApi({apiName:"dismissGroup",context:this,matcher:()=>!t.getInstalledSubPlugins().includes(Kn)})}dismissGroup(i){return I(this,void 0,void 0,function*(){let{ChatError:t}=this._core["helper"];try{yield function(e,t){return I(this,void 0,void 0,function*(){return t.common.buildAndSendPacket({servcmd:"group_open_http_svc.destroy_group",data:{GroupId:e}})})}(i,this._core);let e=T.getLocalGroup(i)["type"];return T.deleteLocalGroup(i),T.emitGroupListUpdate(),O.deleteGroupAttributesCache(i),A({groupID:i,type:e},{message:i})}catch(e){var{errorCode:s,errorInfo:r}=e;throw new t({functionName:"dismissGroup",code:s,message:r})}})}},vo=new class{constructor(){this._name="GetGroupProfile"}init(e){e=(this._core=e).helper;e.registerApi({apiName:"getGroupProfile",context:this})}getGroupProfile(t){return I(this,void 0,void 0,function*(){let{groupID:i,groupCustomFieldFilter:e}=t,n={groupIDList:[i],responseFilter:{GroupBaseInfoFilter:[...Hn],AppDefinedDataFilter_Group:e,MemberInfoFilter:[...zn]}},{ChatError:r}=this._core["helper"];try{let e=yield this.getGroupProfileAdvance(n),{successGroupList:t,failureGroupList:s}=e;if(0<s.length)throw s[0];let r;return(r=!T.hasLocalGroup(i)&&io(t[0].type)?new po(t[0]):(T.updateLocalGroup(t),T.getLocalGroup(i))).isSupportTopic||T.updateConversationGroupProfile(i),A({group:r},{message:"groupID:"+i})}catch(e){let{code:t,message:s}=e;throw new r({functionName:"getGroupProfile",code:t,message:s})}})}getGroupProfileAdvance(a){return I(this,void 0,void 0,function*(){let e=a["groupIDList"],{isCommunity:t}=this._core["common"],s=e.filter(e=>!t({groupID:e})),r=e.filter(e=>t({groupID:e})),i=(50<s.length&&(s.length=50),50<r.length&&(r.length=50),yield Promise.all([this._getGroupProfileAdvance(Object.assign(Object.assign({},a),{groupIDList:s})),this._getGroupProfileAdvance(Object.assign(Object.assign({},a),{groupIDList:r,isCommunityProfile:!0}))])),n=[],o=[];return i.forEach(e=>{n.push(...e.successGroupList),o.push(...e.failureGroupList)}),{successGroupList:n,failureGroupList:o}})}_getGroupProfileAdvance(e){return I(this,void 0,void 0,function*(){let{ssoLog:n,utils:{isUndefined:o}}=this._core,{isCommunityProfile:t=!1}=e,a=f(e,["isCommunityProfile"]);if(0===a.groupIDList.length)return{successGroupList:[],failureGroupList:[]};try{let e=yield function(s,r){return I(this,void 0,void 0,function*(){var{groupIDList:e,responseFilter:t}=s;return r.common.buildAndSendPacket({servcmd:"group_open_http_svc.get_group_self_member_info",data:{GroupIdList:e,ResponseFilter:t}})})}(a,this._core),{GroupInfo:t=[]}=e||{},s=this._convertGroupProfileKey(t),r=s.filter(e=>o(e.errorCode)||0===e.errorCode),i=s.filter(e=>e.errorCode&&0!==e.errorCode).map(e=>({code:e.errorCode,message:e.errorInfo,data:{groupID:e.groupID}}));return n.debug("_getGroupProfileAdvance",this._name+"._getGroupProfileAdvance ok, groupID:"+a.groupIDList.join(",")),{successGroupList:r,failureGroupList:i}}catch(e){if(t)return{successGroupList:[],failureGroupList:[]};throw e}})}_convertGroupProfileKey(s){var r=[];for(let e=0,t=s.length;e<t;e++){var{AppDefinedData:i,ApplyJoinOption:n,CreateTime:o,FaceUrl:a,GroupId:u,InfoSeq:l,Introduction:c,InviteJoinOption:d,LastInfoTime:p,LastMsgTime:h,MaxMemberNum:g,MemberNum:_,MuteAllMember:m,Name:v,NextMsgSeq:f,Notification:I,Owner_Account:E,ShutUpAllMember:C,ShutUpUntil:S,Type:M,MemberList:y,ErrorCode:T,ErrorInfo:A}=s[e],i=oo(i),y=this._convertMembers(y);r.push({groupCustomField:i,joinOption:n,createTime:o,avatar:a,groupID:u,infoSequence:l,introduction:c,inviteOption:d,lastInfoTime:p,lastMsgTime:h,maxMemberCount:g,memberCount:_,muteAllMembers:m,name:v,nextMessageSeq:f,notification:I,ownerID:E,shutUpAllMember:C,muteUntil:S,type:M,members:y,errorCode:T,errorInfo:A})}return r}_convertMembers(s){if(!s)return[];var r=[];for(let e=0,t=s.length;e<t;e++){var{AppMemberDefinedData:i,JoinTime:n,Member_Account:o,MsgFlag:a,MsgSeq:u,NameCard:l,Role:c}=s[e],i=oo(i);r.push({memberCustomField:i,joinTime:n,userID:o,messageRemindType:a,sequence:u,nameCard:l,role:c})}return r}},fo=new class{constructor(){this._groupCountersMap=new Map}init(e){this._core=e}getLocalGroupCounters(e){return this._hasLocalGroupCounters(e)||this.initGroupCountersCache({groupID:e}),this._groupCountersMap.get(e)}updateLocalGroupCounters(e){var{groupID:r,counterList:i=[],groupCounterSeq:n}=e;if(this._hasLocalGroupCounters(r)){let{counters:s,avChatRoomKey:e,groupCounterSeq:t}=this.getLocalGroupCounters(r);0<n&&n<t||(i.forEach(e=>{var{Key:e,Value:t=0}=e;s.set(e,t)}),this._groupCountersMap.set(r,{lastUpdateTime:Date.now(),groupCounterSeq:n,counters:s,avChatRoomKey:e}))}}initGroupCountersCache(e){var{groupID:e,avChatRoomKey:t}=e;this._groupCountersMap.set(e,{lastUpdateTime:0,groupCounterSeq:0,counters:new Map,avChatRoomKey:t})}getLocalCounters(e,s){let r={};if(this._hasLocalGroupCounters(e)){let t=this.getLocalGroupCounters(e)["counters"];if(0<s.length)s.forEach(e=>{t.has(e)&&(r[e]=t.get(e))});else for(let e of t.keys())r[e]=t.get(e)}return r}deleteLocalGroupCounters(e){var{groupID:s,counterList:r=[],groupCounterSeq:i}=e;if(this._hasLocalGroupCounters(s)){let{counters:t,avChatRoomKey:e}=this.getLocalGroupCounters(s);r.forEach(e=>{t.delete(e.key)}),this._groupCountersMap.set(s,{lastUpdateTime:Date.now(),groupCounterSeq:i,counters:t,avChatRoomKey:e})}}setGroupCounters(t,i){if(this._hasLocalGroupCounters(t)){let e=this.getLocalGroupCounters(t),s=e["counters"],r=!1;Object.entries(i).forEach(([e,t])=>{s.has(e)&&s.get(e)!==t&&(s.set(e,t),r=!0)}),r&&this._groupCountersMap.set(t,Object.assign(Object.assign({},e),{lastUpdateTime:Date.now(),counters:s}))}}_hasLocalGroupCounters(e){return this._groupCountersMap.has(e)}reset(){this._groupCountersMap.clear()}},Io=new class{constructor(){this._name="JoinGroup"}init(e,t){e=(this._core=e).helper;e.registerApi({apiName:"joinGroup",context:this,matcher:()=>!t.getInstalledSubPlugins().includes(Kn)})}joinGroup(s){return I(this,void 0,void 0,function*(){let r=s["groupID"],{helper:{ChatError:i},OuterConstant:e,ssoLog:t}=this._core;try{if(T.hasLocalGroup(r))try{return yield vo.getGroupProfile({groupID:r}),A({status:e.JOIN_STATUS_ALREADY_IN_GROUP,group:T.getLocalGroup(r)},{message:`groupID:${r} joinedStatus:`+e.JOIN_STATUS_ALREADY_IN_GROUP})}catch(i){t.warn("joinGroup",this._name+`.joinGroup ${r} was unjoined, start to join!`),T.deleteLocalGroup(r)}return yield this._applyJoinGroup(s)}catch(e){let{errorCode:t,errorInfo:s}=e;throw new i({functionName:"joinGroup",code:t,message:s,moreMessage:"groupID:"+r})}})}_applyJoinGroup(p){return I(this,void 0,void 0,function*(){var{OuterConstant:e,helper:t,ssoLog:s}=this._core,r=p["groupID"],i=Object.assign({},p),t=t.checkBusinessCapabilityBits("AV_HISTORY_MSG"),i=(t&&(i.historyMessageFlag=1),yield function(r,i){return I(this,void 0,void 0,function*(){var{groupID:e,applyMessage:t,historyMessageFlag:s}=r;return i.common.buildAndSendPacket({servcmd:"group_open_http_svc.apply_join_group",data:{GroupId:e,ApplyMsg:t,HugeGroupHistoryMsgFlag:s}})})}(i,this._core)),{Type:i,JoinedStatus:n,LongPollingKey:o,StartSeq:a,HugeGroupFlag:u,AVChatRoomKey:l,RspMsgList:c=[]}=i||{},t=`groupID:${r} joinedStatus:${n} longPollingKey:${o} startSeq:${a} avChatRoomFlag:${u} canGetAVChatRoomHistoryMsg:${t}, historyMessageCount:`+c.length;s.debug("_applyJoinGroup",this._name+"._applyJoinGroup ok, "+t);let d=new po({groupID:r,type:i});if(n===e.JOIN_STATUS_WAIT_APPROVAL)return A({status:e.JOIN_STATUS_WAIT_APPROVAL,group:d});if(n!==e.JOIN_STATUS_SUCCESS)throw new this._core.helper.ChatError({code:2660});try{d=(yield vo.getGroupProfile({groupID:r})).data.group}catch(e){s.warn("_applyJoinGroup",this._name+`._applyJoinGroup getGroupProfile failed, groupID: ${r}, errorCode:`+(null==e?void 0:e.code))}return this._handleJoinResult({group:d,avChatRoomFlag:u,longPollingKey:o,startSequence:a,avChatRoomKey:l,historyMessageList:c})})}_handleJoinResult(e){var{group:t,avChatRoomFlag:s,avChatRoomKey:r}=e;return 1===s?(O.initGroupAttributesCache({groupID:t.groupID,avChatRoomKey:r}),fo.initGroupCountersCache({groupID:t.groupID,avChatRoomKey:r}),A(e)):(T.updateLocalGroup([t]),T.emitGroupListUpdate(),A({status:this._core.OuterConstant.JOIN_STATUS_SUCCESS,group:t},{message:"groupID:"+t.groupID}))}},Eo=new class{constructor(){this._name="QuitGroup"}init(e,t){e=(this._core=e).helper;e.registerApi({apiName:"quitGroup",context:this,matcher:()=>!t.getInstalledSubPlugins().includes(Kn)})}quitGroup(i){return I(this,void 0,void 0,function*(){if(!T.hasLocalGroup(i))throw new this._core.helper.ChatError({code:2623});let{ChatError:t}=this._core["helper"];try{yield function(e,t){return I(this,void 0,void 0,function*(){return t.common.buildAndSendPacket({servcmd:"group_open_http_svc.quit_group",data:{GroupId:e}})})}(i,this._core);let e=T.getLocalGroup(i)["type"];return T.deleteLocalGroup(i),T.emitGroupListUpdate(),O.deleteGroupAttributesCache(i),A({groupID:i,type:e},{message:"groupID:"+i})}catch(e){var{errorCode:s,errorInfo:r}=e;throw new t({functionName:"quitGroup",code:s,message:r,moreMessage:"groupID:"+i})}})}},Co=new class{constructor(){this._name="SearchGroup"}init(e){e=(this._core=e).helper;e.registerApi({apiName:"searchGroupByID",context:this})}searchGroupByID(v){return I(this,void 0,void 0,function*(){try{var t=yield function(t,s){return I(this,void 0,void 0,function*(){var e={GroupIdList:[t],GroupBasePublicInfoFilter:[...Yn]};return s.common.buildAndSendPacket({servcmd:"group_open_http_svc.get_group_public_info",data:e})})}(v,this._core),{GroupInfo:s=[]}=t||{},{AppDefinedData:e=[],ApplyJoinOption:r,CreateTime:i,FaceUrl:n,Introduction:o,InviteJoinOption:a,MaxMemberNum:u,MemberNum:l,Name:c,Owner_Account:d,Type:p,ErrorCode:h,ErrorInfo:g}=s[0];if(0!==h)throw new this._core.helper.ChatError({code:h,message:g});var _=oo(e),m=new po({groupID:v,name:c,avatar:n,introduction:o,joinOption:r,inviteOption:a,maxMemberCount:u,memberCount:l,type:p,ownerID:d,createTime:i,groupCustomField:_});return A({group:m})}catch(e){var{errorCode:t,errorInfo:s}=e;throw new this._core.helper.ChatError({functionName:"searchGroupByID",code:t,message:s})}})}},So=new class{constructor(){this._name="UpdateGroupProfile"}init(e){e=(this._core=e).helper;e.registerApi({apiName:"updateGroupProfile",context:this})}updateGroupProfile(o){return I(this,void 0,void 0,function*(){let r=o["groupID"],{utils:{isUndefined:t},ssoLog:s,helper:i}=this._core,n=T.getLocalGroup(r);if(n){let e=n["type"];this._canIUseJoinOption(e)||t(o.joinOption)||(s.warn("updateGroupProfile",this._name+`.updateGroupProfile groupID:${r} joinOption is unavailable for Work/Meeting/AVChatRoom`),o.joinOption=void 0)}t(o.muteAllMembers)||(o.muteAllMembers=!0===o.muteAllMembers?"On":"Off");try{return yield function(l,c){return I(this,void 0,void 0,function*(){var{groupID:e,name:t,avatar:s,introduction:r,notification:i,muteAllMembers:n,joinOption:o,inviteOption:a,groupCustomField:u}=l,e={GroupId:e,Name:t,FaceUrl:s,Introduction:r,Notification:i,ShutUpAllMember:n,ApplyJoinOption:o,InviteJoinOption:a,AppDefinedData:u?ao(u):void 0};return c.common.buildAndSendPacket({servcmd:"group_open_http_svc.modify_group_base_info",data:e})})}(o,this._core),n?(n.updateGroup(o),T.emitGroupListUpdate()):n=new po(o),A({group:n},{message:"groupID:"+r})}catch(e){let{errorCode:t,errorInfo:s}=e;throw new i.ChatError({code:t,message:s,moreMessage:"groupID:"+r})}})}_canIUseJoinOption(e){return ro(e)||this._core.common.isCommunity({type:e})}},Mo=new class{constructor(){this._name="ChangeGroupOwner"}init(e){e=(this._core=e).helper;e.registerApi({apiName:"changeGroupOwner",context:this})}changeGroupOwner(o){return I(this,void 0,void 0,function*(){var t="changeGroupOwner",{groupID:e,newOwnerID:s}=o,e=T.getLocalGroup(e),{helper:r,OuterConstant:i,common:{getCurrentUserID:n}}=this._core;if((null==e?void 0:e.type)===i.GRP_AVCHATROOM)throw new r.ChatError({functionName:t,code:2620});if(s===n())throw new r.ChatError({functionName:t,code:2621});try{return yield function(s,r){return I(this,void 0,void 0,function*(){var{groupID:e,newOwnerID:t}=s;return r.common.buildAndSendPacket({servcmd:"group_open_http_svc.change_group_owner",data:{GroupId:e,NewOwner_Account:t}})})}(o,this._core),e.ownerID=s,T.emitGroupListUpdate(),A({group:e})}catch(e){throw new r.ChatError({functionName:t,code:null==e?void 0:e.errorCode,message:null==e?void 0:e.errorInfo})}})}},yo=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(Kn)})}getGroupOnlineMemberCount(n){return I(this,void 0,void 0,function*(){let s="getGroupOnlineMemberCount";if(!T.hasLocalGroup(n))return A({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 A({memberCount:s})}try{let e=yield function(e,t){return I(this,void 0,void 0,function*(){return t.common.buildAndSendPacket({servcmd:"group_open_http_svc.get_online_member_num",data:{GroupId:e}})})}(n,this._core),{OnlineMemberNum:t=0}=e||{};this._onlineMemberCountMap.set(n,{lastReqTime:Date.now(),memberCount:t});var i=`${this._name}.${s} ok. groupID:${n} memberCount:`+t;return A({memberCount:t},{message:i})}catch(e){throw new this._core.helper.ChatError({functionName:s,code:null==e?void 0:e.errorCode,message:null==e?void 0:e.errorInfo})}})}},To=new class{init(e,t){e.ssoLog.debug("GroupAction.init"),go.init(e),_o.init(e),mo.init(e,t),Io.init(e,t),Eo.init(e,t),Co.init(e),vo.init(e),So.init(e),Mo.init(e),yo.init(e,t)}dismissGroup(e){return mo.dismissGroup(e)}joinGroup(e){return Io.joinGroup(e)}quitGroup(e){return Eo.quitGroup(e)}getGroupOnlineMemberCount(e){return yo.getGroupOnlineMemberCount(e)}},Ao=new class{constructor(){this._name="GetGroupApplicationList"}init(e){e=(this._core=e).helper;e.registerApi({apiName:"getGroupApplicationList",context:this})}getGroupApplicationList(){return I(this,void 0,void 0,function*(){var t="getGroupApplicationList";try{var e=yield Promise.all([this._getGroupApplicationList(),this._getGroupApplicationList({type:this._core.OuterConstant.GRP_COMMUNITY})]),s=(this._core.ssoLog.debug("getGroupApplicationList",this._name+`.${t} ok.`),this._handleGroupApplicationResult([...e[0],...e[1]]));return A({applicationList:s})}catch(e){throw new this._core.helper.ChatError({functionName:t,code:null==e?void 0:e.errorCode,message:null==e?void 0:e.errorInfo})}})}_getGroupApplicationList(n){return I(this,void 0,void 0,function*(){var{type:e,startTime:t=0,limit:s=20}=n||{},r=this._core["common"];let i;try{i=yield function(i,n){return I(this,void 0,void 0,function*(){var{type:e,startTime:t,limit:s,handleAccount:r}=i;return n.common.buildAndSendPacket({servcmd:"group_open_http_svc.get_pendency",data:{Type:e,StartTime:t,Limit:s,Handle_Account:r}})})}({type:e,startTime:t,limit:s,handleAccount:r.getCurrentUserID()},this._core)}catch(e){if(11e3!==(null==e?void 0:e.errorCode))throw e;i={}}var{NextStartTime:e=0,PendencyList:t=[]}=i||{};return 0===e?t:(s=yield this._getGroupApplicationList(Object.assign(Object.assign({},n),{startTime:e})),[...t,...s])})}_handleGroupApplicationResult(e){let s=[];return e.forEach(e=>{var e=this._convertApplicationData(e),t=e["handled"],e=f(e,["handled"]);0===t&&s.push(e)}),s}_convertApplicationData(e){var{Handled:e,AddTime:t,ApplyInviteMsg:s,Authentication:r,FromUserNickName:i,From_Account:n,GroupId:o,GroupName:a,PendencyType:u,To_Account:l}=e;return{handled:e,messageKey:t,applicant:n,applicantNick:i,groupID:o,groupName:a,authentication:r,applicationType:u,userID:l,note:s}}},Oo=new class{constructor(){this._name="HandleGroupApplication"}init(e){e=(this._core=e).helper;e.registerApi({apiName:"handleGroupApplication",context:this})}handleGroupApplication(e){return I(this,void 0,void 0,function*(){var t=e["application"],s=this._handleParams(e);try{2===(null==t?void 0:t.applicationType)?yield function(o,a){return I(this,void 0,void 0,function*(){var{groupID:e,handleAction:t,handleMessage:s,applicant:r,authentication:i,invitee:n}=o;return a.common.buildAndSendPacket({servcmd:"group_open_http_svc.handle_invite_join_permission_group",data:{GroupId:e,HandleMsg:t,ApprovalMsg:s,Applicant_Account:r,Authentication:i,Invited_Account:n}})})}(s,this._core):yield function(o,a){return I(this,void 0,void 0,function*(){var{groupID:e,handleAction:t,handleMessage:s,applicant:r,authentication:i,messageKey:n}=o;return a.common.buildAndSendPacket({servcmd:"group_open_http_svc.handle_apply_join_group",data:{GroupId:e,HandleMsg:t,ApprovalMsg:s,Applicant_Account:r,Authentication:i,MsgKey:n}})})}(s,this._core);let e=T.getLocalGroup(s.groupID);return A({group:e})}catch(e){throw new this._core.helper.ChatError({functionName:"handleGroupApplication",code:null==e?void 0:e.errorCode,message:null==e?void 0:e.errorInfo})}})}_handleParams(e){var{handleAction:e,handleMessage:t,message:s,application:r}=e;let i,n,o,a,u;if(s){let e=(s||{})["payload"];i=e.operatorID,n=null==(s=e.groupProfile)?void 0:s.groupID,o=e.authentication,a=e.messageKey}else i=(null==r?void 0:r.applicant)||"",n=(null==r?void 0:r.groupID)||"",o=(null==r?void 0:r.authentication)||"",a=(null==r?void 0:r.messageKey)||0;return 2===(null==r?void 0:r.applicationType)&&(u=r.userID),{handleAction:e,handleMessage:t,applicant:i,invitee:u,groupID:n,authentication:o,messageKey:a}}},Do=new class{init(e){e.ssoLog.debug("GroupApplication.init"),Ao.init(e),Oo.init(e)}};let Ro=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}}=jn["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&&no(this.memberCustomField,e.memberCustomField),s(this,e,["memberCustomField","marks","onlineStatus","muteTime"],t)}};function Lo(a,u){return I(this,void 0,void 0,function*(){var{groupID:e,userID:t,muteTime:s,role:r,nameCard:i,memberCustomField:n}=a;let o;e={GroupId:e,Member_Account:t,ShutUpTime:s,Role:r,NameCard:i,AppMemberDefinedData:o=n?ao(n):o};return u.common.buildAndSendPacket({servcmd:"group_open_http_svc.modify_group_member_info",data:e})})}var No=new class{constructor(){this._name="GetGroupMemberList"}init(e,t){e=(this._core=e).helper;e.registerApi({apiName:"getGroupMemberList",context:this,matcher:()=>!t.getInstalledSubPlugins().includes(Kn)})}getGroupMemberList(r){return I(this,void 0,void 0,function*(){let l="getGroupMemberList",{groupID:c,offset:d=0,count:e=100,role:t="",filter:s=""}=r,p=T.getLocalGroup(c),h=100<e?100:e,g={groupID:c,offset:d,limit:h,memberRoleFilter:Zn.includes(t)?[t]:void 0,memberInfoFilter:eo};try{let e=yield function(n,o){return I(this,void 0,void 0,function*(){var{groupID:e,offset:t,limit:s,memberRoleFilter:r,memberInfoFilter:i}=n;return o.common.buildAndSendPacket({servcmd:"group_open_http_svc.get_group_member_info",data:{GroupId:e,Offset:t,Limit:s,MemberRoleFilter:r,MemberInfoFilter:i}})})}(g,this._core),{MemberList:t,MemberNum:s,Next:r}=e||{},i=`${this._name}.${l} ok, totalMemberCount:${s} next:`+r,{utils:{isArray:n,isEmpty:o},common:{isCommunity:a}}=this._core;if(p&&(p.memberCount=s),!n(t)||0===t.length)return A({memberList:[],offset:0},{message:i});let u=d+h;a({groupID:c})&&(u=o(r)?0:r),t.length<h&&(u=0);var _=this._convertMemberInfo(t),_=yield this._patchAvatarAndNick(_),m=this._generateGroupMember(_);return A({memberList:m,offset:u},{message:i})}catch(e){throw new this._core.helper.ChatError({functionName:l,code:null==e?void 0:e.errorCode,message:null==e?void 0:e.errorInfo})}})}_convertMemberInfo(s){var r=[];for(let e=0,t=s.length;e<t;e++){var{AppMemberDefinedData:i,JoinTime:n,Member_Account:o,OnlineStatus:a,Role:u,ShutUpUntil:l,NameCard:c}=s[e],i=oo(i);r.push({userID:o,joinTime:n,onlineStatus:a,role:u,muteUntil:l,memberCustomField:i,nameCard:c})}return r}_patchAvatarAndNick(n){return I(this,void 0,void 0,function*(){let e,t=n.map(e=>e.userID),s=yield null==(e=this._core.user.userProfile)?void 0:e.getUserProfile({userIDList:t}),r=(null==s?void 0:s.data)||[],i=new Map(r.map(e=>[e.userID,e]));return n.forEach(e=>{var t,s;i.has(e.userID)&&({nick:t="",avatar:s=""}=i.get(e.userID),e.nick=t,e.avatar=s)}),n})}_generateGroupMember(s){var r=[];for(let e=0,t=s.length;e<t;e++){var i=new Ro(s[e]);r.push(i)}return r}},bo=new class{constructor(){this._name="GetGroupMemberProfile"}init(e){e=(this._core=e).helper;e.registerApi({apiName:"getGroupMemberProfile",context:this})}getGroupMemberProfile(c){return I(this,void 0,void 0,function*(){let t="getGroupMemberProfile",{groupID:r,userIDList:i,memberCustomFieldFilter:n}=c,e=T.getLocalGroup(r),{helper:s,utils:{isArray:o},ssoLog:a}=this._core;if(e&&io(e.type))throw new s.ChatError({functionName:t,replacement1:t,code:2687});50<i.length&&(a.warn("getGroupMemberProfile",`${this._name}.${t} userIDList length:${i.length} exceeds limit 50`),i.splice(50));var u=`userIDList length:${i.length} groupID:`+r;try{let e=yield function(i,n){return I(this,void 0,void 0,function*(){var{groupID:e,userIDList:t,memberInfoFilter:s,memberCustomFieldFilter:r}=i;return n.common.buildAndSendPacket({servcmd:"group_open_http_svc.get_specified_group_member_info",data:{GroupId:e,Member_List_Account:t,MemberInfoFilter:s,AppDefinedDataFilter_GroupMember:r}})})}({groupID:r,userIDList:i,memberCustomFieldFilter:n,memberInfoFilter:[...eo]},this._core),t=(e||{})["MemberList"];if(!o(t)||0===t.length)return A({memberList:[]});var l=this._convertMemberInfo(t),l=yield this._getMemberAvatarAndNick(l);let s=this._generateGroupMember(l);return A({memberList:s},{message:u})}catch(e){throw new s.ChatError({functionName:t,code:null==e?void 0:e.errorCode,message:null==e?void 0:e.errorInfo,moreMessage:u})}})}_convertMemberInfo(s){var r=[];for(let e=0,t=s.length;e<t;e++){var{AppMemberDefinedData:i,JoinTime:n,Member_Account:o,OnlineStatus:a,Role:u,ShutUpUntil:l,NameCard:c}=s[e],i=oo(i);r.push({userID:o,joinTime:n,onlineStatus:a,role:u,muteUntil:l,memberCustomField:i,nameCard:c})}return r}_getMemberAvatarAndNick(n){return I(this,void 0,void 0,function*(){let e,t=n.map(e=>e.userID),s=yield null==(e=this._core.user.userProfile)?void 0:e.getUserProfile({userIDList:t}),r=(null==s?void 0:s.data)||[],i=new Map(r.map(e=>[e.userID,e]));return n.forEach(e=>{var t,s;i.has(e.userID)&&({nick:t="",avatar:s=""}=i.get(e.userID),e.nick=t,e.avatar=s)}),n})}_generateGroupMember(s){var r=[];for(let e=0,t=s.length;e<t;e++){var i=new Ro(s[e]);r.push(i)}return r}},Go=new class{constructor(){this._name="AddGroupMember"}init(e){e=(this._core=e).helper;e.registerApi({apiName:"addGroupMember",context:this})}addGroupMember(r){return I(this,void 0,void 0,function*(){let t="addGroupMember",{groupID:o,userIDList:e}=r,a=T.getLocalGroup(o),s=this._core["helper"];if(a&&io(a.type))throw new s.ChatError({functionName:t,code:2661});var u=e.map(e=>({Member_Account:e}));try{let e=yield function(s,r){return I(this,void 0,void 0,function*(){var{groupID:e,userIDList:t}=s;return r.common.buildAndSendPacket({servcmd:"group_open_http_svc.add_group_member",data:{GroupId:e,MemberList:t}})})}({groupID:o,userIDList:u},this._core),{MemberList:t=[]}=e||{},{failureUserIDList:s,successUserIDList:r,existedUserIDList:i,overLimitUserIDList:n}=this._handleResult(t);return A({failureUserIDList:s,successUserIDList:r,existedUserIDList:i,overLimitUserIDList:n,group:a},{message:` groupID:${o} successUserIDList:${r} failureUserIDList:${s} existedUserIDList:${i} overLimitUserIDList:`+n})}catch(e){throw new s.ChatError({functionName:t,code:null==e?void 0:e.errorCode,message:null==e?void 0:e.errorInfo})}})}_handleResult(e){let s=[],r=[],i=[],n=[];return e.forEach(e=>{var{Result:e,Member_Account:t}=e;0===e?s.push(t):1===e?r.push(t):2===e?i.push(t):4===e&&n.push(t)}),{failureUserIDList:s,successUserIDList:r,existedUserIDList:i,overLimitUserIDList:n}}},Po=new class{constructor(){this._name="DeleteGroupMember"}init(e,t){e=(this._core=e).helper;e.registerApi({apiName:"deleteGroupMember",context:this,matcher:()=>!t.getInstalledSubPlugins().includes(Kn)})}deleteGroupMember(a){return I(this,void 0,void 0,function*(){var t="deleteGroupMember",{groupID:e,userIDList:s}=a,r=T.getLocalGroup(e),{helper:i,utils:{isUndefined:n},ssoLog:o}=this._core;if(n(r))throw new i.ChatError({functionName:t,code:2603});20<s.length&&(o.warn("deleteGroupMember",`${this._name}.${t} userIDList length:${s.length} exceeds limit 20`),s.splice(20));try{return yield function(r,i){return I(this,void 0,void 0,function*(){var{groupID:e,userIDList:t,reason:s}=r;return i.common.buildAndSendPacket({servcmd:"group_open_http_svc.delete_group_member",data:{GroupId:e,MemberToDel_Account:t,Reason:s}})})}({groupID:e,userIDList:s},this._core),A({group:r,userIDList:s},{message:`groupID:${e} userIDList length:`+s.length})}catch(e){throw new i.ChatError({functionName:t,code:null==e?void 0:e.errorCode,message:null==e?void 0:e.errorInfo})}})}},wo=new class{constructor(){this._name="SetGroupMemberMuteTime"}init(e){e=(this._core=e).helper;e.registerApi({apiName:"setGroupMemberMuteTime",context:this})}setGroupMemberMuteTime(o){return I(this,void 0,void 0,function*(){let t=this._core["helper"],{groupID:s,userID:r,muteTime:i}=o,n=` groupID:${s} userID:${r} muteTime:`+i;this._preCheckSettingMuteParams(o);try{yield Lo(o,this._core);let e=T.getLocalGroup(s),t=new Ro({userID:r,muteTime:i});return A({group:e,member:t},{message:n})}catch(e){throw new t.ChatError({functionName:"setGroupMemberMuteTime",code:null==e?void 0:e.errorCode,message:null==e?void 0:e.errorInfo,moreMessage:n})}})}_preCheckSettingMuteParams(e){var e=e["userID"],{store:t,helper:s}=this._core;if(e===t.get("login").userId)throw new s.ChatError({functionName:"setGroupMemberMuteTime",code:2685})}},Uo=new class{constructor(){this._name="SetGroupMemberRole"}init(e){e=(this._core=e).helper;e.registerApi({apiName:"setGroupMemberRole",context:this})}setGroupMemberRole(a){return I(this,void 0,void 0,function*(){let t="setGroupMemberRole",s=this._core["helper"],{groupID:r,userID:i,role:n}=a,o=`${this._name}.${t} ok, groupID:${r} userID:${i} role:`+n;this._preCheckSettingRoleParams(a);try{yield Lo(a,this._core);let e=T.getLocalGroup(r),t=new Ro({userID:i,role:n});return A({group:e,member:t},{message:o})}catch(e){throw new s.ChatError({functionName:t,code:null==e?void 0:e.errorCode,message:null==e?void 0:e.errorInfo,moreMessage:o})}})}_preCheckSettingRoleParams(e){var{groupID:e,userID:t,role:s}=e,{store:r,helper:i,OuterConstant:n,common:{isCommunity:o}}=this._core,a=T.getLocalGroup(e);if((null==(a=null==a?void 0:a.selfInfo)?void 0:a.role)!==n.GRP_MBR_ROLE_OWNER)throw new i.ChatError({functionName:"setGroupMemberRole",code:2681});if(t===r.get("login").userId)throw new i.ChatError({functionName:"setGroupMemberRole",code:2684});a=[...Zn];if(o({groupID:e})&&a.push(n.GRP_MBR_ROLE_CUSTOM),!a.includes(s))throw new i.ChatError({functionName:"setGroupMemberRole",code:2683})}},ko=new class{constructor(){this._name="SetGroupMemberNameCard"}init(e){e=(this._core=e).helper;e.registerApi({apiName:"setGroupMemberNameCard",context:this})}setGroupMemberNameCard(l){return I(this,void 0,void 0,function*(){let i="setGroupMemberNameCard",{helper:t,common:{getCurrentUserID:n}}=this._core;this._preCheckSettingNameCardParams(l);try{let{groupID:e,userID:t=n(),nameCard:s}=l,r={groupID:e,userID:t,nameCard:s};yield Lo(r,this._core);var o=`${this._name}.${i} ok, groupID:${e} userID:${t} nameCard:`+s,a=T.getLocalGroup(e),u=new Ro({userID:t,nameCard:s});return A({group:a,member:u},{message:o})}catch(e){throw new t.ChatError({functionName:i,code:null==e?void 0:e.errorCode,message:null==e?void 0:e.errorInfo,moreMessage:logText})}})}_preCheckSettingNameCardParams(e){var e=e["groupID"],t=this._core["helper"],e=T.getLocalGroup(e);if(io(null==e?void 0:e.type))throw new t.ChatError({functionName:"setGroupMemberNameCard",code:2687})}},Fo=new class{constructor(){this._name="SetGroupMemberCustomField"}init(e){e=(this._core=e).helper;e.registerApi({apiName:"setGroupMemberCustomField",context:this})}setGroupMemberCustomField(a){return I(this,void 0,void 0,function*(){let t="setGroupMemberCustomField",{helper:s,common:{getCurrentUserID:e}}=this._core;this._preCheckSettingCustomFiledParams(a);var{groupID:r,userID:i=e(),memberCustomField:n}=a,o=`${this._name}.${t} ok, groupID:${r}userID:${i} memberCustomField:`+JSON.stringify(n);try{let e={groupID:r,userID:i,memberCustomField:n},t=(yield Lo(e,this._core),T.getLocalGroup(r)),s=new Ro({userID:i,memberCustomField:n});return A({group:t,member:s},{message:o})}catch(e){throw new s.ChatError({functionName:t,code:null==e?void 0:e.errorCode,message:null==e?void 0:e.errorInfo,moreMessage:o})}})}_preCheckSettingCustomFiledParams(e){var e=e["groupID"],t=this._core["helper"],e=T.getLocalGroup(e);if(io(null==e?void 0:e.type))throw new t.ChatError({functionName:"setGroupMemberCustomField",code:2687})}},qo=new class{init(e,t){e.ssoLog.debug("GroupMember.init"),No.init(e,t),bo.init(e),Go.init(e),Po.init(e,t),wo.init(e),Uo.init(e),ko.init(e),Fo.init(e)}getGroupMemberList(e){return No.getGroupMemberList(e)}deleteGroupMember(e){return Po.deleteGroupMember(e)}},xo=new class{init(e){e=(this._core=e).helper;e.registerApi({apiName:"getGroupCounters",context:this})}getGroupCounters(u){return I(this,void 0,void 0,function*(){var t="getGroupCounters";try{uo(t,Wn);var e,s,r,{groupID:i,keyList:n=[]}=u,{avChatRoomKey:o,lastUpdateTime:a}=fo.getLocalGroupCounters(i);return Date.now()-a>=this._getExpireTime()&&(e=yield function(i){return I(this,void 0,void 0,function*(){var{groupID:e,GroupCounterKeys:t,avChatRoomKey:s}=i,r=jn.core["common"];return r.buildAndSendPacket({servcmd:"group_open_http_svc.get_group_counter",data:{GroupId:e,keyList:t,BytesKey:s}})})}({groupID:i,keyList:n,avChatRoomKey:o}),{GroupCounter:s=[],GroupCounterSeq:r}=e,fo.updateLocalGroupCounters({groupID:i,counterList:s,groupCounterSeq:r})),{code:0,data:{counters:fo.getLocalCounters(i,n)}}}catch(e){lo(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)}},Vo=new class{init(e){e=e.helper;e.registerApi({apiName:"setGroupCounters",context:this}),e.registerApi({apiName:"increaseGroupCounter",context:this}),e.registerApi({apiName:"decreaseGroupCounter",context:this})}setGroupCounters(e){return I(this,void 0,void 0,function*(){return this._handleCounterOperation("Set",e)})}increaseGroupCounter(e){return I(this,void 0,void 0,function*(){return this._handleCounterOperation("Increase",e)})}decreaseGroupCounter(e){return I(this,void 0,void 0,function*(){return this._handleCounterOperation("Decrease",e)})}_handleCounterOperation(a,u){return I(this,void 0,void 0,function*(){var t=a+"GroupCounter";try{uo(t,Wn);var{groupID:e,key:s,value:r=0}=u,i=fo.getLocalGroupCounters(e)["avChatRoomKey"],n="Set"===a?this._convertObjectToList(u.counters):[{Key:s,Value:r}],o=yield this._updateGroupCounters({groupID:e,counterList:n,avChatRoomKey:i,mode:a});return fo.setGroupCounters(e,o),{code:0,data:{counters:o}}}catch(e){lo(t,e)}})}_updateGroupCounters(n){return I(this,void 0,void 0,function*(){let e=yield function(){var{groupID:e,counterList:t,mode:s,avChatRoomKey:r}=n,i=jn.core["common"];return i.buildAndSendPacket({servcmd:"group_open_http_svc.update_group_counter",data:{GroupId:e,GroupCounter:t,Mode:s,BytesKey:r}})}(),{GroupCounter:t=[]}=e,s={};return t.forEach(e=>{var{Key:e,Value:t=0}=e;s[e]=t}),s})}_convertObjectToList(e){return Object.entries(e).map(([e,t])=>({Key:e,Value:t||0}))}},Bo=new class{init(e){this._core=e,xo.init(e),Vo.init(e)}isGroupCounterUpdated(e){var e=e["elements"]["groupCounterInfo"],t=this._core["utils"]["isEmpty"];return!t(e)}handleGroupCounterUpdated(e){let{to:r,elements:{groupCounterInfo:t}}=e;t.forEach(e=>{var{type:e,groupCounterSeq:t,counterList:s=[]}=e;0!==e&&2!==e||this._processAndNotifyCounterUpdate(r,t,s),1===e&&fo.deleteLocalGroupCounters({groupID:r,groupCounterSeq:t,counterList:s})})}_processAndNotifyCounterUpdate(s,e,t){let{OuterEvent:r,notificationCenter:i}=this._core;fo.updateLocalGroupCounters({groupID:s,groupCounterSeq:e,counterList:t}),t.forEach(({Key:e,Value:t=0})=>{i.emitOuterEvent(r.GROUP_COUNTER_UPDATED,{name:r.GROUP_COUNTER_UPDATED,data:{groupID:s,key:e,value:t}})})}reset(){fo.reset()}},jo=new class{constructor(){this._name="InitGroupAttributes"}init(e){e=(this._core=e).helper;e.registerApi({apiName:"initGroupAttributes",context:this})}initGroupAttributes(e){return I(this,void 0,void 0,function*(){let{groupID:i,groupAttributes:n}=e,{serverMainSequence:o,avChatRoomKey:a}=O.getGroupAttributesCache(i),u=O.convertKeyValueMapToList(n);try{let e=yield function(i,n){return I(this,void 0,void 0,function*(){var{groupID:e,mainSequence:t,groupAttributeList:s,avChatRoomKey:r}=i;return n.common.buildAndSendPacket({servcmd:"group_open_http_svc.set_group_attr",data:{GroupId:e,AttrMainSeq:t,GroupAttr:s,BytesKey:r,AttrControl:["RaceConflict"]}})})}({groupID:i,avChatRoomKey:a,groupAttributeList:u,mainSequence:o},this._core),{AttrMainSeq:t,GroupAttr:s}=e||{},r=s.map(e=>{var{Key:e,seq:t}=e;return{key:e,value:n[e],sequence:t}});return O.saveGroupAttributesCacheValuesCopy(i),O.refreshGroupAttributesCache({groupID:i,serverMainSequence:t,groupAttributeList:r,operation:1}),O.emitGroupAttributesUpdated(i),A({groupAttributes:n},{message:` groupID:${i} serverMainSequence:`+t})}catch(e){throw new this._core.helper.ChatError({functionName:"initGroupAttributes",code:null==e?void 0:e.errorCode,message:null==e?void 0:e.errorInfo})}})}},Ko=new class{constructor(){this._name="SetGroupAttributes"}init(e){e=(this._core=e).helper;e.registerApi({apiName:"setGroupAttributes",context:this})}setGroupAttributes(e){return I(this,void 0,void 0,function*(){let{groupID:i,groupAttributes:n}=e,{serverMainSequence:o,avChatRoomKey:a,values:r}=O.getGroupAttributesCache(i),u=O.convertKeyValueMapToList(n).map(e=>{var{key:t,value:s}=e;return{key:t,value:s,seq:(null==(t=r.get(e.key))?void 0:t.sequence)||0}});try{let e=yield function(i,n){return I(this,void 0,void 0,function*(){var{groupID:e,mainSequence:t,groupAttributeList:s,avChatRoomKey:r}=i;return n.common.buildAndSendPacket({servcmd:"group_open_http_svc.modify_group_attr",data:{GroupId:e,AttrMainSeq:t,GroupAttr:s,BytesKey:r,AttrControl:["RaceConflict"]}})})}({groupID:i,avChatRoomKey:a,groupAttributeList:u,mainSequence:o},this._core),{AttrMainSeq:t,GroupAttr:s}=e||{},r=s.map(e=>{var{Key:e,seq:t}=e;return{key:e,value:n[e],sequence:t}});return O.saveGroupAttributesCacheValuesCopy(i),O.refreshGroupAttributesCache({groupID:i,serverMainSequence:t,groupAttributeList:r,operation:2}),O.emitGroupAttributesUpdated(i),A({groupAttributes:n},{message:` groupID:${i} serverMainSequence:`+t})}catch(e){throw new this._core.helper.ChatError({functionName:"setGroupAttributes",code:null==e?void 0:e.errorCode,message:null==e?void 0:e.errorInfo})}})}},Wo=new class{constructor(){this._name="DeleteGroupAttributes"}init(e){e=(this._core=e).helper;e.registerApi({apiName:"deleteGroupAttributes",context:this})}deleteGroupAttributes(u){return I(this,void 0,void 0,function*(){var t="deleteGroupAttributes",{groupID:e,keyList:s=[]}=u;try{var{resultList:r,serverMainSequence:i,operation:n,groupAttributeList:o}=(0===s.length?yield this._clearGroupAttributes(e):yield this._deleteGroupAttributes(e,s))||{},a=this._name+`.${t} ok. groupID:${e} operation: `+n;return O.saveGroupAttributesCacheValuesCopy(e),O.refreshGroupAttributesCache({groupID:e,serverMainSequence:i,groupAttributeList:o,operation:n}),O.emitGroupAttributesUpdated(e),A({keyList:r},{message:a})}catch(e){throw new this._core.helper.ChatError({functionName:t,code:null==e?void 0:e.errorCode,message:null==e?void 0:e.errorInfo})}})}_deleteGroupAttributes(o,a){return I(this,void 0,void 0,function*(){let{serverMainSequence:e,avChatRoomKey:t,values:s}=O.getGroupAttributesCache(o),r=[],i=[];a.forEach(e=>{var t;s.has(e)&&({sequence:t=0}=s.get(e)||{},i.push({key:e,seq:t}),r.push(e))});var n=((yield function(i,n){return I(this,void 0,void 0,function*(){var{groupID:e,mainSequence:t,groupAttributeList:s,avChatRoomKey:r}=i;return n.common.buildAndSendPacket({servcmd:"group_open_http_svc.delete_group_attr",data:{GroupId:e,AttrMainSeq:t,GroupAttr:s,BytesKey:r,AttrControl:["RaceConflict"]}})})}({groupID:o,avChatRoomKey:t,groupAttributeList:i,mainSequence:e},this._core))||{})["AttrMainSeq"];return{resultList:r,serverMainSequence:n,groupAttributeList:i,operation:4}})}_clearGroupAttributes(r){return I(this,void 0,void 0,function*(){var{serverMainSequence:e,avChatRoomKey:t,values:s}=O.getGroupAttributesCache(r),s=[...s.keys()],t=((yield function(r,i){return I(this,void 0,void 0,function*(){var{groupID:e,mainSequence:t,avChatRoomKey:s}=r;return i.common.buildAndSendPacket({servcmd:"group_open_http_svc.clear_group_attr",data:{GroupId:e,AttrMainSeq:t,BytesKey:s,AttrControl:["RaceConflict"]}})})}({groupID:r,avChatRoomKey:t,mainSequence:e},this._core))||{})["AttrMainSeq"];return{resultList:s,serverMainSequence:t,operation:3}})}},Ho=new class{constructor(){this._name="GetGroupAttributes"}init(e){e=(this._core=e).helper;e.registerApi({apiName:"getGroupAttributes",context:this})}getGroupAttributes(u){return I(this,void 0,void 0,function*(){let r=u["groupID"],{avChatRoomKey:i,lastUpdateTime:e,localMainSequence:t,serverMainSequence:s}=O.getGroupAttributesCache(r),{ChatError:n}=this._core["helper"],o=`groupID:${r} localMainSequence:${t} serverMainSequence:${s} keyList:`+u.keyList;if(3e4<=Date.now()-e||t<s)try{let e=yield this.getGroupAttributesFromServer({groupID:r,avChatRoomKey:i}),t=O.getGroupAttributesCacheValues(u),{serverGroupAttributeList:s=[]}=e||{};return A({groupAttributes:t},{message:o,moreMessage:"from server, count:"+s.length})}catch(e){throw new n({functionName:"getGroupAttributes",code:null==e?void 0:e.errorCode,message:null==e?void 0:e.errorInfo})}var a=O.getGroupAttributesCacheValues(u);return A({groupAttributes:a},{message:o,moreMessage:"from cache"})})}getGroupAttributesFromServer(i){return I(this,void 0,void 0,function*(){var{utils:{isUndefined:e},ssoLog:t}=this._core,{groupID:s,avChatRoomKey:r}=i,{AttrMainSeq:e=0,GroupAttrAry:r}=(yield function(r,i){return I(this,void 0,void 0,function*(){var{groupID:e,groupType:t,avChatRoomKey:s}=r;return i.common.buildAndSendPacket({servcmd:"group_open_attr_http_svc.get_group_attr",data:{GroupId:e,GroupType:t,Key:s}})})}({groupID:s,avChatRoomKey:r,groupType:e(r)?0:1},this._core))||{},t=(t.debug("getGroupAttributesFromServer",this._name+`._getGroupAttributesFromServer ok. groupID:${s} serverMainSequence:`+e),r.map(e=>{var{key:e,value:t,seq:s}=e;return{key:e,value:t,sequence:s}}));return O.refreshGroupAttributesCache({groupID:s,serverMainSequence:e,groupAttributeList:t,operation:5}),{serverGroupAttributeList:r}})}},Yo=new class{init(e){e.ssoLog.debug("GroupAttribute.init"),jo.init(e),Ko.init(e),Wo.init(e),Ho.init(e),O.init(e)}isGroupAttributesUpdated(e){return O.isGroupAttributesUpdated(e)}handleGroupAttributesUpdated(e){let{to:t,elements:{newGroupProfile:s}}=e,r=s["groupAttributeOption"],{serverMainSequence:i,withChangedAttributeInfo:n}=r,o=O.getGroupAttributesCache(t)["localMainSequence"],a=i-o;if(console.log(`GroupAttribute.handleGroupAttributesUpdated groupID:${t} withChangedAttributeInfo:${n} diffSequence:`+a),0!=a)if(O.saveGroupAttributesCacheValuesCopy(t),1!==n||1!=a){if(O.hasGroupAttributesCache(t)){let e=O.getGroupAttributesCache(t)["avChatRoomKey"];Ho.getGroupAttributesFromServer({groupID:t,avChatRoomKey:e}).then(()=>{O.emitGroupAttributesUpdated(t)}).catch(()=>{})}}else O.handleGroupAttributesUpdated({groupID:t,groupAttributeOption:r})}reset(){O.reset()}};function $o(e,t="tips"){let{ClientSeq:s,From_Account:r,MsgClientTime:i,MsgPriority:n,MsgRandom:o,MsgSeq:a,MsgTimeStamp:u,TinyId:l,ToGroupId:c,GroupInfo:d,MsgBody:p}=e,h=function(){var{GroupCode:e,GroupId:t,GroupName:s,GroupType:r,MsgFrom_AccountExtraInfo:i,From_Account:n,To_Account:o}=d;return{groupCode:e,groupID:t,groupName:s,type:r,messageFromAccountExtraInformation:i,from:n,to:o}}();return{clientSequence:s,from:r,clientTime:i,priority:n,random:o,sequence:a,time:u,tinyID:l,to:c,groupProfile:h,elements:("tips"===t?zo:Qo)(p)}}function zo(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=>Jo(e));break;case"MsgOperatorMemberExtraInfo":e.operatorInfo=Jo(r[s]);break;case"MsgGroupNewInfo":e.newGroupProfile=function(o){let e={};return Object.keys(o).forEach(n=>{switch(n){case"GroupIntroduction":e.introduction=o[n];break;case"GroupName":e.groupName=o[n];break;case"GroupFaceUrl":e.avatar=o[n];break;case"GroupNotification":e.notification=o[n];break;case"ApplyJoinOption":e.joinOption=o[n];break;case"InviteJoinOption":e.inviteOption=o[n];break;case"ShutupAll":e.muteAllMembers=o[n];break;case"Owner_Account":e.ownerID=o[n];break;case"GroupAttrOption":e.groupAttributeOption=function(){var{BytesChangedKeys:e,GroupAttrSeq:t,OpType:s,PushChangedAttrValFlag:r,GroupAttrInfo:i}=o[n];return{changedKeyList:e,groupAttributeList:i.map(e=>{var{Key:e,Val:t,SubKeySeq:s}=e;return{key:e,value:t,sequence:s}}),serverMainSequence:t,operation:s,withChangedAttributeInfo:r}}()}}),e}(r[s]);break;case"MsgMemberInfo":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 Jo(e){var{ImageUrl:e,NickName:t,Role:s,UserId:r}=e;return{avatar:e,nick:t,role:s,userID:r}}function Qo(t){let s={};return Object.keys(t).forEach(e=>{switch(e){case"MsgKey":s.messageKey=t[e];break;case"Operator_Account":s.operatorID=t[e];break;case"ReportType":s.operationType=t[e];break;case"Authentication":s.authentication=t[e];break;case"MsgFlag":s.messageRemindType=t[e];break;case"UserDefinedField":s.userDefinedField=t[e];break;case"RemarkInfo":s.remarkInfo=t[e];break;case"BanDuration":s.duration=t[e];break;case"MuteTime":s.muteTime=t[e]}}),s}class Xo{constructor(e){this.type=jn.core.OuterConstant.MSG_GRP_TIP,this.content={},this._initContent(e)}static parseServerPushElement(e){e=zo(e);return new Xo(e)}_initContent(t){Object.keys(t).forEach(e=>{switch(e){case"groupProfile":this._initGroupProfile(t[e]);break;case"operatorInfo":this._initOperatorInfo(t[e]);break;case"memberInfoList":case"msgMemberInfo":this._updateMemberList(t[e]);break;case"newGroupProfile":this._initNewGroupProfile(t[e]);break;case"memberExtraInfo":case"remarkInfo":case"onlineMemberInfo":break;default:this.content[e]=t[e]}}),this.content.userIDList||(this.content.userIDList=[this.content.operatorID])}_initGroupProfile(t){this.content.groupProfile={};var s=Object.keys(t);for(let e=0;e<s.length;e++){var r=s[e];to[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 Zo=new class{constructor(){this._name="GroupTipsNotification"}init(e){var{common:{workflowManager:t},constants:{WORKFLOW_NAME:s,WORKFLOW_STEP:r}}=this._core=e,{message:{messageFactory:e},OuterConstant:i}=e;null!=e&&e.registerElementClass(i.MSG_GRP_TIP,Xo),t.registerWorkflowStep(s.SYNC_SERVER_INFO_AFTER_RE_ONLINE,r.GROUP_TIPS_RECOVER,this._handleGroupTipsRecover,this),t.registerWorkflowStep(s.RECEIVE_GROUP_TIPS_NOTIFICATION,r.HANDLE_GROUP_TIPS_NOTIFICATION,this.onNewGroupTips,this)}onNewGroupTips(e){let t=(e||{})["data"],{messageList:s,conversationUpdateFieldList:r}=this._handleGroupTips(t),{notificationCenter:i,OuterEvent:n,appStore:{conversationStore:o}}=this._core;return null!=r&&r.forEach(e=>{var{conversationID:e,lastMessage:t,unreadCount:s}=e,{unreadCount:r=0}=o.getConversation(e)||{};o.updateConversation(e,{lastMessage:t,unreadCount:s+r})}),0<s.length&&(i.emitOuterEvent(n.MESSAGE_RECEIVED,{name:n.MESSAGE_RECEIVED,data:s}),this._handleGroupTipMessage(s)),{conversationUpdateFieldList:r}}_handleGroupTips(e,s=!0){let{Event:r,GroupTips:i}=e,n=new Map,t=[],o=[];for(let t=0,e=i.length;t<e;t++){let e=$o(i[t],"tips");if(6===r){if(Yo.isGroupAttributesUpdated(e)){Yo.handleGroupAttributesUpdated(e);continue}if(Bo.isGroupCounterUpdated(e)){Bo.handleGroupCounterUpdated(e);continue}}var a=e["groupProfile"]["groupID"];if(T.hasLocalGroup(a)){a=this._assembleMessage(e);if(6===r&&(a._onlineOnlyFlag=!0,o.push(a)),4===r){if(!this._core.message.messageDataHandler.storeConversationMessage(a)&&s)continue;o.push(a)}this._handleConversationOptions(n,a)}}return t.push(...n.values()),{conversationUpdateFieldList:t,messageList:o}}_assembleMessage(e){var{OuterConstant:t,message:{messageFactory:s}}=this._core,t=(e.flow="in",e.conversationType=t.CONV_GROUP,s.createMessage(e)),s=(this._patchNickAndAvatar(e.elements,t),new Xo(Object.assign(Object.assign({},e.elements),{groupProfile:Object.assign({},e.groupProfile)})));return t.setElement(s),t.isSystemMessage=!1,t}_patchNickAndAvatar(e,s){let{utils:{isEmpty:t},OuterConstant:{GROUP_TIPS_OPERATION_TYPE:r}}=this._core,{operationType:i,memberInfoList:n,operatorInfo:o}=e,a={};if(t(n)?t(o)||(a=o):i!==r.JOINED&&i!==r.KICKED&&i!==r.ADMIN_SET&&i!==r.ADMIN_CANCELED||(a=Object.assign({},n[0])),!t(a)){let{nick:e="",avatar:t=""}=a;s.nick=e,s.avatar=t}}_handleConversationOptions(e,t){var{common:{getMessagePreviewText:s},utils:{isObject:r}}=this._core,{conversationID:i,conversationType:n}=t;let o;if(e.has(i))o=e.get(i),"in"!==t.flow||t._isExcludedFromUnreadCount||t._onlineOnlyFlag||o.unreadCount++,o.type=n,o.lastMessage=t._isExcludedFromLastMessage?"":Object.assign({},t);else{let e=0;"in"!==t.flow||t._isExcludedFromUnreadCount||t._onlineOnlyFlag||(e=1),o={conversationID:i,unreadCount:e,type:n,lastMessage:t._isExcludedFromLastMessage?"":Object.assign({},t)}}r(o.lastMessage)&&(o.lastMessage.messageForShow=s(o.lastMessage.type,o.lastMessage.payload)),e.set(i,o)}_handleGroupTipMessage(e){let{GROUP_TIPS_OPERATION_TYPE:s}=this._core["OuterConstant"];e.forEach(e=>{var t=e.payload["operationType"];switch(t){case s.JOINED:this._handleNewMemberJoined(e);break;case s.QUITTED:this._handleMemberQuitted(e);break;case s.KICKED:this._handleMemberKicked(e);break;case s.GROUP_PROFILE_UPDATED:this._handleGroupProfileUpdated(e)}})}_handleNewMemberJoined(e){this._handleGroupMemberCountUpdated(e)}_handleMemberQuitted(e){this._handleGroupMemberCountUpdated(e)}_handleMemberKicked(e){this._handleGroupMemberCountUpdated(e)}_handleGroupProfileUpdated(e){let t,{newGroupProfile:s,groupProfile:r,operatorInfo:i}=e.payload,n=r.groupID,o=T.getLocalGroup(n);Object.keys(s).forEach(e=>{switch(e){case"ownerID":this._handleGroupOwnerChanged(n,s);break;case"groupName":o.name=s[e];break;default:o[e]=s[e]}});var e=this._core["utils"]["isUndefined"];e(i)||(null==(t=null==o?void 0:o.selfInfo)?void 0:t.userID)!==i.userID||Object.keys(i).forEach(e=>{"nameCard"===e&&o.updateSelfInfo({nameCard:i[e]}),"role"===e&&this._updateSelfRole(o,i[e])}),T.emitGroupListUpdate(),T.updateConversationGroupProfile(n)}_handleGroupOwnerChanged(e,t){var{common:s,OuterConstant:r}=this._core,e=T.getLocalGroup(e),t=t["ownerID"];s.getCurrentUserID()===t&&e.updateGroup({ownerID:t,selfInfo:{role:r.GRP_MBR_ROLE_OWNER}})}_updateSelfRole(e,t){var s=this._core["OuterConstant"];let r=s.GRP_MBR_ROLE_MEMBER;400===t?r=s.GRP_MBR_ROLE_OWNER:300===t&&(r=s.GRP_MBR_ROLE_ADMIN),e.updateSelfInfo({role:r})}_handleGroupMemberCountUpdated(e){var{memberCount:e,groupProfile:{groupID:t}}=e.payload,s=T.getLocalGroup(t),r=this._core["utils"]["isNumber"];s&&r(e)&&s.memberCount!==e&&(s.memberCount=e,T.emitGroupListUpdate(),T.updateConversationGroupProfile(t))}_handleGroupTipsRecover(e){var t=this._core["utils"]["isArray"],e=((null==e?void 0:e.result)||{})["groupTipList"];t(e)&&e.forEach(e=>{e=this._handleGroupTips({Event:e.Event,GroupTips:[e]},!1).messageList;this._handleGroupTipMessage(e)})}};class ea{constructor(e){this.type=jn.core.OuterConstant.MSG_GRP_SYS_NOTICE,this.content={},this._initContent(e)}static parseServerPushElement(e){e=Qo(e);return new ea(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];so[r]&&(this.content.groupProfile[r]=t[r])}}}var ta=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,ea)}onNewGroupSystemNotification(e){var{GroupTips:e=[],isInstantMessage:t=!0}=e,{conversationUpdateFieldList:e,messageList:s}=(this._core.ssoLog.debug("onNewGroupSystemNotification",` count:${e.length} isInstantMessage:`+t),this._handleGroupSystemNotification(e,t)),{notificationCenter:r,OuterEvent:i}=this._core;0<e.length&&this._handleGroupSysTemMessage(t,s),!0===t&&0<s.length&&r.emitOuterEvent(i.MESSAGE_RECEIVED,{name:i.MESSAGE_RECEIVED,data:s})}_handleGroupSystemNotification(t,s){var r=[];let i={};for(let e=0;e<t.length;e++){var n=$o(t[e],"system"),o=n["elements"]["operationType"];15!==o&&(o=this._assembleMessage(n),this._core.message.messageDataHandler.storeConversationMessage(o))&&(r.push(o),i=this._handleConversationOptions(o,s))}return i.lastMessage=r[r.length-1],{conversationUpdateFieldList:0<r.length?[i]:[],messageList:r}}_assembleMessage(e){var{message:{messageFactory:t},OuterConstant:s,utils:{randomInt:r}}=this._core,s=(e.flow="in",e.conversationType=s.CONV_SYSTEM,e.conversationSubType=e.groupProfile.type,e.conversationID=s.CONV_SYSTEM,t.createMessage(e)),t=new ea(Object.assign(Object.assign({},e.elements),{groupProfile:Object.assign({},e.groupProfile)})),e=(s.setElement(t),s.isSystemMessage=!0,1===s.sequence&&1===s.random),t=2===s.sequence&&2===s.random;return(e||t)&&(s.sequence=r(),s.random=r(),s.generateMessageID()),s}_handleConversationOptions(e,t){var s=this._core["OuterConstant"],s={conversationID:s.CONV_SYSTEM,unreadCount:0,type:s.CONV_SYSTEM,subType:e.conversationSubType,lastMessage:null};return t&&s.unreadCount++,s}_handleGroupSysTemMessage(e,t){e&&t.forEach(e=>{var t=e.payload["operationType"];switch(t){case 2:this._handleGroupJoinResult(e);break;case 4:this._handleMemberKicked(e);break;case 5:this._handleGroupDismissed(e);break;case 7:this._handleGroupInvitedResult(e);break;case 8:this._handleGroupQuitResult(e);break;case 20:this._handleMessageRemindTypeSynced(e);break;case 21:this._handleAVChatRoomMemberBanned(e)}})}_handleGroupJoinResult(e){var e=e.payload["groupProfile"],{groupID:t,type:s}=e,r=T.hasLocalGroup(t);this._core.ssoLog.debug("_handleGroupJoinResult",` groupID:${t} type:${s} hasLocalGroup:`+r),r||io(s)||(T.updateLocalGroup([Object.assign({},e)]),T.emitGroupListUpdate())}_handleMemberKicked(e){var{groupID:e,type:t}=e.payload["groupProfile"];T.hasLocalGroup(e)&&this._deleteLocalGroup(e,t),this._updateConversationProfile(e,{unreadCount:0})}_handleGroupDismissed(e){var{groupID:e,type:t}=e.payload["groupProfile"];T.hasLocalGroup(e)&&this._deleteLocalGroup(e,t),this._updateConversationProfile(e,{unreadCount:0})}_handleGroupInvitedResult(e){var e=e.payload["groupProfile"],e=e["groupID"],t=T.hasLocalGroup(e);this._core.ssoLog.debug("_handleGroupInvitedResult",` groupID:${e} hasLocalGroup:`+t),t||vo.getGroupProfile({groupID:e}).then(e=>{var e=e["data"]["group"];T.updateLocalGroup([Object.assign({},e)]),T.emitGroupListUpdate()})}_handleGroupQuitResult(e){var{groupID:e,type:t}=e.payload["groupProfile"],s=T.hasLocalGroup(e);this._core.ssoLog.debug("_handleGroupQuitResult",` groupID:${e} type:${t} hasLocalGroup:`+s),s&&this._deleteLocalGroup(e,t),this._updateConversationProfile(e,{unreadCount:0})}_handleMessageRemindTypeSynced(e){var{groupProfile:{groupID:e},messageRemindType:t}=e.payload;this._updateConversationProfile(e,{messageRemindType:t})}_handleAVChatRoomMemberBanned(e){var{groupID:e,type:t}=e.payload["groupProfile"];this._deleteLocalGroup(e,t)}_deleteLocalGroup(s,e){if(io(e)){let{appStore:{conversationStore:e},OuterConstant:{CONV_GROUP:t}}=this._core;e.deleteConversation(""+t+s)}T.deleteLocalGroup(s),T.emitGroupListUpdate()}_updateConversationProfile(e,t){var{appStore:{conversationStore:s},OuterConstant:{CONV_GROUP:r}}=this._core,r=""+r+e;s.getConversation(r)&&s.updateConversation(r,t)}},sa=new class{init(e){(this._core=e).ssoLog.debug("GroupNotificationHandler.init"),Zo.init(e),ta.init(e);var{notificationCenter:e,InnerEvent:t}=e,s=e["InnerEventSubType"];e.subscribeInnerEvent(t.MESSAGE_PUSH,s.GROUP_TIPS_NOTIFICATION,this._onNewGroupTipsNotification,this),e.subscribeInnerEvent(t.MESSAGE_PUSH,s.GROUP_SYSTEM_NOTIFICATION,this._onNewGroupSystemNotification,this),e.subscribeInnerEvent(t.DESTROY,this._dispose,this)}_onNewGroupTipsNotification(e){var{common:{workflowManager:t},constants:{WORKFLOW_NAME:s}}=this._core;t.executeWorkflow(s.RECEIVE_GROUP_TIPS_NOTIFICATION,e)}_onNewGroupSystemNotification(e){ta.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 D={required:!0,rules:["string"],allowEmpty:!1},ra={required:!0,rules:["number"],allowEmpty:!1},ia={required:!0,rules:["array"],allowEmpty:!1},na={required:!0,rules:["object"],allowEmpty:!1},oa={createGroup:{name:D,type:D},dismissGroup:[Object.assign({key:"groupID"},D)],joinGroup:{groupID:D,applyMessage:{required:!1,rules:["string"],allowEmpty:!0}},quitGroup:[Object.assign({key:"groupID"},D)],searchGroupByID:[Object.assign({key:"groupID"},D)],getGroupProfile:{groupID:D,groupCustomFieldFilter:{required:!1,rules:["array"],allowEmpty:!0}},updateGroupProfile:{groupID:D,muteAllMembers:{required:!1,rules:["boolean"],allowEmpty:!1}},changeGroupOwner:{groupID:D,newOwnerID:D},getGroupOnlineMemberCount:[Object.assign({key:"groupID"},D)],handleGroupApplication:{handleAction:D},getGroupMemberList:{groupID:D},getGroupMemberProfile:{groupID:D,userIDList:ia,memberCustomFieldFilter:{required:!1,rules:["array"],allowEmpty:!0}},addGroupMember:{groupID:D,userIDList:ia},deleteGroupMember:{groupID:D,userIDList:ia},setGroupMemberMuteTime:{groupID:D,userID:D,muteTime:Object.assign(Object.assign({},ra),{customValidator:e=>!(e<0)||"muteTime must be a non-negative number."})},setGroupMemberRole:{groupID:D,userID:D,role:D},setGroupMemberNameCard:{groupID:D,userID:{required:!1,rules:["string"],allowEmpty:!1},nameCard:D},setGroupMemberCustomField:{groupID:D,userID:{required:!1,rules:["string"],allowEmpty:!1},memberCustomField:ia},markGroupMemberList:{groupID:D,markType:Object.assign(Object.assign({},ra),{customValidator:e=>!(e<1e3)||"markType must be greater than or equal to 1000."}),enableMark:{required:!0,rules:["boolean"],allowEmpty:!1},userIDList:ia},initGroupAttributes:{groupID:D,groupAttributes:na},setGroupAttributes:{groupID:D,groupAttributes:na},deleteGroupAttributes:{groupID:D,keyList:Object.assign(Object.assign({},ia),{allowEmpty:!0})},getGroupAttributes:{groupID:D,keyList:Object.assign(Object.assign({},ia),{allowEmpty:!0})},getGroupCounters:{groupID:D,keyList:{required:!1,rules:["array"],allowEmpty:!0}},setGroupCounters:{groupID:D,counters:na},increaseGroupCounter:{groupID:D,key:D,value:ra},decreaseGroupCounter:{groupID:D,key:D,value:ra}},aa={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},ua=new class{constructor(){this._installedSubPlugins=[],this.groupDataHandler=T,this.groupAction=To,this.groupAttribute=Yo,this.groupMember=qo,this.name="Group"}install(e,t=[]){this._core=e,jn.init(e),T.init(e),To.init(e,this),qo.init(e,this),Do.init(e),Bo.init(e),Yo.init(e),sa.init(e),e.helper.registerValidateConfig({auth:aa,params:oa}),this._installSubPlugins(t);var{notificationCenter:t,InnerEvent:e}=e;t.subscribeInnerEvent(e.LOGOUT,this._reset,this),t.subscribeInnerEvent(e.DESTROY,this._dispose,this)}getInstalledSubPlugins(){return this._installedSubPlugins}_installSubPlugins(e){var{isArray:t}=this._core["utils"];e&&t(e)&&e.forEach(e=>{var t;this._installedSubPlugins.includes(e.name)||(null!=(t=e.install)&&t.call(e,this._core,this),this._installedSubPlugins.push(e.name))})}_reset(){T.reset(),Yo.reset(),Bo.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)}},la=new class{init(e){this.core=e}},ca={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},da={GROUP_DISMISSED:5,QUIT_GROUP:8,AVCHATROOM_MEMBER_BANNED:21};class pa{constructor(e){var{core:e,manager:t,groupID:s,getRequestParams:r,onSuccess:i,onFail:n}=e;this._name="Polling",this._core=e,this._manager=t,this._timeoutID=-1,this._isRunning=!1,this._groupID=s,this._getRequestParams=r,this._onSuccess=i,this._onFail=n}start(){this._isRunning=!0,this._request(),console.log(this._name+".start pollingInterval:"+this._manager.getCurrentPollingInterval(this._groupID))}isRunning(){return this._isRunning}_request(){return I(this,void 0,void 0,function*(){try{var e=yield function(i,n){return I(this,void 0,void 0,function*(){var{longPollingKey:e,startSequence:t,startBroadcastSeq:s,simplifiedMessage:r}=i;return n.common.buildAndSendPacket({servcmd:"group_open_long_polling_http_svc.get_msg",data:{Key:e,StartSeq:t,StartBroadcastSeq:s,DownsizeFlag:r,USP:1,HoldTime:90}})})}(this._getRequestParams(this._groupID),this._core),t=(this._onSuccess(this._groupID,e),this._manager.getCurrentPollingInterval(this._groupID));this._runNextPolling(t)}catch(e){this._onFail(this._groupID,e),this._runNextPolling(2e3)}})}_runNextPolling(e){this.isRunning()&&(-1<this._timeoutID&&clearTimeout(this._timeoutID),this._timeoutID=setTimeout(this._request.bind(this),e))}stop(){console.log(this._name+".stop timerID:"+this._timeoutID),-1<this._timeoutID&&(clearTimeout(this._timeoutID),this._timeoutID=-1),this._isRunning=!1}}class ha{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 ga=e=>e===ca.GROUP_TIPS_HAS_NO_ROAMING||e===ca.GROUP_TIPS_HAS_ROAMING,_a=e=>e===ca.GROUP_SYSTEM_MESSAGE;function ma(h){var e,t,s,r,i,n,o,a=function(){var{E:e,MCT:t,MR:s,MP:r,MTS:i,GId:n,MS:o,CCD:a,F_Account:u,IsSys:l,GInf:c,MsgBody:d}=h,p=f(h,["E","MCT","MR","MP","MTS","GId","MS","CCD","F_Account","IsSys","GInf","MsgBody"]);return Object.assign({Event:e,MsgClientTime:t,MsgRandom:s,MsgPriority:r,MsgTimeStamp:i,ToGroupId:n,MsgSeq:o,CloudCustomData:a,From_Account:u,IsSystemMsg:l,GroupInfo:function(e){var e=e||{},{GN:t,GT:s,F_Hd:r,F_NN:i,F_Ll:n}=e,e=f(e,["GN","GT","F_Hd","F_NN","F_Ll"]),t=Object.assign({GroupName:t,GroupType:s},e);return r&&(t.From_AccountHeadurl=r),i&&(t.From_AccountNick=i),n&&(t.From_AccountLevel=n),t}(c),MsgBody:function(e){let t=e,s=(t=Array.isArray(e)?t:[e]).map(e=>{var{O_Account:t,Opt:s,L_Account:r,RT:i,UDF:n,OpInf:o,OnlineInf:a,MsgMemberExtraInfo:u}=e,e=f(e,["O_Account","Opt","L_Account","RT","UDF","OpInf","OnlineInf","MsgMemberExtraInfo"]),t=Object.assign({Operator_Account:t,OpType:s,List_Account:r,ReportType:i,UserDefinedField:n},e);return o&&(t.MsgOperatorMemberExtraInfo=function(){var{Img:e,NN:t}=o,s=f(o,["Img","NN"]);return Object.assign({ImageUrl:e,NickName:t},s)}()),u&&(t.MsgMemberExtraInfo=u.map(e=>{var{Img:t,NN:s}=e,e=f(e,["Img","NN"]);return Object.assign({ImageUrl:t,NickName:s},e)})),a&&(t.OnlineMemberInfo=function(){var{ET:e,Num:t}=a;return{ExpireTime:e,OnlineMemberNum:t}}()),t});return Array.isArray(e)?s:s[0]}(d)},p)}(),u=a,l=u["Event"];if((ga(l)||_a(l))&&(u.From_Account=u.From_Account||"@TIM#SYSTEM"),l===ca.BROADCAST_MESSAGE||l===ca.NORMAL_MESSAGE){var c=u;let e=la["core"]["OuterConstant"];c.CloudCustomData=c.CloudCustomData||"",c.MsgBody=c.MsgBody.map(t=>{if(t.MsgType===e.MSG_CUSTOM){let{content:e={}}=t;t.content=Object.assign({Data:"",Desc:"",Ext:""},e)}return t})}return ga(l)&&({GroupJoinType:e,MsgOperatorMemberExtraInfo:t={},MsgMemberExtraInfo:s,Operator_Account:r,List_Account:i,OpType:n}=(c=u).MsgBody||{},"number"==typeof e||1!==n&&2!==n||(c.MsgBody.GroupJoinType=2===n?0:1),s||(c.MsgBody.MsgMemberExtraInfo=i.map(e=>({UserId:e}))),1!==n||s||(c.MsgBody.MsgMemberExtraInfo=[{UserId:t.UserId}]),c.MsgBody.MsgOperatorMemberExtraInfo=Object.assign({Operator_Account:r,ImageUrl:"",NickName:""},t)),_a(l)&&({MsgOperatorMemberExtraInfo:e={},Operator_Account:i}=(o=u).MsgBody||{},o.MsgBody.MsgMemberExtraInfo=Object.assign({UserId:i,ImageUrl:"",NickName:""},e),o.MsgBody=Object.assign({Authentication:"",RemarkInfo:"",MsgKey:1e3*o.MsgTimeStamp},o.MsgBody),o.MsgBody=Object.keys(o.MsgBody).filter(e=>"MsgOperatorMemberExtraInfo"!==e).reduce((e,t)=>Object.assign(Object.assign({},e),{[t]:o.MsgBody[t]}),{})),a}var va=new class{constructor(){this._name="MessageParser",this._sequenceList=new ha(200),this._messageIDList=new ha(100),this._broadcastMessageIDMap=new Map,this._reportMessageStackedCount=0}init(e,t){this._core=e,this._avChatRoomHandler=t}onMessageReceived(i,e,n=!1){this._sortServerMessageList({groupID:i,serverMessageList:e,isHistoryMessage:n});var o=this._handleMessageList(i,e);if(0!==o.length){if(!n){let{appStore:{conversationStore:e},OuterConstant:{CONV_GROUP:t}}=this._core,s=(e=>{var{common:{getMessagePreviewText:t}}=la["core"];return{lastTime:(null==e?void 0:e.time)||(null==e?void 0:e.lastTime)||0,lastSequence:(null==e?void 0:e.sequence)||(null==e?void 0:e.lastSequence)||0,fromAccount:(null==e?void 0:e.from)||(null==e?void 0:e.fromAccount)||"",messageForShow:t(null==e?void 0:e.type,null==e?void 0:e.payload),payload:(null==e?void 0:e.payload)||null,type:(null==e?void 0:e.type)||"",isRevoked:(null==e?void 0:e.isRevoked)||!1,cloudCustomData:(null==e?void 0:e.cloudCustomData)||"",onlineOnlyFlag:(null==e?void 0:e._onlineOnlyFlag)||!1,nick:(null==e?void 0:e.nick)||"",nameCard:(null==e?void 0:e.nameCard)||"",version:(null==e?void 0:e.version)||0,isPeerRead:(null==e?void 0:e.isPeerRead)||!1,revoker:(null==e?void 0:e.revoker)||null}})(o[o.length-1]);e.updateConversation(""+t+i,{lastMessage:s})}this._checkMessageStacked(o);let e=o.filter(e=>!0===e.isModified),t=o.filter(e=>!1===e.isModified),{MESSAGE_RECEIVED:s,MESSAGE_MODIFIED:r}=this._core["OuterEvent"];0<e.length&&this._emitEvent({name:r,data:e}),0<t.length&&this._emitEvent({name:s,data:t})}}_sortServerMessageList(e){var{groupID:e,serverMessageList:t,isHistoryMessage:s}=e;let r=[];r=this._avChatRoomHandler.isPollingSimplifiedMessage()&&!s?(t.sort((e,t)=>e.MS-t.MS),t.map(e=>e.MS)):(t.sort((e,t)=>e.MsgSeq-t.MsgSeq),t.map(e=>e.MsgSeq)),console.log(`${this._name}._sortServerMessageList groupID:${e} count:${r.length} sequenceList:`+r),r.length=0}_handleMessageList(s,r){var i,n,{messageDataHandler:o,messageHelper:a}=this._core["message"],u=this._avChatRoomHandler.isPollingSimplifiedMessage(),l=[],e=r.length;for(let t=0;t<e;t++){let e=r[t];if(u&&(e=ma(e)),_a(e.Event)&&Object.values(da).includes(e.MsgBody.ReportType)){this._onGroupDismissed(s);break}null!==this._filterMessageItem(e)&&(this._patchMessageType(e),i=a.parseServerGroupMessage(e),(n=this._createMessage(i)).level=e.GroupInfo.From_AccountLevel,ga(e.Event)&&this._avChatRoomHandler.isGroupAttributesUpdated(i)?this._avChatRoomHandler.handleGroupAttributesUpdated(i):null===this._filterDuplicateMessage(n)||o.isMessageSentByCurrentInstance(n)||(1===i.isModified&&(n.isModified=!0),ga(e.Event)&&this._updateLocalOnlineMemberCountFromTips(e),l.push(n)))}return l}_patchMessageType(e){var t=this._core["OuterConstant"];ga(e.Event)&&(e.MsgBody.MsgType=t.MSG_GRP_TIP),_a(e.Event)&&(e.MsgBody.MsgType=t.MSG_GRP_SYS_NOTICE)}_filterMessageItem(e){var t=e["Event"];return Object.values(ca).includes(t)?t===ca.MESSAGE_REVOKED?(this._handleMessageRevoked(e),null):t===ca.LIVE_CUSTOM_DATA?(this._onLiveCustomData(e),null):t===ca.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===ca.GROUP_SYSTEM_MESSAGE&&(r=s.CONV_SYSTEM);s=!!e.isSystemMessage,t=t.createMessage(Object.assign(Object.assign({},e),{conversationType:r,isSystemMessage:s,flow:"in"}));return t.setElement(e.elements),t}_filterDuplicateMessage(e){var t=this._core["common"];if(!t.isUnlimitedAVChatRoom()){if(this._sequenceList.has(e.sequence))return null;this._sequenceList.set(e.sequence)}t=this._messageIDList.has(e.ID);return t?(console.warn(`${this._name}_filterDuplicateMessageItem ID:${e.ID} has:`+t),null):(this._messageIDList.set(e.ID),e)}_handleMessageRevoked(e){let{OuterConstant:i,OuterEvent:{MESSAGE_REVOKED:t}}=this._core,{ToGroupId:n,MsgBody:{RevokeMsgList:s},RevokerInfo:{Revoker_Account:o,Reason:a=""}}=e,u=[];s.forEach(e=>{var{TinyId:e,MsgClientTime:t,Random:s,MsgSeq:r}=e,e={conversationID:""+i.CONV_GROUP+n,ID:e+`-${t}-`+s,revoker:o,revokeReason:a,revokerInfo:{userID:o,nick:"",avatar:""},sequence:r};u.push(e)}),0!==u.length&&this._emitEvent({name:t,data:u})}_onLiveCustomData(e){var t=this._core["OuterEvent"]["ROOM_CUSTOM_DATA_RECEIVED"],{ToGroupId:e,MsgSeq:s,MsgTimeStamp:r,MsgBody:i}=e,i=(null==i?void 0:i.MsgContent)||"";this._emitEvent({name:t,data:i}),console.log(this._name+`._onLiveCustomData groupID:${e} sequence:${s} time:${r} data:`+i)}_onGroupDismissed(e){this._avChatRoomHandler.reset(e)}_checkMessageStacked(e){var t=e["length"];if(100<=t&&this._reportMessageStackedCount<5){let e=this._avChatRoomHandler.getJoinedGroups();this._core.ssoLog.info("MessageStacked",`count:${t} groupID:`+e.join(",")),this._reportMessageStackedCount+=1}}_emitEvent(e){this._core.notificationCenter.emitOuterEvent(e.name,e)}onBroadcastMessageReceived(s){var{message:{messageHelper:r},OuterEvent:{MESSAGE_RECEIVED:e}}=this._core,i=this._avChatRoomHandler.isPollingSimplifiedMessage(),n=[],o=s.length;for(let t=0;t<o;t++){let e=s[t];i&&(e=ma(e));var a=r.parseServerGroupMessage(e);Object.values(ca).includes(e.Event)?((a=this._createMessage(a)).isBroadcastMessage=!0,this._broadcastMessageIDMap.has(a.ID)||(n.push(a),this._broadcastMessageIDMap.set(a.ID,1))):console.warn(this._name+".onBroadcastMessageReceived unknown event:"+e.Event)}0<n.length&&this._emitEvent({name:e,data:n})}_updateLocalOnlineMemberCountFromTips(t){var s=this._core["utils"]["isEmpty"],{ToGroupId:t,MsgBody:{OnlineMemberInfo:r}}=t;if(!s(r)){var{OnlineMemberNum:r=0,ExpireTime:i=60}=r,n=Date.now();let e=this._avChatRoomHandler.getLocalOnlineMemberCount(t);s(e)?e={lastReqTime:0,lastSyncTime:0,latestUpdateTime:n,memberCount:r,expireTime:i}:(e.latestUpdateTime=n,e.memberCount=r),this._avChatRoomHandler.updateLocalOnlineMemberCount(t,e)}}reset(){this._reportMessageStackedCount=0,this._sequenceList.clear(),this._messageIDList.clear(),this._broadcastMessageIDMap.clear()}};let fa=e=>{var{store:t}=la["core"];return(t.get("cloudConfig")||{})[e]},Ia=e=>{var{utils:{isUndefined:t}}=la["core"];return!t(e)},Ea=()=>{var e=fa("polling_interval");return Ia(e)?parseInt(e,10):300},Ca=()=>{var e=fa("polling_simplified_msg");return Ia(e)?parseInt(e,10):0};var Sa=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,va.init(e,this),e.ssoLog.debug("AVChatRoomHandler.init")}onAVChatRoomSystemNotification(e){var t=this._core["OuterConstant"]["GRP_AVCHATROOM"],{GroupTips:s=[]}=e;for(let e=0;e<s.length;e++){var{MsgBody:r,GroupInfo:{GroupId:i,GroupType:n}}=s[e],r=Object.values(da).includes(r.ReportType);n===t&&r&&this.reset(i)}}getCurrentPollingInterval(e){return this._pollingIntervalMap.get(e)||Ea()}isPollingSimplifiedMessage(){return 0!==Ca()}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(u){return I(this,void 0,void 0,function*(){var{utils:{isUndefined:e},OuterConstant:{CONV_GROUP:t},apiMap:{getConversationProfile:s},OuterConstant:r}=this._core,{longPollingKey:i,group:n,historyMessageList:o=[]}=u,a=n["groupID"];return yield this._preCheck(n),this._joinedGroupMap.set(a,n),this._parentPlugin.groupDataHandler.updateLocalGroup([n]),this._parentPlugin.groupDataHandler.emitGroupListUpdate(),s(""+t+a),0<o.length&&va.onMessageReceived(a,o,!0),e(i)?{status:r.JOIN_STATUS_SUCCESS,group:n}:this.startMessageLongPolling(u)})}_preCheck(n){return I(this,void 0,void 0,function*(){var{common:t,OuterConstant:e,helper:s,apiMap:{quitGroup:r},ssoLog:i}=this._core;if(t.isUnlimitedAVChatRoom()){if(this._pollingInstanceMap.size>(t=fa("polling_count_limit"),Ia(t)&&0<t?parseInt(t,10):20))throw new s.ChatError({code:2688,message:"the count of longPolling exceeds the max limit"})}else if(0!==this._joinedAVChatRoomCount()&&n.type!==e.GRP_LIVE){var[t,s]=this._joinedGroupMap.entries().next().value;if(s.selfInfo.role===e.GRP_MBR_ROLE_OWNER)this._parentPlugin.groupDataHandler.deleteLocalGroup(t);else try{yield r(t)}catch(e){i.debug("quitGroup",this._name+`._preCheck quitGroup failed, groupID:${t} info:`,e)}this.reset(t)}})}startMessageLongPolling(e){var t=this._core["OuterConstant"],{longPollingKey:e,startSequence:s=1,group:r}=e,i=r["groupID"];return this._pollingRequestInfoMap.set(i,{longPollingKey:e,startSequence:s}),this._pollingIntervalMap.set(i,Ea()),this._startPolling(i),this._reportLongPollingCount(),{status:t.JOIN_STATUS_SUCCESS,group:r}}_startPolling(t){if(this._core.ssoLog.debug("_startPolling",this._name+"._startPolling groupID:"+t),this._pollingInstanceMap.has(t)){let e=this._pollingInstanceMap.get(t);void((null==e?void 0:e.isRunning())||null==e||e.start())}else{let e=new pa({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:Ca()}:{longPollingKey:t,startSequence:s,simplifiedMessage:Ca()}}_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:i=[],RspBroadcastMsgList:n=[]}=e;if(e&&s&&this._pollingRequestInfoMap.set(t,{longPollingKey:e,startSequence:s}),r&&r>this._startBroadcastSequence&&(this._startBroadcastSequence=r),0<i.length)0!==this._getPollingNoMessageCount(t)&&(this._updatePollingNoMessageCount(t,0),this._pollingIntervalMap.set(t,Ea())),va.onMessageReceived(t,i);else{e=this._getPollingNoMessageCount(t);if(this._updatePollingNoMessageCount(t,e+=1),e===(s=fa("polling_no_msg_count"),Ia(s)?parseInt(s,10):20)){let e=Ea()+(r=fa("polling_interval_plus"),Ia(r)?parseInt(r,10):2e3);this._pollingIntervalMap.set(t,e)}}0<n.length&&va.onBroadcastMessageReceived(n)}_handleFailure(e,t){var{ssoLog:s,utils:{safeStringify:r}}=this._core;s.warn("polling",this._name+`._handleFailure groupID:${e} error: `+r(t))}_joinedAVChatRoomCount(){let t=this._core["OuterConstant"],e=[];return(e=0<this._joinedGroupMap.size?this.getJoinedGroups().filter(e=>e.type===t.GRP_AVCHATROOM):e).length}_hasJoinedAVChatRoom(e){return this._joinedGroupMap.has(e)}getJoinedGroups(){return[...this._joinedGroupMap.values()]}updateLocalLiveGroup(e,t){this._joinedGroupMap.set(e,t),this._parentPlugin.groupDataHandler.updateLocalGroup([t])}handleLiveHistoryMessages(e,t){va.onMessageReceived(e,t,!0)}isOverFrequencyLimit(e){var t,s,r,i;return!this._membersReqInfoMap.has(e)||({startTime:t,requestCount:s}=this._membersReqInfoMap.get(e),{interval:r,count:i}=(()=>{var e=fa("av_members_freq_limit");if(Ia(e)){var{interval:e,count:t}=JSON.parse(e);if(0<t&&0<e)return{interval:e,count:t}}return{interval:30,count:4}})(),Date.now()-t>1e3*r)?(this._membersReqInfoMap.set(e,{startTime:Date.now(),requestCount:1}),!1):(this._membersReqInfoMap.set(e,{startTime:t,requestCount:s+=1}),i<s)}_stopPolling(e){var t,s;if(this._core.ssoLog.debug("_stopPolling",this._name+"._stopPolling groupID:"+e),e)({appStore:{conversationStore:s},OuterConstant:{CONV_GROUP:t}}=this._core),s.deleteConversation(""+t+e),null!=(s=this._pollingInstanceMap.get(e))&&s.stop(),this._parentPlugin.groupDataHandler.deleteLocalGroup(e),this._pollingInstanceMap.delete(e),this._pollingRequestInfoMap.delete(e),this._joinedGroupMap.delete(e),this._onlineMemberCountMap.delete(e),this._pollingIntervalMap.delete(e),this._pollingNoMessageCountMap.delete(e),this._membersReqInfoMap.delete(e);else{for(let e of this._pollingInstanceMap.values())null!=e&&e.stop();this._pollingInstanceMap.clear(),this._pollingRequestInfoMap.clear(),this._joinedGroupMap.clear(),this._onlineMemberCountMap.clear(),this._pollingIntervalMap.clear(),this._pollingNoMessageCountMap.clear(),this._membersReqInfoMap.clear()}}_updatePollingNoMessageCount(e,t){this._pollingNoMessageCountMap.set(e,t)}_getPollingNoMessageCount(e){return this._pollingNoMessageCountMap.get(e)||0}_reportLongPollingCount(){var o=this._joinedGroupMap.size;if(1<o){let{common:e,OuterConstant:s,ssoLog:t}=this._core,r=e.isUnlimitedAVChatRoom()?1:0,i=[],n=[];this._joinedGroupMap.values().forEach(({groupID:e,type:t})=>{(t===s.GRP_LIVE?n:i).push(e)}),t.info("longPollingCount",String(o),{moreMessage:`av:${i.join(",")} live:${n.join(",")} code: `+r,eventType:29})}}reset(e){this._stopPolling(e),this._startBroadcastSequence=1,va.reset()}},Ma=new class{init(e,t){this._core=e,this._parentPlugin=t;e=e.helper;e.registerApi({apiName:"joinGroup",context:this,matcher:()=>0<t.getInstalledSubPlugins().length})}joinGroup(i){return I(this,void 0,void 0,function*(){var e=this._core["OuterConstant"],t=yield this._parentPlugin.groupAction.joinGroup(i),{status:s,group:{type:r}}=t["data"];return r!==e.GRP_AVCHATROOM||s===e.JOIN_STATUS_ALREADY_IN_GROUP?t:Sa.handleJoinGroupResult(t.data)})}},ya=new class{init(e,t){this._core=e,this._parentPlugin=t;e=e.helper;e.registerApi({apiName:"quitGroup",context:this,matcher:()=>0<t.getInstalledSubPlugins().length})}quitGroup(r){return I(this,void 0,void 0,function*(){var e=this._core["OuterConstant"],t=yield this._parentPlugin.groupAction.quitGroup(r),{type:s}=t["data"];return s===e.GRP_AVCHATROOM&&Sa.reset(r),t})}},Ta=new class{init(e,t){this._core=e,this._parentPlugin=t;e=e.helper;e.registerApi({apiName:"dismissGroup",context:this,matcher:()=>0<t.getInstalledSubPlugins().length})}dismissGroup(r){return I(this,void 0,void 0,function*(){var e=this._core["OuterConstant"],t=yield this._parentPlugin.groupAction.dismissGroup(r),{type:s}=t["data"];return s===e.GRP_AVCHATROOM&&Sa.reset(r),t})}},Aa=new class{constructor(){this._name="GetAVChatRoomMemberList"}init(e,t){this._core=e,this._parentPlugin=t;e=e.helper;e.registerApi({apiName:"getGroupMemberList",context:this,matcher:()=>0<t.getInstalledSubPlugins().length})}getGroupMemberList(i){return I(this,void 0,void 0,function*(){var{appStore:{groupStore:e},helper:t,OuterConstant:s}=this._core,r=i["groupID"],e=e.getGroup(r);if((null==e?void 0:e.type)===s.GRP_AVCHATROOM&&t.checkBusinessCapabilityBits("AV_MBR_LIST")){if(Sa.isOverFrequencyLimit(r))throw{code:2996,message:"Over frequency limit: get_members-"+r};return this._getGroupMemberList(i)}return this._parentPlugin.groupMember.getGroupMemberList(i)})}_getGroupMemberList(n){return I(this,void 0,void 0,function*(){let i="_getGroupMemberList",t=this._core["helper"];try{let e=yield function(s,r){return I(this,void 0,void 0,function*(){var{groupID:e,offset:t=0}=s;return r.common.buildAndSendPacket({servcmd:"group_open_avchatroom_http_svc.get_members",data:{GroupId:e,Timestamp:t}})})}(n,this._core),{MemberList:t=[],NextTimestamp:s=0}=e||{},r=this._handleMemberList(t);return console.log(`${this._name}.${i} ok, groupID:${n.groupID} count:${r.length} nextOffset:`+s),{code:0,data:{memberList:r,offset:s}}}catch(e){var s=new t.ChatError({functionName:i,code:null==e?void 0:e.errorCode,message:null==e?void 0:e.errorInfo});throw console.error(this._name+`.${i} fail:`,s),s}})}_handleMemberList(e){return e.map(e=>{var{Member_Account:e,NickName:t="",Avatar:s="",Remark:r="",JoinTime:i=0,Marks:n=[]}=e;return{userID:e,nick:t,avatar:s,remark:r,joinTime:i,marks:n,isOnline:!0}})}},Oa=new class{constructor(){this._name="GetAVChatRoomOnlineMemberCount"}init(e,t){this._core=e,this._parentPlugin=t;e=e.helper;e.registerApi({apiName:"getGroupOnlineMemberCount",context:this,matcher:()=>0<t.getInstalledSubPlugins().length})}getGroupOnlineMemberCount(s){return I(this,void 0,void 0,function*(){var{appStore:{groupStore:e},OuterConstant:t}=this._core,e=e.getGroup(s);return e?e.type===t.GRP_AVCHATROOM?this._getOnlineMemberCount(s):this._parentPlugin.groupAction.getGroupOnlineMemberCount(s):{code:0,data:{memberCount:0}}})}_getOnlineMemberCount(r){return I(this,void 0,void 0,function*(){let t="_getOnlineMemberCount",{isEmpty:e}=this._core["utils"],s=Sa.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=Sa.getLocalOnlineMemberCount(e),t=Date.now(),s=t-e.lastSyncTime>1e3*e.expireTime,r=1e4<t-e.latestUpdateTime,t=3e3<t-e.lastReqTime;return s&&r&&t}_getOnlineMemberCountFromServer(n){return I(this,void 0,void 0,function*(){let t="_getOnlineMemberCountFromServer";try{let e=yield function(e,t){return I(this,void 0,void 0,function*(){return t.common.buildAndSendPacket({servcmd:"group_open_http_svc.get_online_member_num",data:{GroupId:e}})})}(n,this._core),{OnlineMemberNum:t=0,ExpireTime:s=60}=e||{},r=Date.now(),i={lastSyncTime:r,latestUpdateTime:r,lastReqTime:r,memberCount:t,expireTime:s};return Sa.updateLocalOnlineMemberCount(n,i),{memberCount:t}}catch(e){var s=new this._core.helper.ChatError({functionName:t,code:null==e?void 0:e.errorCode,message:null==e?void 0:e.errorInfo});throw console.error(`${this._name}.${t} fail:`,s),s}})}},Da=new class{constructor(){this._name="DeleteAVChatRoomMember"}init(e,t){this._core=e,this._parentPlugin=t;e=e.helper;e.registerApi({apiName:"deleteGroupMember",context:this,matcher:()=>0<t.getInstalledSubPlugins().length})}deleteGroupMember(o){return I(this,void 0,void 0,function*(){var e="deleteGroupMember",{appStore:{groupStore:t},utils:{isUndefined:s},helper:r,OuterConstant:i}=this._core,n=o["groupID"],t=t.getGroup(n);if(s(t))throw new r.ChatError({functionName:e,code:2603});if(t.type!==i.GRP_AVCHATROOM)return this._parentPlugin.groupMember.deleteGroupMember(o);if(r.checkBusinessCapabilityBits("AV_BAN_MBR"))return this._deleteGroupMember(o);throw new r.ChatError({functionName:e,code:3122})})}_deleteGroupMember(a){return I(this,void 0,void 0,function*(){var t="_deleteGroupMember",{appStore:{groupStore:e},helper:s,ssoLog:r}=this._core,{groupID:i,duration:n=0,userIDList:o}=a;if(0===n)throw new s.ChatError({functionName:t,code:2686});try{return yield function(i,n){return I(this,void 0,void 0,function*(){var{groupID:e,userIDList:t,duration:s,reason:r}=i;return n.common.buildAndSendPacket({servcmd:"group_open_http_svc.ban_group_member",data:{GroupId:e,Members_Account:t,Duration:s,Description:r}})})}(a,this._core),r.debug(t,this._name+`.${t} ok, groupID:`+i),{code:0,data:{group:e.getGroup(i),userIDList:o}}}catch(e){throw new s.ChatError({functionName:t,code:null==e?void 0:e.errorCode,message:null==e?void 0:e.errorInfo})}})}},Ra=new class{constructor(){this._name="MarkAVChatRoomMember"}init(e){e=(this._core=e).helper;e.registerApi({apiName:"markGroupMemberList",context:this})}markGroupMemberList(e){return I(this,void 0,void 0,function*(){var i="markGroupMemberList",{groupID:n,markType:o,enableMark:a,userIDList:u=[]}=e,l=this._generateRequestData(e);try{let e=yield function(r,i){return I(this,void 0,void 0,function*(){var{groupID:e,operationType:t,memberList:s}=r;return i.common.buildAndSendPacket({servcmd:"group_open_avchatroom_http_svc.modify_user_info",data:{GroupId:e,CommandType:t,MemberList:s}})})}(l,this._core),{MemberList:t=[]}=e||{},{successUserIDList:s,failureUserIDList:r}=this._handleResult(t,u);return{code:0,data:{successUserIDList:s,failureUserIDList:r},successLog:{message:`${this._name}.${i} ok, groupID:${n} markType:${o} enableMark:${a} success:${s.length} fail:`+r.length}}}catch(e){throw new this._core.helper.ChatError({functionName:i,code:null==e?void 0:e.errorCode,message:null==e?void 0:e.errorInfo})}})}_generateRequestData(e){let{groupID:t,markType:s,enableMark:r,userIDList:i=[]}=e,n=!0===r?1:2,o=[...i];return 500<o.length&&console.warn(this._name+"._generateRequestData, the length of userIDList cannot exceed 500"),{groupID:t,operationType:n,memberList:o.map(e=>({Member_Account:e,Marks:[s]}))}}_handleResult(e,t){let s=[],r=[];return e.length===t.length?s.push(...t):t.forEach(t=>{(e.find(e=>e.Member_Account===t)?s:r).push(t)}),{successUserIDList:s,failureUserIDList:r}}},La=new class{init(e,t){e.ssoLog.debug("AVChatRoomAction.init"),Ma.init(e,t),ya.init(e,t),Ta.init(e,t),Aa.init(e,t),Oa.init(e,t),Da.init(e,t),Ra.init(e)}},Na=new class{constructor(){this._name="LiveHandler"}init(e){var{helper:e,ssoLog:t}=this._core=e;e.registerExperimentalAPI("startMessageLongPolling",this),e.registerExperimentalAPI("stopMessageLongPolling",this),t.debug("LiveHandler.init")}startMessageLongPolling(e){var{common:t,utils:{isEmpty:s},OuterConstant:r,ssoLog:i}=this._core,{groupID:e,longPollingKey:n,longPollingSequence:o=1}=e;if(s(n))return i.warn("startMessageLongPolling",this._name+".startMessageLongPolling longPollingKey is empty."),Promise.resolve({});Sa.hasPollingInstance(e)&&this.stopMessageLongPolling({groupID:e});s=Sa.getJoinedLiveList(),t=t.isUnlimitedAVChatRoom(),!t&&0<s.length&&this.stopMessageLongPolling({groupID:s[0].groupID}),i.debug("startMessageLongPolling",this._name+`.startMessageLongPolling isUnlimited:${t} groupID:${e} longPollingKey:${n} longPollingSequence:`+o),s={groupID:e,type:r.GRP_LIVE};return Sa.updateLocalLiveGroup(e,s),this._getLiveHistoryMessages({groupID:e,longPollingKey:n,startSequence:o}),Sa.startMessageLongPolling({group:s,longPollingKey:n,startSequence:o})}stopMessageLongPolling(e){e=e.groupID;return Sa.reset(e),this._core.ssoLog.debug("stopMessageLongPolling",this._name+".stopMessageLongPolling ok, groupID:"+e),Promise.resolve({groupID:e})}_getLiveHistoryMessages(i){return I(this,void 0,void 0,function*(){var t=this._core["ssoLog"],s=i["groupID"];try{var e=yield function(r,i){return I(this,void 0,void 0,function*(){var{groupID:e,longPollingKey:t,startSequence:s}=r;return i.common.buildAndSendPacket({servcmd:"group_open_http_svc.get_huge_group_msg",data:{GroupId:e,LongPollingKey:t,PullPreSeq:s}})})}(i,this._core),{RspMsgList:r=[]}=e||{};t.debug("_getLiveHistoryMessages",this._name+`._getLiveHistoryMessages ok, groupID:${s} count:`+r.length),0<r.length&&Sa.handleLiveHistoryMessages(s,r)}catch(e){t.debug("_getLiveHistoryMessages",this._name+`._getLiveHistoryMessages failed, groupID:${s} info:`+e.message)}})}},ba=new class{constructor(){this.name="AVChatRoom"}install(e,t){this._core=e,la.init(e),Sa.init(e,t),La.init(e,t),Na.init(e);var{notificationCenter:t,InnerEvent:e}=e,s=t["InnerEventSubType"];t.subscribeInnerEvent(e.MESSAGE_PUSH,s.GROUP_SYSTEM_NOTIFICATION,this._onAVChatRoomSystemNotification,this),t.subscribeInnerEvent(e.LOGOUT,this._reset,this),t.subscribeInnerEvent(e.DESTROY,this._dispose,this)}_onAVChatRoomSystemNotification(e){Sa.onAVChatRoomSystemNotification(e)}_reset(){Sa.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 R="friend",Ga="Tag_SNS_IM_",Pa={GROUP:Ga+"Group",REMARK:Ga+"Remark",ADDSOURCE:Ga+"AddSource",ADDWORDING:Ga+"Wording",ADDTIME:Ga+"AddTime"},wa="Update_Type_Add",Ua="Update_Type_Delete",ka="remove",Fa=e=>void 0===e;function qa(e,t="ResultItem",s=e=>({userID:e.To_Account,resultCode:e.ResultCode,resultInfo:e.ResultInfo})){var{[t]:e=[],ActionStatus:t,ErrorCode:r,ErrorInfo:i,ErrorDisplay:n}=e;return{resultList:e.map(s),actionStatus:t,errorCode:r,errorInfo:i,errorDisplay:n}}let xa={[Pa.REMARK]:(e,t)=>{e.remark=t},[Pa.GROUP]:(e,t)=>{e.groupList=t?JSON.parse(JSON.stringify(t)):[]},[Pa.ADDSOURCE]:(e,t)=>{e.source=t},[Pa.ADDWORDING]:(e,t)=>{e.wording=t},[Pa.ADDTIME]:(e,t)=>{e.addTime=t}},Va=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}),xa[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=xa[t];null!=e&&e(this,s)})}};var Ba=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 I(this,void 0,void 0,function*(){var{appStore:{userStore:e},ssoLog:t,utils:{safeStringify:s}}=this._core,e=[...e.getFriendMap().values()];return t.debug("getFriendListFromCache",R+" getFriendListFromCache, data:"+s(e)),{code:0,data:e}})}syncFriendListFromServer(){return I(this,void 0,void 0,function*(){let a,{ssoLog:u,helper:t}=this._core;try{u.debug("syncFriendListFromServer",R+" syncFriendListFromServer");let e={From_Account:null==(a=this._core.store.get("login"))?void 0:a.userId,StartIndex:this._startIndex,StandardSequence:this._standardSequence,CustomSequence:this._customSequence},t=yield function(c,d){return I(this,void 0,void 0,function*(){var{UserDataItem:e=[],StandardSequence:t,CustomSequence:s,FriendNum:r,CompleteFlag:i,NextStartIndex:n,ActionStatus:o,ErrorCode:a,ErrorInfo:u,ErrorDisplay:l}=e=yield d.common.buildAndSendPacket({servcmd:"sns.friend_get",data:c});return{friendList:e.map(e=>{return{userID:e.To_Account,tagValueList:null==(e=e.ValueItem)?void 0:e.map(e=>({tag:e.Tag,value:e.Value}))}}),standardSequence:t,customSequence:s,friendNumber:r,completeFlag:i,nextStartIndex:n,actionStatus:o,errorCode:a,errorInfo:u,errorDisplay:l}})}(e,this._core),{friendList:s,nextStartIndex:r,standardSequence:i,customSequence:n,completeFlag:o}=t;this._startIndex=r,this._standardSequence=i,this._customSequence=n,this._processFriendList(s),0===o?yield this.syncFriendListFromServer():(this._emitFriendListUpdated(),this._fetchFriendProfile()),u.debug("syncFriendListFromServer",R+" syncFriendListFromServer ok")}catch(a){let e=(a||{})["errorCode"];throw new t.ChatError({code:e})}})}getFriendProfile(u){return I(this,void 0,void 0,function*(){var t;try{let e=u["userIDList"];100<e.length&&(e=e.slice(0,100));var s,r,i,{friendUserIdList:n,unFriendUserIdList:o}=this.partitionByIsFriend(e),a=this._createNonFriendErrorList(o);return 0===n.length?{code:0,data:{friendList:[],failureUserIDList:a}}:(s=(yield function(n,o){return I(this,void 0,void 0,function*(){var{InfoItem:e=[],ActionStatus:t,ErrorCode:s,ErrorInfo:r,ErrorDisplay:i}=e=yield o.common.buildAndSendPacket({servcmd:"sns.friend_get_specified",data:n});return{friendProfileList:e.map(e=>{return{userID:e.To_Account,resultCode:e.ResultCode,resultInfo:e.ResultInfo,relation:e.Relation,standardSequence:e.StandardSequence,customSequence:e.CustomSequence,profileItem:(null==(e=e.SnsProfileItem)?void 0:e.map(e=>({tag:e.Tag,value:e.Value})))||[]}}),actionStatus:t,errorCode:s,errorInfo:r,errorDisplay:i}})}({From_Account:null==(t=this._core.store.get("login"))?void 0:t.userId,To_Account:n},this._core))||{},{successProfiles:r,failedProfiles:i}=this._processFriendProfileResponse(s),{code:0,data:{friendList:r,failureUserIDList:[...i,...a]}})}catch(e){let t=(e||{})["errorCode"];throw new this._core.helper.ChatError({code:t})}})}addFriend(g){return I(this,void 0,void 0,function*(){var e,{helper:s,store:t,ssoLog:r}=this._core;try{var{to:i,source:n,type:o,wording:a,remark:u,groupName:l}=g,c=yield function(e,t){return I(this,void 0,void 0,function*(){return qa(yield t.common.buildAndSendPacket({servcmd:"sns.friend_add",data:e}))})}({From_Account:null==(e=t.get("login"))?void 0:e.userId,AddFriendItem:[{To_Account:i,AddSource:n,AddWording:a,GroupName:l,Remark:u}],AddType:o},this._core),{resultList:d=[]}=c,{userID:p,resultCode:h}=d[0];if(0===h)return r.debug("addFriend",R+" addFriend ok"),{code:0,data:{userID:p}};if(30539===h)return r.debug("addFriend",R+" addFriend wait for the other party to agree"),{code:0,data:{userID:p,code:h,message:"wait for the other party to agree"}};throw new s.ChatError({functionName:"addFriend",code:h})}catch(e){let t=(e||{})["errorCode"];throw new s.ChatError({code:t})}})}deleteFriend(p){return I(this,void 0,void 0,function*(){var s,{store:r,ssoLog:i,helper:n}=this._core;try{let{userIDList:e,type:t}=p;var o,a,u,l=null==(s=r.get("login"))?void 0:s.userId,{friendUserIdList:c,unFriendUserIdList:d}=(1e3<e.length&&(i.info("deleteFriend",R+" deleteFriend the length of userIDList cannot exceed:1000"),e=e.slice(0,100)),this.partitionByIsFriend(e));return 0===c.length?{code:0,data:{friendList:[],failureUserIDList:this._createNonFriendErrorList(d)}}:(o=yield function(e,t){return I(this,void 0,void 0,function*(){return qa(yield t.common.buildAndSendPacket({servcmd:"sns.friend_delete",data:e}))})}({From_Account:l,To_Account:c,DeleteType:t},this._core),{successUserIDList:a,failureUserIDList:u}=this._processOperationResult({resultList:o.resultList,includeRelation:!1}),{code:0,data:{successUserIDList:a,failureUserIDList:u}})}catch(e){let t=(e||{})["errorCode"];throw new n.ChatError({code:t})}})}updateFriend(p){return I(this,void 0,void 0,function*(){var e,{helper:s,store:t,appStore:{userStore:r}}=this._core;try{var{userID:i,remark:n,friendCustomField:o}=p,a=null==(e=t.get("login"))?void 0:e.userId;if(!r.getFriendMap().has(i))throw new s.ChatError({functionName:"updateFriend",code:2700});var u=(yield function(e,t){return I(this,void 0,void 0,function*(){return qa(yield t.common.buildAndSendPacket({servcmd:"sns.friend_update",data:e}),"ResultItem",e=>({to:e.To_Account,resultCode:e.ResultCode,resultInfo:e.ResultInfo}))})}({From_Account:a,UpdateItem:[{To_Account:i,SnsItem:this._buildSnsItemList(n,o)}]},this._core))["resultList"],{to:l,resultCode:c,resultInfo:d}=u[0];if(Fa(c)||0===c)return{code:0,data:this._updateLocalFriend({userID:l,remark:n,friendCustomField:o})};throw new s.ChatError({functionName:"updateFriend",code:c,message:d})}catch(e){let t=(e||{})["errorCode"];throw new s.ChatError({code:t})}})}checkFriend(c){return I(this,void 0,void 0,function*(){var a;let{OuterConstant:u,store:l,helper:s}=this._core;try{let{userIDList:e,type:t}=c,s=null==(a=l.get("login"))?void 0:a.userId,r={From_Account:s,To_Account:e,CheckType:t===u.SNS_CHECK_TYPE_SINGLE?t:u.SNS_CHECK_TYPE_BOTH},i=yield function(e,t){return I(this,void 0,void 0,function*(){return qa(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}))})}(r,this._core),{successUserIDList:n=[],failureUserIDList:o=[]}=this._processOperationResult({resultList:i.resultList,includeRelation:!0});return{code:0,data:{successUserIDList:n,failureUserIDList:o}}}catch(e){let t=(e||{})["errorCode"];throw new s.ChatError({code:t})}})}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(n){return I(this,void 0,void 0,function*(){var{ssoLog:e,utils:{safeStringify:t}}=this._core;e.debug("updateFriendList",R+" updateFriendList data:"+t(n));let s=this._core.appStore["userStore"],{addedFriendList:r=[],removedFriendList:i=[]}=n;0<r.length&&(r.forEach(e=>{var t=new Va({userID:e,core:this._core});s.getFriendMap().set(e,t)}),yield this.getFriendProfile({userIDList:r}),this._emitFriendListUpdated()),0<i.length&&(i.forEach(e=>{s.getFriendMap().delete(e)}),this._emitFriendListUpdated())})}updateFriendInfo(e){var{ssoLog:t,utils:{safeStringify:s}}=this._core;t.debug("updateFriendList",R+" updateFriendInfo data:"+s(e));let{appStore:{userStore:r,conversationStore:i},utils:{isEmpty:n}}=this._core,{userID:o,tagValueList:a}=e[0]||{},u=r.getFriend(o);if(!n(a)&&u){let r=a.map(e=>({tag:e.BytesTag,value:e.BytesValue}));r.forEach(e=>{var{tag:e,value:t}=e,s=null==(s=i.getConversation("C2C"+o))?void 0:s.remark;e===Pa.REMARK&&t!==s&&i.updateConversation("C2C"+o,{remark:t}),u.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 Va({userID:e,tagValueList:t,core:this._core}),s.getFriendMap().set(e,t))})}_isInvalidFriend(e){return"@TLS#NOT_FOUND"===e||""===e}_fetchFriendProfile(){return I(this,void 0,void 0,function*(){let{appStore:{userStore:n},user:{userProfile:o},ssoLog:e}=this._core,a=(e.debug("_fetchFriendProfile",R+" _fetchFriendProfile"),[...n.getFriendMap().keys()]),t=Math.ceil(a.length/100);for(let i=0;i<t;i++){let e=100*i,t=Math.min(100+e,a.length),s=a.slice(e,t),r=yield null==o?void 0:o.getUserProfile({userIDList:s});r&&r.data&&r.data.forEach(e=>{var t=n.getFriend(e.userID);t&&(t.profile=e)}),this._emitFriendListUpdated()}})}_emitFriendListUpdated(){var{notificationCenter:e,OuterEvent:t,appStore:{userStore:s}}=this._core,s=Array.from(s.getFriendMap().values());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 i=!1;return e.forEach(({key:t,value:e})=>{var s=r.find(e=>e.key===t);s?s.value!==e&&(s.value=e,i=!0):(r.push({key:t,value:e}),i=!0)}),i}_updateLocalFriend(e){var t=this._core.appStore["userStore"],{userID:e,remark:s,friendCustomField:r}=e,t=t.getFriend(e);if(t)return Fa(s)||(t.remark=s),Array.isArray(r)&&0<r.length&&this._updateCustomField(t.friendCustomField,r),this._emitFriendListUpdated(),t}_processOperationResult(e){let{resultList:t,includeRelation:i=!1}=e,s=this._core.utils["isEmpty"],n=[],o=[];return Array.isArray(t)&&!s(t)&&t.forEach(e=>{var{userID:t,relation:s,resultCode:e,resultInfo:r}=e;if(Fa(e)||0===e){let e={userID:t};i&&(e.code=0,e.relation=s),n.push(e)}else o.push({userID:t,code:e,message:r})}),{successUserIDList:n,failureUserIDList:o}}_createNonFriendErrorList(e){return e.map(e=>({userID:e,code:2700,message:"The specified userID is not my friend"}))}_buildSnsItemList(e,t){let s=[];return Fa(e)||s.push({Tag:Pa.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,i=this._core.appStore["userStore"],n=[],o=[];return t.forEach(e=>{var{userID:t,resultCode:e,resultInfo:s,profileItem:r}=e;if(0===e){let e=new Va({userID:t,tagValueList:r,core:this._core});n.push(e),i.getFriendMap().set(t,e)}else o.push({userID:t,code:e,message:s})}),{successProfiles:n,failedProfiles:o}}partitionByIsFriend(e){let s=[],r=[];return e.forEach(e=>{var t=this._core.appStore["userStore"];(t.getFriendMap().has(e)?s:r).push(e)}),{friendUserIdList:s,unFriendUserIdList:r}}isMyFriend(e){var t=this._core.appStore["userStore"];return t.getFriendMap().has(e)}},ja=new class{init(e){this.core=e}};function Ka(s){return I(this,void 0,void 0,function*(){var{store:e,common:t}=ja.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 Ya(yield t.buildAndSendPacket({servcmd:"sns.friend_response",data:e}))})}function Wa(s){return I(this,void 0,void 0,function*(){var{store:e,common:t}=ja.core,e={From_Account:null==(e=e.get("login"))?void 0:e.userId,ResponseFriendItem:[{To_Account:s.userID,ResponseAction:"Response_Action_Reject"}]};return Ya(yield t.buildAndSendPacket({servcmd:"sns.friend_response",data:e}))})}function Ha(s){return I(this,void 0,void 0,function*(){var{store:e,common:t}=ja.core,e={From_Account:null==(e=e.get("login"))?void 0:e.userId,To_Account:[s.userID],PendencyType:s.type};return Ya(yield t.buildAndSendPacket({servcmd:"sns.pendency_delete",data:e}))})}function Ya(e){var{ResultItem:e=[],ActionStatus:t,ErrorCode:s,ErrorInfo:r,ErrorDisplay:i}=e;return{resultList:e.map(e=>({userID:e.To_Account,resultCode:e.ResultCode,resultInfo:e.ResultInfo})),actionStatus:t,errorCode:s,errorInfo:r,errorDisplay:i}}var $a=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 I(this,void 0,void 0,function*(){var{ssoLog:e,utils:{safeStringify:t}}=this._core,s=[...this._friendApplicationMap.values()];return e.debug("getFriendApplicationListFromCache",R+" getFriendApplicationListFromCache friendApplicationList:"+t(s)),{code:0,data:{friendApplicationList:s,unreadCount:this._unreadCount}}})}syncFriendApplicationListFromServer(){return I(this,void 0,void 0,function*(){let{ssoLog:e,utils:{safeStringify:t}}=this._core,s="syncFriendApplicationListFromServer";try{let e=yield function(u){return I(this,void 0,void 0,function*(){var{store:e,OuterConstant:t,common:s}=ja.core,e={From_Account:null==(e=e.get("login"))?void 0:e.userId,PendencyType:t.SNS_APPLICATION_TYPE_BOTH,MaxLimited:100,StartTime:u.startTime,LastSequence:u.currentSequence},{PendencyItem:t=[],StartTime:s,UnreadPendencyCount:e,CurrentSequence:r,ActionStatus:i,ErrorCode:n,ErrorInfo:o,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:i,errorCode:n,errorInfo:o,errorDisplay:a}})}({startTime:this._startTime,currentSequence:this._currentSequence}),{resultList:t,unreadCount:s,startTime:r,currentSequence:i}=e;this._startTime=r,this._currentSequence=i,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(t){var r=new this._core.helper.ChatError({functionName:s,code:null==t?void 0:t.errorCode,message:null==t?void 0:t.errorInfo});throw e.error("syncFriendApplicationListFromServer",R+` ${s} error:`,{error:r}),r}})}acceptFriendApplication(e){return I(this,void 0,void 0,function*(){return this._operationApplication({functionName:"acceptFriendApplication",options:e,protocolFunction:Ka})})}refuseFriendApplication(e){return I(this,void 0,void 0,function*(){return this._operationApplication({functionName:"refuseFriendApplication",options:e,protocolFunction:Wa})})}deleteFriendApplication(s){return I(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:Ha})})}_checkApplicationExists(e,t,s){if(!this._friendApplicationMap.has(e+"_"+t))throw new this._core.helper.ChatError({functionName:s,code:2716})}_operationApplication(e){return I(this,void 0,void 0,function*(){let{functionName:i,options:n,protocolFunction:o}=e;console.log(R+` ${i} options:`,n);try{let e=yield o(n),{resultList:t=[]}=e,{resultCode:s,resultInfo:r}=t[0];if(0===s)return console.log(R+` ${i} ok`),{code:0,data:{}};throw{errorCode:s,errorInfo:r}}catch(e){let t=new this._core.helper.ChatError({functionName:i,code:null==e?void 0:e.errorCode,message:null==e?void 0:e.errorInfo});throw console.error(R+` ${i} error:`,t),t}})}setFriendApplicationRead(){return I(this,void 0,void 0,function*(){try{return yield function(){return I(this,void 0,void 0,function*(){var{store:e,common:t}=ja.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(),{code:0,data:{}}}catch(e){throw new this._core.helper.ChatError({functionName:"setFriendApplicationRead",code:null==e?void 0:e.errorCode,message:null==e?void 0:e.errorInfo})}})}updateFriendApplicationList(e){var{from:e,addedApplicationList:t=[],removedApplicationList:s=[]}=e,r=this._core.utils["isEmpty"];r(t)||this.onApplicationAdded(t,e),r(s)||this.onApplicationDeleted()}onApplicationAdded(e,t){let s,{store:r,OuterConstant:i}=this._core,n=t===(null==(s=r.get("login"))?void 0:s.userId)?i.SNS_APPLICATION_SENT_BY_ME:i.SNS_APPLICATION_SENT_TO_ME;e.forEach(e=>{var t=e.userID+"_"+n;n!==i.SNS_APPLICATION_SENT_TO_ME||this._friendApplicationMap.has(t)||(this._unreadCount+=1),this._friendApplicationMap.set(t,this._createFriendApplication(Object.assign(Object.assign({},e),{type:n})))}),this._emitApplicationListUpdated()}onApplicationDeleted(){this._startTime=0,this._currentSequence=0,this.syncFriendApplicationListFromServer()}onApplicationRead(){this._unreadCount=0,this._emitApplicationListUpdated()}reset(){this._startTime=0,this._currentSequence=0,this._unreadCount=0,this._friendApplicationMap.clear()}dispose(){this.reset()}_createFriendApplication(e){return{userID:e.userID||"",nick:e.nick||"",avatar:e.avatar||"",time:e.time||0,source:e.source||"",wording:e.wording||"",type:e.type||""}}_emitApplicationListUpdated(){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 za(r){return I(this,void 0,void 0,function*(){var e=ja.core["common"],{name:t,userIDList:s}=r,s=Qa(s,wa),t={From_Account:e.getCurrentUserID(),GroupOldName:t,UpdateGroupItem:s};return Xa(yield e.buildAndSendPacket({servcmd:"sns.group_update",data:t}),e=>({userID:e.To_Account,updateType:e.UpdateType,resultCode:e.ResultCode,resultInfo:e.ResultInfo}))})}function Ja(r){return I(this,void 0,void 0,function*(){var e=ja.core["common"],{name:t,userIDList:s}=r,s=Qa(s,Ua),t={From_Account:e.getCurrentUserID(),GroupOldName:t,UpdateGroupItem:s};return Xa(yield e.buildAndSendPacket({servcmd:"sns.group_update",data:t}),e=>({userID:e.To_Account,updateType:e.UpdateType,resultCode:e.ResultCode,resultInfo:e.ResultInfo}))})}function Qa(e,t){return e.filter(e=>Ba.isMyFriend(e)).map(e=>({To_Account:e,UpdateType:t}))}function Xa(e,t){var{CurrentSequence:e,ActionStatus:s,ErrorCode:r,ErrorInfo:i,ErrorDisplay:n,ResultItem:o=[]}=e,e={currentSequence:e,actionStatus:s,errorCode:r,errorInfo:i,errorDisplay:n};return t&&0<o.length?Object.assign(Object.assign({},e),{resultList:o.map(t)}):e}class Za{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 eu=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 I(this,void 0,void 0,function*(){var{ssoLog:e,utils:{safeStringify:t}}=this._core,s=[...this._friendGroupMap.values()];return e.debug(R+" getFriendGroupListFromCache, data:"+t(s)),{code:0,data:s}})}syncFriendGroupListFromServer(){return I(this,void 0,void 0,function*(){var e=this._core["ssoLog"],t="syncFriendGroupListFromServer";try{var s=yield function(){return I(this,void 0,void 0,function*(){var e=ja.core["common"],t={From_Account:e.getCurrentUserID(),LastSequence:0,NeedFriend:"Need_Friend_Type_Yes"};return Xa(yield e.buildAndSendPacket({servcmd:"sns.group_get",data:t}),e=>({name:e.GroupName,userIDList:e.To_Account||[],count:e.FriendNumber}))})}(),{resultList:r=[]}=s;this._core.helper.isEmpty(r)&&e.debug("syncFriendGroupListFromServer",R+` ${t} ok. count: 0`),r.forEach(e=>{var t=new Za(e);this._friendGroupMap.set(e.name,t)}),this._emitGroupListUpdated()}catch(e){this._handleError(t,e)}})}createFriendGroup(o){return I(this,void 0,void 0,function*(){var t="createFriendGroup";try{var e=o["name"],s=(this._checkGroupExist(t,e),yield function(r){return I(this,void 0,void 0,function*(){var{name:e,userIDList:t}=r,s=ja.core["common"],e={From_Account:s.getCurrentUserID(),GroupName:[e],To_Account:t};return Xa(yield s.buildAndSendPacket({servcmd:"sns.group_add",data:e}),e=>({userID:e.To_Account,resultCode:e.ResultCode,resultInfo:e.ResultInfo}))})}(o)),{successUserIDList:r,failureUserIDList:i}=this._parseCreateGroupResponse(s),n=new Za({name:e,userIDList:r});return this._friendGroupMap.set(e,n),this._emitGroupListUpdated(),{code:0,data:{friendGroup:n,failureUserIDList:i}}}catch(e){this._handleError(t,e)}})}deleteFriendGroup(r){return I(this,void 0,void 0,function*(){var t="deleteFriendGroup";try{var e=r["name"],s=(this._checkGroupNotExist(t,e),yield function(s){return I(this,void 0,void 0,function*(){var e=ja.core["common"],t={From_Account:e.getCurrentUserID(),GroupName:[s.name]};return Xa(yield e.buildAndSendPacket({servcmd:"sns.group_delete",data:t}))})}(r),this._friendGroupMap.get(e));return s&&(this._updateFriendGroup({name:e,userIDList:s.userIDList,action:ka}),this._friendGroupMap.delete(e)),this._emitGroupListUpdated(),{code:0,data:s}}catch(e){this._handleError(t,e)}})}addToFriendGroup(e){return I(this,void 0,void 0,function*(){return this._updateFriendGroupMember({functionName:"addToFriendGroup",params:e,protocolFunction:za})})}removeFromFriendGroup(e){return I(this,void 0,void 0,function*(){return this._updateFriendGroupMember({functionName:"removeFromFriendGroup",params:e,protocolFunction:Ja})})}renameFriendGroup(i){return I(this,void 0,void 0,function*(){var t="renameFriendGroup";try{var{oldName:e,newName:s}=i,r=(this._checkGroupNotExist(t,e),this._checkGroupExist(t,s),yield function(r){return I(this,void 0,void 0,function*(){var e=ja.core["common"],{oldName:t,newName:s}=r,t={From_Account:e.getCurrentUserID(),GroupOldName:t,GroupNewName:s};return Xa(yield e.buildAndSendPacket({servcmd:"sns.group_update",data:t}))})}(i),this._updateGroupNameInCache(e,s));return r&&this._updateFriendGroup({name:e,userIDList:r.userIDList,action:"rename",newName:s}),this._emitGroupListUpdated(),{code:0,data:r}}catch(e){this._handleError(t,e)}})}_updateFriendGroupMember(e){return I(this,void 0,void 0,function*(){var{functionName:t,params:s,protocolFunction:r}=e;try{let e=s["name"];this._checkGroupNotExist(t,e);var i=yield r(s),{friendGroup:n,failureUserIDList:o}=this._parseUpdateFriendGroupResponse(e,i);return this._emitGroupListUpdated(),{code:0,data:{friendGroup:n,failureUserIDList:o}}}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=[],i=[];return t.forEach(({userID:e,resultCode:t,resultInfo:s})=>{Fa(t)||0===t?r.push(e):i.push({userID:e,code:t,message:s})}),{successUserIDList:r,failureUserIDList:i}}_parseUpdateFriendGroupResponse(t,e){let{resultList:s=[]}=e,r=this._friendGroupMap.get(t),i=[],n=[],o=[];return s.forEach(e=>{0===e.resultCode?r&&(e.updateType===wa?this._addFriendToGroup(t,e.userID,r,n):e.updateType===Ua&&this._removeFriendFromGroup(t,e.userID,r,o)):i.push({userID:e.userID,code:e.resultCode,message:e.resultInfo})}),{friendGroup:r,failureUserIDList:i}}_addFriendToGroup(e,t,s,r){s.addToUserIDList(t),r.push(t),this._updateFriendGroup({name:e,userIDList:r,action:"add"})}_removeFriendFromGroup(e,t,s,r){s.removeFromUserIDList(t),r.push(t),this._updateFriendGroup({name:e,userIDList:r,action:ka})}_emitGroupListUpdated(){var{notificationCenter:e,OuterEvent:t}=this._core,s=[...this._friendGroupMap.values()];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:2711})}_checkGroupExist(e,t){if(this._friendGroupMap.has(t))throw new this._core.helper.ChatError({functionName:e,code:2710})}_updateFriendGroup(e){let{name:r,userIDList:t,action:i,newName:n}=e,o=this._core.appStore["userStore"];r&&!this._core.utils.isEmpty(t)&&t.forEach(e=>{var t=o.getFriend(e);if(t){var s=t["groupList"];switch(i){case"add":-1===s.indexOf(r)&&(s.push(r),t.count=s.length);break;case ka:{let e=s.indexOf(r);-1<e&&(s.splice(e,1),t.count=s.length);break}case"rename":if(n){let e=s.indexOf(r);-1!==e&&(s[e]=n)}}}})}_handleError(e,t){throw new this._core.helper.ChatError({functionName:e,code:null==t?void 0:t.errorCode,message:null==t?void 0:t.errorInfo})}reset(){this._friendGroupMap.clear()}dispose(){this.reset()}};function tu(e){return e&&0!==e.length?e.map(e=>({userID:e.To_Account,addBlackTimeStamp:e.AddBlackTimeStamp})):[]}var su=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 I(this,void 0,void 0,function*(){return{code:0,data:Array.from(this._blacklistMap.keys())}})}syncBlacklistFromServer(){return I(this,void 0,void 0,function*(){try{this._core.ssoLog.debug(R+" syncBlacklistFromServer");var e=yield function(r,i){return I(this,void 0,void 0,function*(){var{helper:e,channel:t}=i,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:tu(t),startIndex:e}})}({From_Account:this._core.common.getCurrentUserID(),MaxLimited:100,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,e}})}addToBlacklist(i){return I(this,void 0,void 0,function*(){let t=this._core["helper"];try{let e=this._preprocessBlacklist(i),t={From_Account:this._core.common.getCurrentUserID(),To_Account:e},s=yield function(r,i){return I(this,void 0,void 0,function*(){var{helper:e,channel:t}=i,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:tu(t)}})}(t,this._core),{blackList:r=[]}=s;return this._addBlacklistMap(r),this._emitBlackListUpdated(),{code:0,data:Array.from(this._blacklistMap.keys())}}catch(e){var s=(e||{})["errorCode"];throw new t.ChatError({code:s})}})}removeFromBlacklist(r){return I(this,void 0,void 0,function*(){let t=this._core["helper"];try{let e={From_Account:this._core.common.getCurrentUserID(),To_Account:r.userIDList},t=yield function(r,i){return I(this,void 0,void 0,function*(){var{helper:e,channel:t}=i,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:tu(t)}})}(e,this._core),{blackList:s=[]}=t;return this._deleteBlacklistMap(s),this._emitBlackListUpdated(),{code:0,data:Array.from(this._blacklistMap.keys())}}catch(e){var s=(e||{})["errorCode"];throw new t.ChatError({code:s})}})}dispose(){this.reset()}reset(){this._retryCount=0,this._startIndex=0,this._blacklistMap.clear()}updateBlacklist(e){var{ssoLog:t,utils:{safeStringify:s}}=this._core,{addedBlacklist:t=[],removedBlacklist:s=[]}=(t.debug("updateBlacklist",R+" updateBlacklist data: "+s(e)),e);let r=!1;0<t.length&&t.some(e=>!this._blacklistMap.has(e))&&(r=!0,this._addBlacklistMap(t.map(e=>({userID:e})))),0<s.length&&s.some(e=>this._blacklistMap.has(e))&&(r=!0,this._deleteBlacklistMap(s.map(e=>({userID:e})))),r&&this._emitBlackListUpdated()}_addBlacklistMap(e){var{ssoLog:t,utils:{safeStringify:s}}=this._core;t.debug("_addBlacklistMap",R+" _addBlacklistMap blackList: "+s(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){var{ssoLog:t,utils:{safeStringify:s}}=this._core;t.debug("_deleteBlacklistMap",R+" _deleteBlacklistMap blackList: "+s(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:2742});return t=t.includes(s)?e.userIDList.filter(e=>e!==s):t}_emitBlackListUpdated(){var{notificationCenter:e,OuterEvent:t,ssoLog:s,utils:{safeStringify:r}}=this._core,i=Array.from(this._blacklistMap.keys());s.debug(R+" _emitBlackListUpdated blackList:"+r(i)),e.emitOuterEvent(t.BLACKLIST_UPDATED,{name:t.BLACKLIST_UPDATED,data:i})}};let ru={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=ja.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=ja.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=ja.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=ja.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}}},iu={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},nu=new class{constructor(){this.name="Friend"}install(e){e.ssoLog.debug(R+" install");var{helper:t,notificationCenter:s,InnerEvent:r,constants:{WORKFLOW_NAME:i,WORKFLOW_STEP:n}}=this._core=e;ja.init(e),Ba.init(e),$a.init(e),eu.init(e),su.init(e),t.registerValidateConfig({auth:iu,params:ru}),t.registerWorkflowStep(i.SYNC_SERVER_INFO_AFTER_LOGIN,n.FRIEND_AND_BLACKLIST_SYNC,this.handleLoginSuccess,this),s.subscribeInnerEvent(r.LOGOUT,this.reset,this),s.subscribeInnerEvent(r.MESSAGE_PUSH,s.InnerEventSubType.FRIEND_LIST_MODIFIED,this.onFriendModified,this)}handleLoginSuccess(){su.syncBlacklistFromServer(),Ba.syncFriendListFromServer(),$a.syncFriendApplicationListFromServer(),eu.syncFriendGroupListFromServer()}onFriendModified(e){var{from:e,addedBlacklist:t,removedBlacklist:s,addedFriendList:r,removedFriendList:i,addedApplicationList:n,removedApplicationList:o,friendUpdateInfo:a,reportTime:u}=this._parseFriendListModification(null==e?void 0:e.FriendListMod[0]),l=this._core.utils["isEmpty"];l(t)&&l(s)||su.updateBlacklist({addedBlacklist:t,removedBlacklist:s}),l(r)&&l(i)||(Ba.updateFriendList({addedFriendList:r,removedFriendList:i}),$a.updateFriendApplicationList({from:e,removedApplicationList:r})),l(a)||Ba.updateFriendInfo(a),l(n)&&l(o)||$a.updateFriendApplicationList({from:e,addedApplicationList:n,removedApplicationList:o}),u&&$a.onApplicationRead()}_parseFriendListModification(e){var{PushType:e,From_Account:t,To_Account:s,ReportTime:r,BlackListAdd_Account:i=[],BlackListDel_Account:n=[],FriendAdd_Account:o=[],FriendDel_Account:a=[],PendencyAdd:u=[],FrienPencydDel_Account:l=[],FriendUpInfo:c=[]}=e,c=c.map(e=>({userID:e.Friend_Account,tagValueList:[...e.SNS]}));return{pushType:e,from:t,to:s,reportTime:r,addedBlacklist:i,removedBlacklist:n,addedFriendList:o,removedFriendList:a,addedApplicationList:u.map(e=>({userID:e.PendencyAdd_Account,source:e.AddSource,time:e.AddTime,wording:e.AddWording,nick:e.ProfileImNick})),friendUpdateInfo:c,removedApplicationList:l}}reset(){su.reset(),Ba.reset(),$a.reset(),eu.reset()}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),su.dispose(),Ba.dispose(),$a.dispose(),eu.dispose()}},ou=new class{init(e){this.core=e}},au="Follow",uu={NONE:0,FOLLOWERS:1,FOLLOWING:2,MUTUAL:3};function lu(o,a){return I(this,void 0,void 0,function*(){var{common:e,store:t}=ou.core,t={FollowType:o,From_Account:null==(t=t.get("login"))?void 0:t.userId,StartCursor:a,WantNum:function(){let e=ou.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}}()},{FollowItem:e=[],NextCursor:t,ActionStatus:s,ErrorCode:r,ErrorInfo:i,ErrorDisplay:n}=e=yield e.buildAndSendPacket({servcmd:"follow.follow_get",data:t});return{resultList:e.map(e=>({userID:e.To_Account,followTime:e.FollowTime,profileItem:e.ProfileItem,profileSequence:e.ProfileSequence})),nextPageToken:t,actionStatus:s,errorCode:r,errorInfo:i,errorDisplay:n}})}function cu(e){return I(this,void 0,void 0,function*(){return lu(uu.FOLLOWERS,e)})}function du(e){return I(this,void 0,void 0,function*(){return lu(uu.MUTUAL,e)})}function pu(e){return I(this,void 0,void 0,function*(){return lu(uu.FOLLOWING,e)})}function hu(n){return I(this,void 0,void 0,function*(){var{common:e,store:t}=ou.core,t={From_Account:null==(t=t.get("login"))?void 0:t.userId,FollowItem:n.map(e=>({To_Account:e}))},{ResultItem:e=[],ActionStatus:t,ErrorCode:s,ErrorInfo:r,ErrorDisplay:i}=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:i}})}function gu(n){return I(this,void 0,void 0,function*(){var{common:e,store:t}=ou.core,t={From_Account:null==(t=t.get("login"))?void 0:t.userId,To_Account:n},{ResultItem:e=[],ActionStatus:t,ErrorCode:s,ErrorInfo:r,ErrorDisplay:i}=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:i}})}let _u={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}]},mu={getMyFollowersList:!0,getMyFollowingsList:!0,getMutualFollowersList:!0,followUser:!0,unfollowUser:!0,checkFollow:!0,getUserFollowInfo:!0},vu=new class{constructor(){this.name="Follow"}install(e){var{helper:t,notificationCenter:s,InnerEvent:r}=this._core=e;ou.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:mu,params:_u}),s.subscribeInnerEvent(r.MESSAGE_PUSH,s.InnerEventSubType.FOLLOW_LIST_UPDATED,this.onFollowListUpdated,this)}getMyFollowingList(){return I(this,arguments,void 0,function*(e=""){return this._getFollowList({functionName:"getMyFollowingList",protocolFunction:pu,nextCursor:e})})}getMyFollowersList(){return I(this,arguments,void 0,function*(e=""){return this._getFollowList({functionName:"getMyFollowersList",protocolFunction:cu,nextCursor:e})})}getMutualFollowersList(){return I(this,arguments,void 0,function*(e=""){return this._getFollowList({functionName:"getMutualFollowersList",protocolFunction:du,nextCursor:e})})}_getFollowList(e){return I(this,void 0,void 0,function*(){var{functionName:r,protocolFunction:i,nextCursor:n=""}=e;try{this._checkBusinessCapabilityBits(r);let e=yield i(n),{resultList:t=[],nextPageToken:s=""}=e;return{code:0,data:{resultList:this._parseFollowItems(t),nextCursor:s},successLog:{message:r+` nextCursor: ${n} from remote`}}}catch(e){this._handleError(r,e)}})}followUser(e){return I(this,void 0,void 0,function*(){return this._handleUserFollowRelation({functionName:"followUser",userIDList:e,protocolFunction:hu})})}unfollowUser(e){return I(this,void 0,void 0,function*(){return this._handleUserFollowRelation({functionName:"unfollowUser",userIDList:e,protocolFunction:gu})})}_handleUserFollowRelation(e){return I(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:i=[]}=yield r(e);return{code:0,data:i}}catch(e){this._handleError(t,e)}})}getUserFollowInfo(n){return I(this,void 0,void 0,function*(){var s="getUserFollowInfo";try{this._checkBusinessCapabilityBits(s);var i=n||[this._core.common.getCurrentUserID()];console.log(au+` ${s} userIDList: `+i);let e=yield function(n){return I(this,void 0,void 0,function*(){var{common:e,store:t}=ou.core,t={From_Account:null==(t=t.get("login"))?void 0:t.userId,To_Account:n},{FollowInfo:e=[],ActionStatus:t,ErrorCode:s,ErrorInfo:r,ErrorDisplay:i}=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:i}})}(n),{followInfoList:t=[]}=e,r=[];return t.forEach(e=>{var{followerCount:e,followingCount:t,mutualFollowingCount:s}=e;r.push({followerCount:e,followingCount:t,mutualFollowingCount:s})}),{code:0,data:r}}catch(e){this._handleError(s,e)}})}checkFollowType(r){return I(this,void 0,void 0,function*(){var t="checkFollowType";try{this._checkBusinessCapabilityBits(t),100<r.length&&(r=r.slice(0,100),this._core.ssoLog.warn(t,au+` ${t} the length of userIDList cannot exceed 100`));var e=yield function(n){return I(this,void 0,void 0,function*(){var{common:e,store:t}=ou.core,t={From_Account:null==(t=t.get("login"))?void 0:t.userId,To_Account:n},{ResultItem:e=[],ActionStatus:t,ErrorCode:s,ErrorInfo:r,ErrorDisplay:i}=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:i}})}(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){var{ssoLog:t,utils:{safeStringify:s}}=this._core,{FollowChangeList:t=[]}=(t.debug("onFollowListUpdated",au+" onFollowListUpdated "+s(e)),e);t.forEach(e=>this._processFollowChangeItem(e))}_processFollowChangeItem(e){let{From_Account:t,FollowDiffList:s=[]}=e,r=f(e,["From_Account","FollowDiffList"]),i={userID:t,avatar:r.FaceUrl,nick:r.NickName};s.forEach(e=>{e=this._updateFollowRelation(e,i);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={[uu.FOLLOWERS]:t.MY_FOLLOWERS_LIST_UPDATED,[uu.FOLLOWING]:t.MY_FOLLOWING_LIST_UPDATED,[uu.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(uu).forEach(e=>{e!==uu.NONE&&(t[e]={userInfoList:[],isAdd:!1})}),t}_emitFollowUpdated(e,t){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("FOLLOW"))throw new t.ChatError({functionName:e,code:3122,replacement1:e})}_handleError(e,t){throw new this._core.helper.ChatError({functionName:e,code:null==t?void 0:t.errorCode,message:null==t?void 0:t.errorInfo})}_parseFollowItems(e){return e.map(e=>{let t,{userID:s,followTime:r,profileItem:i=[]}=e,n=[];i.forEach(e=>{n.push({tag:e.Tag,value:e.Value})});e=null==(t=this._core.user.userProfile)?void 0:t.createProfile(s,n);return{userID:s,followTime:r,nick:null==e?void 0:e.nick,avatar:null==e?void 0:e.avatar,allowType:null==e?void 0:e.allowType,adminForbidType:null==e?void 0:e.adminForbidType}})}},fu=new class{init(e){this.core=e}},Iu="message",Eu="user",Cu={OR:"or",AND:"and"},Su={required:!1,rules:["array"],allowEmpty:!0,customValidator:e=>!e||!!(Array.isArray(e)&&e.length<=5)||"keywordList should be an array and length <= 5"},Mu={required:!1,rules:["string"],allowEmpty:!0,customValidator:e=>!e||!![Cu.OR,Cu.AND].includes(e)||"keywordListMatchType should be OR or AND"},yu={required:!1,rules:["number"],allowEmpty:!0,customValidator:e=>"number"==typeof e&&1<=e&&e<=100||"count must be a number between 1 and 100"},Tu={required:!1,rules:["string"],allowEmpty:!0},Au={required:!1,rules:["array"],allowEmpty:!0,customValidator:t=>{var e=fu.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"}},Ou={required:!1,rules:["array"],allowEmpty:!0,customValidator:t=>{var e=fu.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"}},Du={required:!1,rules:["string"],allowEmpty:!0,customValidator:e=>{var t=fu.core["OuterConstant"];return!!(null!=e&&e.startsWith(t.CONV_C2C)||null!=e&&e.startsWith(t.CONV_GROUP)||e===t.CONV_SYSTEM)||"conversationID is invalid"}},Ru=t=>({required:!1,rules:["number"],allowEmpty:!0,customValidator:e=>"number"==typeof e&&0<=e||t+" should be a number >= 0';"}),Lu={required:!1,rules:["string"],allowEmpty:!0,customValidator:e=>{var t=fu.core["OuterConstant"];return!![t.GENDER_FEMALE,t.GENDER_MALE].includes(e)||"gender is invalid"}},Nu={searchCloudMessages:{keywordList:Su,keywordListMatchType:Mu,cursor:Tu,senderUserIDList:{required:!1,rules:["array"],allowEmpty:!0,customValidator:e=>!!(Array.isArray(e)&&e.length<=5)||"senderUserIDList should be an array and length <= 5"},messageTypeList:Ou,conversationID:Du,timePosition:Ru("timePosition"),timePeriod:Ru("timePeriod")},searchCloudUsers:{keywordList:Su,keywordListMatchType:Mu,cursor:Tu,count:yu,miniBirthday:Ru("miniBirthday"),maxBirthday:Ru("maxBirthday"),gender:Lu},searchCloudGroupMembers:{keywordList:Su,keywordListMatchType:Mu,cursor:Tu,count:yu,groupTypeList:Au,groupIDList:{required:!1,rules:["array"],allowEmpty:!0}},searchCloudGroups:{keywordList:Su,keywordListMatchType:Mu,cursor:Tu,count:yu,groupTypeList:Au}},bu={searchCloudMessages:!0,searchCloudUsers:!0,searchCloudGroupMembers:!0,searchCloudGroups:!0},Gu=new class{constructor(){this.name="CloudSearch"}install(e){this._core=e,fu.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:bu,params:Nu})}searchCloudMessages(g){return I(this,void 0,void 0,function*(){try{let{OuterConstant:o,helper:a}=this._core,{conversationID:e,timePeriod:t,timePosition:s}=g,r=f(g,["conversationID","timePeriod","timePosition"]),i=Object.assign({count:100},r);e&&(e.startsWith(o.CONV_C2C)?i.account=e.replace(o.CONV_C2C,""):e.startsWith(o.CONV_GROUP)&&(i.groupID=e.replace(o.CONV_GROUP,""))),this._setTimeRangeParams(i,{timePeriod:t,timePosition:s});var n=yield function(c){return I(this,void 0,void 0,function*(){var{count:e,keywordList:t,keywordListMatchType:s,senderUserIDList:r,messageTypeList:i,endTime:n,startTime:o,cursor:a,account:u,groupID:l}=c,e={Count:e,KeywordList:t,MatchType:s,SendUserIDList:r,MsgTypeList:i,EndTime:n,StartTime:o,Cursor:a,PeerAccount:u,GroupID:l};return fu.core.common.buildAndSendPacket({servcmd:"message_search.query",data:e})})}(i);if(!n)return{code:0,data:{}};var{ErrorCode:u,ErrorInfo:l,TotalCount:c,Cursor:d="",ConversationMsgs:p=[]}=n;if(0!==u)throw{errorCode:u,errorInfo:l};var h=`keywordList:${g.keywordList} keywordListMatchType:${g.keywordListMatchType} cursor:${g.cursor} res: totalCount:`+c;return{code:0,data:{searchResultList:p.map(e=>{let{MsgList:t,Count:s,GroupID:i,UserID:r}=e,n=i?""+o.CONV_GROUP+i:""+o.CONV_C2C+r;return this._isSearchingAllConversations(g)&&1<s?{conversationID:n,messageCount:s,messageList:[]}:{conversationID:n,messageCount:s,messageList:t.map(e=>{return a.isEmpty(i)?(t=this._core,s=t.OuterConstant.CONV_C2C,r=t.message.messageHelper.parseServerPushMessage(e),(t=t.message.messageFactory.createMessage(Object.assign(Object.assign({},r),{conversationType:s,flow:"in"}))).setElement(r.elements),t):(s=this._core,r=s.OuterConstant.CONV_GROUP,t=s.message.messageHelper.parseServerGroupMessage(e),(s=s.message.messageFactory.createMessage(Object.assign(Object.assign({},t),{conversationType:r,flow:"in"}))).setElement(t.elements),s);var t,s,r})}}),cursor:d,totalCount:c},successLog:{message:h}}}catch(e){var{errorCode:n,errorInfo:u}=e||{};this._handleError({errorCode:n,errorInfo:u,searchType:Iu,functionName:"searchCloudMessages"})}})}searchCloudUsers(v){return I(this,void 0,void 0,function*(){var s;try{var{keywordListMatchType:e,count:t=20}=v,r=f(v,["keywordListMatchType","count"]),i=Object.assign({count:t,keywordListMatchType:e===Cu.AND?1:0},r),n=(this._setBirthdayRangeParams(i,v),yield function(a){return I(this,void 0,void 0,function*(){var{count:e,keywordList:t,keywordListMatchType:s,miniBirthday:r,maxBirthday:i,cursor:n,gender:o}=a,e={Count:e,Keywords:t,KeywordMatchType:s,Cursor:n,UserBirthStart:r,UserBirthEnd:i,Gender:o};return fu.core.common.buildAndSendPacket({servcmd:"user_search.query",data:e})})}(i));if(!n)return{error:0,data:{}};var{ErrorCode:o,ErrorInfo:a,TotalCount:u,Cursor:l="",Users:c=[]}=n;if(0!==o)throw{errorCode:o,errorInfo:a};var d=`keywordList:${v.keywordList} keywordListMatchType:${v.keywordListMatchType} cursor:${v.cursor} count:${v.count} res: totalCount:`+u,p=[];for(let e=0,t=c.length;e<t;e++){var h,g,{UserID:_,ProfileItems:m}=c[e];_!==this._core.OuterConstant.USER_NOT_FOUND&&""!==_&&(h=m.map(e=>({tag:e.Tag,value:e.StrValue})),g=null==(s=this._core.user.userProfile)?void 0:s.createProfile(_,h),p.push(g))}return{code:0,data:{searchResultList:p,cursor:l,totalCount:u},successLog:{message:d}}}catch(e){let{errorCode:t,errorInfo:s}=e||{};this._handleError({errorCode:t,errorInfo:s,searchType:Eu,functionName:"searchCloudUsers"})}})}searchCloudGroupMembers(d){return I(this,void 0,void 0,function*(){try{var{count:t=20,keywordListMatchType:s}=d,r=f(d,["count","keywordListMatchType"]),i=yield function(o){return I(this,void 0,void 0,function*(){var{count:e,keywordList:t,keywordListMatchType:s,groupTypeList:r,cursor:i,groupIDList:n}=o,e={Count:e,Keywords:t,KeywordMatchType:s,Cursor:i,GroupType:r,GroupIdList:n};return fu.core.common.buildAndSendPacket({servcmd:"group_member_search.query",data:e})})}(Object.assign({count:t,keywordListMatchType:s===Cu.AND?1:0},r));if(!i)return{code:0,data:{}};var{ErrorCode:n,ErrorInfo:o,GroupMembers:a=[],Cursor:l,TotalCount:c}=i;if(0!==n)throw{errorCode:n,errorInfo:o};let e=`keywordList:${d.keywordList} keywordListMatchType:${d.keywordListMatchType} cursor:${d.cursor} count:${d.count} res: totalCount:`+c,u=new Map;return a.forEach(e=>{var{GroupID:t,GroupName:e,GroupType:s,GroupFaceUrl:r,GroupMemberUserName:i,GroupMemberUserID:n,GroupMemberNameCard:o,GroupMemberAvatar:a=""}=e,e={groupID:t,name:e,type:s,avatar:r},s={userID:n,nick:i,nameCard:o,avatar:a};if(u.has(t)){let e=u.get(t);e.memberList.push(s),u.set(t,e)}else u.set(t,{groupInfo:e,memberList:[s]})}),{code:0,data:{searchResultList:[...u.values()],cursor:l,totalCount:c},successLog:{message:e}}}catch(e){var{errorCode:t,errorInfo:s}=e||{};this._handleError({errorCode:t,errorInfo:s,searchType:Eu,functionName:"searchCloudGroupMembers"})}})}searchCloudGroups(c){return I(this,void 0,void 0,function*(){try{var{count:t=20,keywordListMatchType:s}=c,e=f(c,["count","keywordListMatchType"]),r=yield function(n){return I(this,void 0,void 0,function*(){var{count:e,keywordList:t,keywordListMatchType:s,groupTypeList:r,cursor:i}=n,e={Count:e,Keywords:t,KeywordMatchType:s,Cursor:i,GroupType:r};return fu.core.common.buildAndSendPacket({servcmd:"group_search.query",data:e})})}(Object.assign({count:t,keywordListMatchType:s===Cu.AND?1:0},e));if(!r)return{code:0,data:{}};var{ErrorCode:i,ErrorInfo:n,Groups:o,Cursor:a,TotalCount:u}=r;if(0!==i)throw{errorCode:i,errorInfo:n};var l=`keywordList:${c.keywordList} keywordListMatchType:${c.keywordListMatchType} cursor:${c.cursor} count:${c.count} res: totalCount:`+u;return{code:0,data:{searchResultList:(null==o?void 0:o.map(e=>{var{GroupFaceUrl:e,GroupID:t,GroupIntroduction:s,GroupMemberNum:r,GroupName:i,GroupOwnerTinyID:n,GroupOwnerUserID:o,GroupOwnerUserName:a,GroupType:u,GroupAddOption:l,GroupInviteOption:c}=e;return{avatar:e,groupID:t,introduction:s,memberCount:r,name:i,ownerTinyID:n,ownerID:o,ownerNick:a,type:u,joinOption:l,inviteOption:c}}))||[],cursor:a,totalCount:u},successLog:{message:l}}}catch(e){var{errorCode:t,errorInfo:s}=e||{};this._handleError({errorCode:t,errorInfo:s,searchType:Eu,functionName:"searchCloudGroups"})}})}_setTimeRangeParams(e,{timePeriod:t,timePosition:s}){t&&0<t&&(e.startTime=s&&0<s?s-t:this._core.helper.timeManager.getServerTimeSeconds()-t),e.startTime&&e.startTime<0&&(e.startTime=void 0),s&&0<s&&(e.endTime=s)}_handleError({errorCode:e,errorMessage:t,searchType:s}){var r=this._core["helper"];let i=e;throw 60020===e?i="SearchUnable":s!==Iu&&27003===e?i="SearchParamsError":s!==Iu&&60018===e&&(i="SearchOverLimit"),new r.ChatError({code:i,message:t})}_isSearchingAllConversations(e){return this._core.helper.isEmpty(e.conversationID)}_setBirthdayRangeParams(e,t){var{miniBirthday:t,maxBirthday:s}=t;void 0!==t&&(e.miniBirthday=t,void 0===s)&&(e.maxBirthday=4294967295),void 0!==s&&(e.maxBirthday=s)}};var Pu=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 wu=new class{init(e){this.core=e}},Uu="NOT_STARTED";function ku(e){var{helper:t,constants:s}=wu.core;if(!t.checkBusinessCapabilityBits("CONV_GROUP"))throw new t.ChatError({functionName:e,code:s.ERROR_CODE.NO_USE,replacement1:e})}function Fu(){var{notificationCenter:e,OuterEvent:t}=wu.core;e.emitOuterEvent(t.CONVERSATION_GROUP_LIST_UPDATED,{name:t.CONVERSATION_GROUP_LIST_UPDATED,data:[...Pu.getConversationGroupMap().values()]})}function qu(e){var{utils:{isUndefined:t},constants:{OuterConstant:s}}=wu.core,{Type:e,To_Account:r,GroupId:i,ToGroupId:i=i,Peer_Account:n}=e;let o="";return 1===e?t(n)?t(r)||(o=""+s.CONV_C2C+r):o=""+s.CONV_C2C+n:2===e&&(o=""+s.CONV_GROUP+i),o}function xu(e){let t=[],{OuterConstant:s,common:{isC2CConv:r,isGroupConv:i}}=wu.core,{conversationIDList:n,failureConversationIDList:o,additionalData:a={}}=e;return n.forEach(e=>{Vu(e,o),r(e)?t.push(Object.assign({ContactItem:{Type:1,To_Account:e.replace(s.CONV_C2C,"")}},a)):i(e)&&t.push(Object.assign({ContactItem:{Type:2,ToGroupId:e.replace(s.CONV_GROUP,"")}},a))}),t}function Vu(e,t){var{appStore:{conversationStore:s},common:{isC2CConv:r,isGroupConv:i}}=wu.core;s.getConversation(e)?r(e)||i(e)||t.push({conversationID:e,code:2503}):t.push({conversationID:e,code:2500})}function Bu(t){var{isString:e}=wu.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 ju(i){null!=i&&i.forEach((e,t)=>{var s=wu.core["appStore"],{conversationID:e,data:r}=e,t=t===i.length-1;s.conversationStore.updateConversation(e,r,{emit:t})})}function Ku(e){var{conversationInfoList:e,fromAccount:t}=e,t={From_Account:t,MarkItem:e};return wu.core.common.buildAndSendPacket({servcmd:"recentcontact.mark_contact",data:t})}function Wu(e){var{fromAccount:e,groupName:t,conversationInfoList:s}=e,e={From_Account:e,UpdateType:1,UpdateGroup:{UpdateGroupType:2,OldGroupName:t,ContactUpdateItem:s}};return wu.core.common.buildAndSendPacket({servcmd:"recentcontact.update_contact_group",data:e})}var Hu=new class{init(e){var{registerApi:t}=e["helper"];this._core=e,t({apiName:"createConversationGroup",context:this})}createConversationGroup(s){return I(this,void 0,void 0,function*(){let{utils:{isPlainObject:n,isArray:o},appStore:a}=this._core,{groupName:u,conversationIDList:e}=(ku("createConversationGroup"),s),l=[],t=this._generateConversationInfo(e,l);if(l.length===e.length)return{code:0,data:{successConversationIDList:[],failureConversationIDList:l}};try{let i=yield function(e){var{buildAndSendPacket:t,getCurrentUserID:s}=wu.core["common"],{item:e,groupName:r}=e;return t({servcmd:"recentcontact.create_contact_group",data:{From_Account:s(),GroupContactItem:[{GroupName:r,ContactItem:e}]}})}({groupName:u,item:t});if(i){let{GroupResultItem:e=[]}=i,{GroupItem:s,ResultItem:t}=(null==e?void 0:e[0])||{},r=[];if(n(s)){let{GroupName:e,GroupId:t}=s;Pu.setConversationGroup(t,e),Fu()}if(o(t)){let n=[];t.forEach(e=>{let{ContactItem:t,ResultCode:s,ResultInfo:r}=e,i=qu(t);if(0===s){let t=a.conversationStore.getConversation(i);if(t&&!t.conversationGroupList.includes(u)){let e=t.conversationGroupList.slice();e.push(u),n.push({conversationID:i,data:{conversationGroupList:e}})}}else l.push({conversationID:i,code:s,message:r})}),0<n.length&&(ju(n),Fu())}return{code:0,data:{successConversationIDList:r,failureConversationIDList:l}}}}catch(e){let{errorCode:t,errorInfo:s}=e;throw new this._core.helper.ChatError({functionName:"createConversationGroup",code:t,message:s})}})}_generateConversationInfo(e,t,s={}){let r=[],{OuterConstant:i,common:{isC2CConv:n,isGroupConv:o}}=this._core;return e.forEach(e=>{Vu(e,t),n(e)?r.push(Object.assign({Type:1,To_Account:e.replace(i.CONV_C2C,"")},s)):o(e)&&r.push(Object.assign({Type:2,ToGroupId:e.replace(i.CONV_GROUP,"")},s))}),r}},Yu=new class{constructor(){this._fetchConversationGroupStatus=Uu}init(e){var{helper:{registerApi:t,registerWorkflowStep:s},constants:{WORKFLOW_NAME:r,WORKFLOW_STEP:i}}=e;this._core=e,t({apiName:"getConversationGroupList",context:this}),s(r.SYNC_SERVER_INFO_AFTER_LOGIN,i.CONVERSATION_GROUP_LIST_SYNC,this._syncConversationGroupList,this),s(r.SYNC_SERVER_INFO_AFTER_LOGIN,i.CONVERSATION_GROUP_UPDATE,this._updateConversation,this)}getConversationGroupList(){return I(this,void 0,void 0,function*(){return ku("getConversationGroupList"),"FAILED"===this._fetchConversationGroupStatus&&(yield this._fetchConversationGroupList(0)),{code:0,data:[...Pu.getConversationGroupMap().values()]}})}_syncConversationGroupList(){return I(this,void 0,void 0,function*(){return yield this._fetchConversationGroupList(0)})}_fetchConversationGroupList(e){return I(this,arguments,void 0,function*(r,n=[]){let{common:{getCurrentUserID:e},utils:{isArray:o}}=this._core;this._fetchConversationGroupStatus="FETCHING";try{let s=e(),i=yield function(){var{fromAccount:e,startIndex:t}={fromAccount:s,startIndex:r},e={From_Account:e,StartIndex:t};return wu.core.common.buildAndSendPacket({servcmd:"recentcontact.get_contact_group",data:e})}();if(i){let{CompleteFlag:e,ContactItem:t=[],NextStartIndex:s=0,GroupItem:r=[]}=i;return(o(r)&&r.forEach(e=>{var{GroupName:e,GroupId:t}=e;Pu.setConversationGroup(t,e)}),n.push(...t),0===e)?this._fetchConversationGroupList(s):1===e?(this._fetchConversationGroupStatus="FINISHED",n):void 0}}catch(r){this._fetchConversationGroupStatus="FAILED",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])||[];ju(this._generateConversationUpdateFields(e)),Fu()}_generateConversationUpdateFields(e){let{utils:{isArray:o},appStore:a}=this._core,u=[];if(o(e)){let n;e.forEach(e=>{let t=[],{StandardMark:s,CustomMark:r="",ContactGroupId:i}=e;o(i)&&i.forEach(e=>{Pu.getConversationGroupMap().has(e)&&t.push(Pu.getConversationGroup(e))});e=qu(e);(n=a.conversationStore.getConversation(e))&&u.push({conversationID:e,data:{markList:Bu(s),customData:r,conversationGroupList:[...t]}})})}return u}reset(){this._fetchConversationGroupStatus=Uu}dispose(){this.reset()}},$u=new class{init(e){var{notificationCenter:t,helper:{registerApi:s},InnerEvent:{MESSAGE_PUSH:r},InnerEventSubType:{CONVERSATION_MARK_UPDATED:i,CONVERSATION_GROUP_ADD:n,CONVERSATION_GROUP_DELETED:o,CONVERSATION_GROUP_UPDATED:a}}=e;this._core=e,s({apiName:"renameConversationGroup",context:this}),s({apiName:"deleteConversationGroup",context:this}),s({apiName:"markConversation",context:this}),s({apiName:"setConversationCustomData",context:this}),s({apiName:"deleteConversationsFromGroup",context:this}),s({apiName:"addConversationsToGroup",context:this}),t.subscribeInnerEvent(r,n,this._handleConversationGroupAdd,this),t.subscribeInnerEvent(r,o,this._handleConversationGroupDeleted,this),t.subscribeInnerEvent(r,a,this._handleConversationGroupUpdated,this),t.subscribeInnerEvent(r,i,this._handleConversationMarkUpdated,this)}renameConversationGroup(e){return I(this,void 0,void 0,function*(){ku("renameConversationGroup");let{getCurrentUserID:r}=this._core["common"],{oldName:i,newName:n}=e,o=`oldName:${i} newName:`+n;try{let s=yield function(){var{fromAccount:e,oldName:t,newName:s}={fromAccount:r(),oldName:i,newName:n},e={From_Account:e,UpdateType:1,UpdateGroup:{UpdateGroupType:1,OldGroupName:t,NewGroupName:s}};return wu.core.common.buildAndSendPacket({servcmd:"recentcontact.update_contact_group",data:e})}();if(s){let e=s["UpdateGroupResult"],t=e["GroupId"];Pu.setConversationGroup(t,n),Fu(),this._updateLocalConversationGroupName({oldName:i,newName:n})}return{successLog:{message:o}}}catch(e){let{errorCode:t,errorInfo:s}=e;throw new this._core.helper.ChatError({functionName:"renameConversationGroup",code:t,message:s,moreMessage:o})}})}deleteConversationGroup(r){return I(this,void 0,void 0,function*(){ku("deleteConversationGroup");let s=this._core["common"]["getCurrentUserID"];try{var t=yield function(){var{fromAccount:e,groupName:t}={fromAccount:s(),groupName:r},e={From_Account:e,GroupName:[t]};return wu.core.common.buildAndSendPacket({servcmd:"recentcontact.del_contact_group",data:e})}();if(t){let e=t["GroupItem"],s=!1;return null!=e&&e.forEach(e=>{var e=e["GroupId"],t=Pu.getConversationGroupMap();t.has(e)&&(t.delete(e),s=!0)}),s&&Fu(),this._deleteLocalConversationGroupName([r]),{successLog:{message:"groupName:"+r}}}}catch(s){var{errorCode:t,errorInfo:e}=s;throw new this._core.helper.ChatError({functionName:"deleteConversationGroup",code:t,message:e,moreMessage:"groupName:"+r})}})}markConversation(p){return I(this,void 0,void 0,function*(){ku("markConversation");let{utils:{isNumber:e},common:{getCurrentUserID:s},appStore:o}=this._core,{conversationIDList:t,markType:a,enableMark:u}=p,r=this._getFlagBit(a),l=[],c=[],i,n;!0===u&&e(r)?i=[r]:n=[r];var d=xu({conversationIDList:t,failureConversationIDList:l,additionalData:{SetMark:i,ClearMark:n,OptType:1}});if(l.length===t.length)return{code:0,data:{successConversationIDList:[],failureConversationIDList:l}};try{let t=yield Ku({conversationInfoList:d,fromAccount:s()});if(t){let e=t["ResultItem"],n=[];e.forEach(e=>{let{ContactItem:t,ResultCode:s,ResultInfo:r}=e,i=qu(t);if(0===s){c.push(i);let s=o.conversationStore.getConversation(i);if(s){let t=s.markList.indexOf(a),e=!1===u&&-1!==t;if(!0===u&&-1===t)n.push({conversationID:i,data:{markList:[...s.markList,a]}});else if(e){let e=s.markList.slice();e.splice(t,1),n.push({conversationID:i,data:{markList:e}})}}}else l.push({conversationID:i,code:s,message:r})}),ju(n)}return{code:0,data:{successConversationIDList:c,failureConversationIDList:l}}}catch(e){let{errorCode:t,errorInfo:s}=e;throw new this._core.helper.ChatError({functionName:"markConversation",code:t,message:s})}})}setConversationCustomData(r){return I(this,void 0,void 0,function*(){ku("setConversationCustomData");let{common:{getCurrentUserID:e},appStore:i}=this._core,{conversationIDList:t,customData:n}=r,o=[],a=[],s=xu({conversationIDList:t,failureConversationIDList:o,additionalData:{CustomMark:n,OptType:2}});if(o.length===t.length)return{code:0,data:{successConversationIDList:[],failureConversationIDList:o}};try{let t=yield Ku({fromAccount:e(),conversationInfoList:s});if(t){let e=t["ResultItem"],r=[];null!=e&&e.forEach(e=>{var{ContactItem:s,ResultCode:e,ResultInfo:t}=e;if(0===e){let e=qu(s),t=(a.push(e),i.conversationStore.getConversation(e));t&&t.customData!==n&&r.push({conversationID:e,data:{customData:n}})}else o.push({conversationID:conversationID,code:e,message:t})}),ju(r)}return{code:0,data:{successConversationIDList:a,failureConversationIDList:o}}}catch(e){let{errorCode:t,errorInfo:s}=e;throw new this._core.helper.ChatError({functionName:"setConversationCustomData",code:t,message:s})}})}deleteConversationsFromGroup(i){return I(this,void 0,void 0,function*(){ku("deleteConversationsFromGroup");let{common:{getCurrentUserID:e},appStore:n}=this._core,{conversationIDList:t,groupName:o}=i,s=[],a=[],r=xu({conversationIDList:t,failureConversationIDList:s,additionalData:{ContactOptType:2}});if(s.length===t.length)return{code:0,data:{successConversationIDList:[],failureConversationIDList:s}};try{let t=yield Wu({fromAccount:e(),groupName:o,conversationInfoList:r});if(t){let i=[],{ContactResultItem:e}=t["UpdateGroupResult"];null!=e&&e.forEach(e=>{var r=qu(e.ContactItem);if(0===e.ResultCode){let s=n.conversationStore.getConversation(r);if(s){let t=s.conversationGroupList.indexOf(o);if(-1!==t){let e=s.conversationGroupList.slice();e.splice(t,1),a.push(r),i.push({conversationID:r,data:{conversationGroupList:e}})}}}else s.push({conversationID:r,code:e.ResultCode,message:e.ResultInfo})}),0<i.length&&(Fu(),ju(i))}return{code:0,data:{successConversationIDList:a,failureConversationIDList:s}}}catch(e){let{errorCode:t,errorInfo:s}=e;throw new this._core.helper.ChatError({functionName:"deleteConversationsFromGroup",code:t,message:s})}})}addConversationsToGroup(r){return I(this,void 0,void 0,function*(){ku("deleteConversationsFromGroup");let{common:{getCurrentUserID:e},appStore:i}=this._core,{conversationIDList:t,groupName:n}=r,o=[],a=[],s=xu({conversationIDList:t,failureConversationIDList:o,additionalData:{ContactOptType:1}});if(o.length===t.length)return{code:0,data:{successConversationIDList:[],failureConversationIDList:o}};try{let t=yield Wu({fromAccount:e(),groupName:n,conversationInfoList:s});if(t){let r=[],{ContactResultItem:e}=t["UpdateGroupResult"];null!=e&&e.forEach(e=>{var s=qu(e.ContactItem);if(0===e.ResultCode){let t=i.conversationStore.getConversation(s);if(t&&-1===t.conversationGroupList.indexOf(n)){let e=t.conversationGroupList.slice();e.push(n),a.push(s),r.push({conversationID:s,data:{conversationGroupList:e}})}}else o.push({conversationID:s,code:e.ResultCode,message:e.ResultInfo})}),0<r.length&&(Fu(),ju(r))}return{code:0,data:{successConversationIDList:a,failureConversationIDList:o}}}catch(e){let{errorCode:t,errorInfo:s}=e;throw new this._core.helper.ChatError({functionName:"deleteConversationsFromGroup",code:t,message:s})}})}_updateLocalConversationGroupName(e){let t=this._core["appStore"],{oldName:s,newName:r}=e,i=[],n=[],o;Array.from(t.conversationStore.getConversationMap().values()).forEach(e=>{var t;i=e.conversationGroupList,-1!==(o=i.indexOf(s))&&((t=i.slice()).splice(o,1,r),n.push({conversationID:e.conversationID,data:{conversationGroupList:t}}))}),ju(n)}_deleteLocalConversationGroupName(i){var{utils:{isEmpty:e},appStore:t}=this._core;if(!e(i)){let r=[];Array.from(t.conversationStore.getConversationMap().values()).forEach(e=>{var{conversationID:e,conversationGroupList:t}=e,s=t.filter(e=>!i.includes(e));s.length<t.length&&r.push({conversationID:e,data:{conversationGroupList:s}})}),ju(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:u}=this._core;null!=(t=null==e?void 0:e.RecentContactMod)&&t.forEach(e=>{var e=e["RecentContactCreateContactGroup"]["MsgContactGroupContactItem"];let o=!1;null!=e&&e.forEach(e=>{let{MsgGroupItem:t,MsgRecentContactItem:s}=e,{GroupId:r,GroupName:i}=t,n=[];Pu.getConversationGroup(r)!==i&&(Pu.setConversationGroup(r,i),o=!0),a(s)&&s.forEach(e=>{var t=qu(e),s=u.conversationStore.getConversation(t);if(s&&(null==(e=s.conversationGroupList)||!e.includes(i))){let e=s.conversationGroupList.slice();e.push(i),n.push({conversationID:t,data:{conversationGroupList:e}})}}),o&&Fu(),ju(n)})})}_handleConversationGroupDeleted(e){let t,{isArray:s}=this._core.utils;null!=(t=null==e?void 0:e.RecentContactMod)&&t.forEach(e=>{e=((null==e?void 0:e.RecentContactDelContactGroup)||{}).MsgGroupItem;if(s(e)){let r=!1,i=[];e.forEach(e=>{var{GroupId:e,GroupName:t}=e,s=Pu.getConversationGroupMap();s.has(e)&&(s.delete(e),r=!0,i.push(t))}),r&&Fu(),0<i.length&&this._deleteLocalConversationGroupName(i)}})}_handleConversationGroupUpdated(e){null!=(e=e.RecentContactMod)&&e.forEach(e=>{var{GroupId:e,GroupName:t,OldGroupName:s,RecentContactUpdateGroupItem:r,UpdateGroupType:i}=e["RecentContactUpdateContactGroup"]["MsgUpdateGroup"];1===i?this._handleGroupNameUpdated({groupID:e,newName:t,oldName:s}):2===i&&this._handleGroupAddOrDeleteFromConversation({groupInfoList:r,groupName:s})})}_handleConversationMarkUpdated(e){let t,n=this._core.appStore;null!=(t=null==e?void 0:e.RecentContactMod)&&t.forEach(e=>{let{RecentContactMarkContactItem:t}=e["RecentContactMarkContact"],i=[];null!=t&&t.forEach(e=>{var{RecentContactItem:e,CustomMark:t,StandardMark:s,OptType:r}=e,e=qu(e),e=n.conversationStore.getConversation(e);e&&(1===r?this._updateStandMark({conversation:e,standardMark:s,updateConversationList:i}):2===r?this._updateCustomMark({conversation:e,customMark:t,updateConversationList:i}):3===r&&(this._updateStandMark({conversation:e,standardMark:s,updateConversationList:i}),this._updateCustomMark({conversation:e,customMark:t,updateConversationList:i})))}),ju(i)})}_updateStandMark(e){var{conversation:e,standardMark:t,updateConversationList:s}=e,t=Bu(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;Pu.getConversationGroup(e)!==s&&(Pu.setConversationGroup(e,s),Fu(),this._updateLocalConversationGroupName({oldName:t,newName:s}))}_handleGroupAddOrDeleteFromConversation({groupInfoList:e,groupName:n}){let o=this._core["appStore"],a=[];e.forEach(e=>{var{RecentContactItem:e,ContactOptType:t}=e,s=qu(e),r=o.conversationStore.getConversation(s),i=r.conversationGroupList.indexOf(n);if(r){let e=r.conversationGroupList.slice();1===t&&-1===i?(e.push(n),a.push({conversationID:s,data:{conversationGroupList:e}})):2===t&&-1!==i&&(e.splice(i,1),a.push({conversationID:s,data:{conversationGroupList:e}}))}}),ju(a)}dispose(){var{notificationCenter:e,InnerEvent:{MESSAGE_PUSH:t},InnerEventSubType:{CONVERSATION_MARK_UPDATED:s,CONVERSATION_GROUP_ADD:r,CONVERSATION_GROUP_DELETED:i,CONVERSATION_GROUP_UPDATED:n}}=this._core;e.unSubscribeInnerEvent(t,r,this._handleConversationGroupAdd,this),e.unSubscribeInnerEvent(t,i,this._handleConversationGroupDeleted,this),e.unSubscribeInnerEvent(t,n,this._handleConversationGroupUpdated,this),e.unSubscribeInnerEvent(t,s,this._handleConversationMarkUpdated,this)}};let zu={required:!0,rules:["string"],allowEmpty:!1},Ju={required:!0,rules:["array"],allowEmpty:!1},Qu={createConversationGroup:{groupName:zu,conversationIDList:{required:!0,rules:["array"],allowEmpty:!1}},renameConversationGroup:{oldName:zu,newName:Object.assign(Object.assign({},zu),{customValidator:e=>!(32<e.length)||"newName length cannot longer than 32"})},deleteConversationGroup:[{required:!0,rules:["string"],allowEmpty:!1}],addConversationsToGroup:{conversationIDList:Ju,groupName:zu},deleteConversationsFromGroup:{conversationIDList:Ju,groupName:zu},markConversation:{conversationIDList:Ju,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:Ju,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"}}},Xu={createConversationGroup:!0,deleteConversationGroup:!0,renameConversationGroup:!0,getConversationGroupList:!0,addConversationsToGroup:!0,deleteConversationsFromGroup:!0,markConversation:!0,setConversationCustomData:!0},Zu=new class{constructor(){this.name="ConversationGroup"}install(e){this._core=e,wu.init(e),Pu.init(e),Hu.init(e),Yu.init(e),$u.init(e),e.helper.registerValidateConfig({auth:Xu,params:Qu}),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),$u.dispose(),Yu.dispose()}reset(){Yu.reset()}},el=new class{init(e){this.core=e}},tl=["topicID","topicName","avatar","introduction","notification","unreadCount","muteAllMembers","customData","nextMessageSeq","selfInfo","lastMessage"],sl=e=>{var{common:{getMessagePreviewText:t}}=el["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 rl{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=sl(),this.selfInfo={muteTime:0,readedSequence:0,messageRemindType:"",excludedUnreadSequenceList:void 0},this._init(e)}_init(e){for(var t in e)tl.includes(t)&&("lastMessage"===t?this[t]=sl(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=sl(e)}updateGroupAtInfoList(e){var{common:{updateGroupAtInfo:t}}=el["core"];t(e,this.groupAtInfoList)}updateTopic(e){var{utils:{isUndefined:t},common:{deepMerge:s}}=el["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}}=el["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 L=new class{constructor(){this._name="TopicDataHandler",this._topicMap=new Map,this._topicRequestInfo=new Map}init(e){var{helper:t,constants:s,notificationCenter:r,InnerEvent:{LOGOUT:i,DESTROY:n}}=this._core=e;t.registerWorkflowStep(s.WORKFLOW_NAME.SYNC_SERVER_INFO_AFTER_RE_ONLINE,s.WORKFLOW_STEP.TOPIC_REQUEST_INFO_RESET,this._resetTopicRequestInfo,this),r.subscribeInnerEvent(i,this._reset,this),r.subscribeInnerEvent(n,this._dispose,this),e.ssoLog.debug(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 rl(e),this._setTopic(t,s,r));e=this.computeUnreadCount(r);null!=r&&r.updateUnreadCount(e)})}_getLastMessage(s){var{isEmpty:r,isUndefined:i,isArray:n}=this._core["utils"];if(!i(s.lastMsg)){let e=null,t="";t=(n(s.lastMsg.elements)?(e=s.lastMsg.elements[0].content,s.lastMsg.elements[0]):(e=s.lastMsg.elements.content,s.lastMsg.elements)).type;i={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=i}}computeUnreadCount(s){let{excludedUnreadSequenceList:e=[],readedSequence:r}=s.selfInfo,i=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&&(i-=t)}return 0<i?i: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:i,isEmpty:t}}=this._core,n=e(),o=null;s.forEach(e=>{var{groupID:t,topicID:s,from:r}=e;r!==n&&((o=this.getTopic(t,s))&&o.updateGroupAtInfoList(e),i(o))&&a&&(this.updateTopic([{groupID:t,topicID:s}]),null!=(r=this.getTopic(t,s)))&&r.updateGroupAtInfoList(e)}),t(o)||this.emitTopicUpdate(o)}}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,i=(null==t?void 0:t.getLocalMessageList(""+r+e))||[];if(0!==i.length){e=i["length"];for(let t=e-1;0<=t;t--){let e=i[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 i=!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),i=!0),i)&&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 il=(e="")=>{var{OuterConstant:t}=el["core"];return e.replace(t.CONV_GROUP,"")},nl=(e="")=>e.split("@TOPIC#_")[0];var ol,al=new class{constructor(){this._name="TopicMessageHandler"}init(e){var{helper:t,notificationCenter:s,constants:{WORKFLOW_NAME:r,WORKFLOW_STEP:i},InnerEvent:{MESSAGE_PUSH:n,TOPIC_NEW_MESSAGE:o,TOPIC_MESSAGE_DELETED:a,TOPIC_MESSAGE_REVOKED:u,TOPIC_MESSAGE_MODIFIED:l,DESTROY:c}}=this._core=e,{TOPIC_AT_TIPS:d,TOPIC_LATEST_MESSAGE:p}=s["InnerEventSubType"];t.registerWorkflowStep(r.SYNC_SERVER_INFO_AFTER_LOGIN,i.UPDATE_TOPIC_AFTER_UNREAD_SYNC_FINISHED,this._handleUnreadSyncFinished,this),t.registerWorkflowStep(r.RECEIVE_GROUP_NEW_MESSAGE,i.UPDATE_TOPIC_BY_RECEIVE_NEW_MESSAGE,this._handleNewMessage,this),s.subscribeInnerEvent(o,this._handleNewMessage,this),s.subscribeInnerEvent(a,this._handleMessageDeleted,this),s.subscribeInnerEvent(u,this._handleMessageRevoked,this),s.subscribeInnerEvent(l,this._handleMessageModified,this),s.subscribeInnerEvent(n,d,this._handleTopicAtTips,this),s.subscribeInnerEvent(n,p,this._handleLatestMessage,this),s.subscribeInnerEvent(c,this._dispose,this),e.ssoLog.debug(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 o=this._core["common"]["getCurrentUserID"];e.forEach(e=>{let{conversationID:t="",lastMessage:i}=e,s=il(t),r=nl(s),n=L.getTopic(r,s);if(n){let{from:e,sequence:t}=i,s=t+1,r=e===o();if(s>n.nextMessageSeq){n.updateNextMessageSeq(s),n.updateLastMessage(i),n.updateReadSequence(t,r);let e=r?0:L.computeUnreadCount(n);n.updateUnreadCount(e),this._emitTopicUpdate(n)}}})}}}_handleMessageDeleted(s){var r=il(s),i=nl(r),i=L.getTopic(i,r);if(console.log(this._name+`._handleMessageDeleted, topicID:${r} hasTopic:`+!!i),i){var{message:{messageDataHandler:n},utils:{isEmpty:o}}=this._core,a=(null==n?void 0:n.getLocalMessageList(s))||[];let t={};for(let e=(a.length||0)-1;0<=e;e--)if(!a[e].isDeleted){t=a[e];break}let e=!1;i.lastMessage.lastSequence!==t.sequence&&(o(t)&&(t={}),i.updateLastMessage(t),e=!0),e&&(this._emitTopicUpdate(i),console.log(this._name+`._handleMessageDeleted, topicID:${r} with lastMessage:`+i.lastMessage))}}_handleMessageRevoked(e){var{messageList:e=[]}=e;if(console.log(this._name+"._handleMessageRevoked messageList:"+e.length),0!==e.length){let i=null,n=!1;e.forEach(e=>{var{to:e,sequence:t,revoker:s}=e,r=nl(e);if(i=L.getTopic(r,e)){i.reduceUnreadCount()&&(n=!0),i.isLastMessageRevoked(t)&&(i.setLastMessageRevoked(!0),i.setLastMessageRevoker(s),n=!0);let{excludedUnreadSequenceList:e=[]}=i.selfInfo;e.push(t),i.updateSelfInfo({excludedUnreadSequenceList:e})}}),n&&this._emitTopicUpdate(i)}}_handleMessageModified(e){let{conversationID:t,messageList:s}=e,r=il(t),i=nl(r),a=L.getTopic(i,r);if(console.log(`${this._name}._handleMessageModified topicID:${r} hasTopic:`+!!a),a){var u=a["lastMessage"];if(u){let o=(null==s?void 0:s[0])||{};if(this._shouldUpdateLastMessage(u,o)){let{getMessagePreviewText:e}=this._core["common"],{time:t,sequence:s,elements:r,cloudCustomData:i,messageVersion:n}=o;u.type=r[0].type,u.payload=r[0].content,u.messageForShow=e(u.type,u.payload),u.cloudCustomData=i,u.version=n,u.lastSequence=s,u.lastTime=t,this._emitTopicUpdate(a)}}}}_shouldUpdateLastMessage(e,t){var s;return null===e.payload||({sequence:t,messageVersion:s}=t,e.lastSequence===t&&e.version!==s)}_emitTopicUpdate(e){var{notificationCenter:t,OuterEvent:s}=this._core;t.emitOuterEvent(s.TOPIC_UPDATED,{name:s.TOPIC_UPDATED,data:e})}_handleTopicAtTips(e){let{GroupTips:t=[]}=e,n=[],o=!1;t.forEach(e=>{var{GroupAtTips:e,MsgBody:t,MsgRandom:s,ClientSeq:r}=e;let i={};e?i=this._convertAtInfo(e):t&&(i=this._convertAtInfo(t),o=!0),i.__random=s,i.__sequence=r,n.push(i)}),L.updateGroupAtInfoList(n,o)}_convertAtInfo(e){var{From_Account:e,GroupId:t,TopicId:s,MsgSeq:r,GroupAtType:i}=e;return{groupID:t,topicID:s,from:e,sequence:r,groupAtType:i}}_handleLatestMessage(e){let{utils:{isEmpty:t},message:{messageHelper:r,messageFactory:i}}=this._core,{NewMsg:n,NoUnreadSeqList:o}=e||{};if(!t(n)){let{TopicId:e}=n["GroupInfo"],t=r.parseServerGroupMessage(n),s=i.createMessage(t);s.setElement(t.elements),this._updateUnreadCountAndLastMessage({topicID:e,message:s,excludedUnreadSequenceList:o})}}_updateUnreadCountAndLastMessage(e){let{isUndefined:t}=this._core["utils"],{topicID:s,message:r,excludedUnreadSequenceList:i}=e,n=nl(s),o=L.getTopic(n,s);if(o){let e=o.selfInfo.excludedUnreadSequenceList||[];if(t(i)||(e=i),r._isExcludedFromUnreadCount&&e.push(r.sequence),o.updateSelfInfo({excludedUnreadSequenceList:e}),console.log(`${this._name}._updateUnreadCountAndLastMessage latest message sequence:${r.sequence} lastMessage sequence:`+o.lastMessage.lastSequence),r.sequence>o.lastMessage.lastSequence){let e=r.sequence+1,t=(o.updateLastMessage(r),o.updateNextMessageSeq(e),L.computeUnreadCount(o));o.updateUnreadCount(t),this._emitTopicUpdate(o)}}}_dispose(){var{notificationCenter:e,InnerEvent:{MESSAGE_PUSH:t,TOPIC_NEW_MESSAGE:s,TOPIC_MESSAGE_DELETED:r,TOPIC_MESSAGE_REVOKED:i,TOPIC_MESSAGE_MODIFIED:n,DESTROY:o}}=this._core,{TOPIC_AT_TIPS:a,TOPIC_LATEST_MESSAGE:u}=e["InnerEventSubType"];e.unSubscribeInnerEvent(s,this._handleNewMessage,this),e.unSubscribeInnerEvent(r,this._handleMessageDeleted,this),e.unSubscribeInnerEvent(i,this._handleMessageRevoked,this),e.unSubscribeInnerEvent(n,this._handleMessageModified,this),e.unSubscribeInnerEvent(t,a,this._handleTopicAtTips,this),e.unSubscribeInnerEvent(t,u,this._handleLatestMessage,this),e.unSubscribeInnerEvent(o,this._dispose,this)}},ul=new class{constructor(){this._name="TopicOperationHandler"}init(e){var{notificationCenter:t,InnerEvent:{MESSAGE_PUSH:s,DESTROY:r}}=this._core=e,{TOPIC_TIPS_NOTIFICATION:i,TOPIC_SYSTEM_NOTIFICATION:n,TOPIC_MESSAGE_READ_SYNC:o}=t["InnerEventSubType"];t.subscribeInnerEvent(s,i,this._handleTopicTips,this),t.subscribeInnerEvent(s,n,this._handleTopicNotices,this),t.subscribeInnerEvent(s,o,this._handleTopicMessageReadSynced,this),t.subscribeInnerEvent(r,this._dispose,this),e.ssoLog.debug(this._name+".init")}_handleTopicTips(e){var{GroupTips:t=[]}=e;for(let e=0;e<t.length;e++){var s=t[e];7!==s.MsgBody.OpType?8!==s.MsgBody.OpType?this._emitTopicTips(s):this._handleTopicProfileUpdated(s):this._handleMuteTimeUpdated(s)}}_handleMuteTimeUpdated(e){var{getCurrentUserID:t}=this._core["common"],{GroupInfo:{GroupId:s,TopicId:r},MsgBody:{MsgMemberInfo:i=[]}}=e;for(let e=0;e<i.length;e++){var{User_Account:n,ShutupTime:o}=i[e];if(n===t()&&0<=o){L.updateSelfInfo({groupID:s,topicID:r,selfInfo:{muteTime:o}});break}}}_handleTopicProfileUpdated(e){var{GroupInfo:{GroupId:e,TopicId:t},MsgBody:{MsgTopicNewInfo:{CustomString:s,ShutupAll:r,TopicFaceUrl:i,TopicIntroduction:n,TopicName:o,TopicNotification:a}}}=e,u=L.getTopic(e,t);u&&(u.updateTopic({groupID:e,topicID:t,customData:s,muteAllMembers:r,avatar:i,introduction:n,topicName:o,notification:a}),L.emitTopicUpdate(u))}_handleTopicNotices(e){var{GroupTips:t=[]}=e;for(let e=0;e<t.length;e++){var s=t[e],{MsgBody:{ReportType:r,TopicIdArray:i,MsgFlag:n},GroupInfo:{GroupId:o,TopicId:a}}=s;17===r?this._handleTopicCreated({groupID:o,topicID:a}):18===r?this._handleTopicDeleted({groupID:o,topicIDList:i}):20===r?this._handleMessageRemindTypeUpdated({groupID:o,topicID:a,messageRemindType:n}):this._emitTopicNotices(s)}}_handleTopicCreated(e){var{OuterEvent:t,notificationCenter:s}=this._core;L.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:i=[]}=e;L.deleteTopicList(r,i),s.emitOuterEvent(t.TOPIC_DELETED,{name:t.TOPIC_DELETED,data:e})}_handleMessageRemindTypeUpdated(e){var{groupID:e,topicID:t,messageRemindType:s}=e;L.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),L.updateSelfInfo({groupID:e,topicID:t,selfInfo:{readedSequence:s}}),L.clearGroupAtInfoList(e,t),L.markMessageAsRead(t,s),L.updateUnreadCount(e,t)})})}_emitTopicTips(e){var{message:{messageHelper:t,messageFactory:s},OuterConstant:r,OuterEvent:i,notificationCenter:n}=this._core,t=(e.MsgBody.MsgType=r.MSG_GRP_TIP,t.parseServerGroupMessage(e)),e=(t.flow="in",t.conversationType=r.CONV_GROUP,s.createMessage(t));e.setElement(t.elements),e.isSystemMessage=!0,n.emitOuterEvent(i.MESSAGE_RECEIVED,{name:i.MESSAGE_RECEIVED,data:[e]})}_emitTopicNotices(e){var{message:{messageHelper:t,messageFactory:s},OuterConstant:r,OuterEvent:i,notificationCenter:n}=this._core,t=(e.MsgBody.MsgType=r.MSG_GRP_SYS_NOTICE,t.parseServerGroupMessage(e)),e=(t.flow="in",t.conversationType=r.CONV_SYSTEM,t.conversationID=r.CONV_SYSTEM,s.createMessage(t));e.setElement(t.elements),e.isSystemMessage=!0,n.emitOuterEvent(i.MESSAGE_RECEIVED,{name:i.MESSAGE_RECEIVED,data:[e]})}_dispose(){var{notificationCenter:e,InnerEvent:{MESSAGE_PUSH:t,DESTROY:s}}=this._core,{TOPIC_TIPS_NOTIFICATION:r,TOPIC_SYSTEM_NOTIFICATION:i,TOPIC_MESSAGE_READ_SYNC:n}=e["InnerEventSubType"];e.unSubscribeInnerEvent(t,r,this._handleTopicTips,this),e.unSubscribeInnerEvent(t,i,this._handleTopicNotices,this),e.unSubscribeInnerEvent(t,n,this._handleTopicMessageReadSynced,this),e.unSubscribeInnerEvent(s,this._dispose,this)}},ll=new class{constructor(){this._name="GetJoinedCommunityHandler"}init(e){e=(this._core=e).helper;e.registerApi({apiName:"getJoinedCommunityList",context:this})}getJoinedCommunityList(){return I(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}}})}},cl=new class{constructor(){this._name="CreateTopicHandler"}init(e){e=(this._core=e).helper;e.registerApi({apiName:"createTopicInCommunity",context:this})}createTopicInCommunity(n){return I(this,void 0,void 0,function*(){let s="createTopicInCommunity",{utils:{isUndefined:e},common:{isTopic:t},helper:{ChatError:r}}=this._core,i=n["topicID"];if(!e(i)&&!t(i)){let e=new r({functionName:s,code:3021});throw console.error(this._name+`.${s} fail:`,e),e}try{let e=yield function(a,u){return I(this,void 0,void 0,function*(){var{groupID:e,topicID:t,topicName:s,avatar:r,notification:i,introduction:n,customData:o}=a;return u.common.buildAndSendPacket({servcmd:"million_group_open_http_svc.create_topic",data:{GroupId:e,TopicId:t,TopicName:s,FaceUrl:r,Notification:i,Introduction:n,CustomString:o}})})}(n,this._core),{TopicId:t=""}=e||{};return console.log(this._name+`.${s} ok, topicID:`+t),L.updateTopic([Object.assign(Object.assign({},n),{topicID:t})]),{code:0,data:{topicID:t}}}catch(e){throw console.error(this._name+`.${s} failed, error:`,e),e}})}},dl=new class{constructor(){this._name="DeleteTopicHandler"}init(e){e=(this._core=e).helper;e.registerApi({apiName:"deleteTopicFromCommunity",context:this})}deleteTopicFromCommunity(u){return I(this,void 0,void 0,function*(){var s="deleteTopicFromCommunity",{groupID:o,topicIDList:a=[]}=u;try{let e=yield function(s,r){return I(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:o,topicIDList:a},this._core),{DestroyResultItem:t=[]}=e||{},r=[],i=[],n=[];return t.forEach(e=>{var{TopicId:e,ErrorCode:t,ErrorInfo:s}=e;0===t?(r.push({topicID:e}),n.push(e)):i.push({topicID:e,code:t,message:s})}),0<n.length&&L.deleteTopicList(u.groupID,n),console.log(`${this._name}.${s} ok, groupID:${o} success:${r.length} fail:`+i.length),{code:0,data:{successTopicList:r,failureTopicList:i}}}catch(e){throw console.error(this._name+`.${s} failed, error:`,e),e}})}},pl=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 I(this,void 0,void 0,function*(){var{groupID:t,topicIDList:s=[]}=e,r=0===s.length;if(this._isFetchingFromCache(t,r)){let e=L.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}=L.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)&&0<=(t=parseInt(t,10))&&t<=3600?1e3*t:3e5}_getTopicListFromServer(l,c){return I(this,void 0,void 0,function*(){var r="_getTopicListFromServer",{isEmpty:i}=this._core["utils"],u=l["groupID"];try{let e=yield function(s,r){return I(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"]}})})}(l,this._core),{TopicAndSelfInfo:t=[]}=e||{},n=[],o=[],a=[],s=(this._convertTopicInfoList(t).forEach(e=>{var{topic:e,selfInfo:t,code:s,message:r}=e,i=e["topicID"];0===s?(n.push(Object.assign(Object.assign({},e),{selfInfo:t})),o.push(i)):a.push({topicID:i,code:s,message:r})}),L.updateTopic(n),L.updateTopicAtInfo(n),console.log(`${this._name}.${r} groupID:${u} from remote, success count:${o.length}, fail count:`+a.length),[]);return i(o)||(L.setTopicRequestInfo(u,{hasFetchedAllTopics:c,time:Date.now()}),s=L.getTopicList(u,o)),{code:0,data:{successTopicList:s,failureTopicList:a}}}catch(e){throw console.error(this._name+`.${r} failed, error:`,e),e}})}_convertTopicInfoList(e){let i=[];return e.forEach(e=>{var{TopicInfo:e={},SelfInfo:t={},ErrorCode:s,ErrorInfo:r}=e;i.push({code:s,message:r,topic:this._convertTopicInfo(e),selfInfo:this._convertSelfInfo(t)})}),i}_convertTopicInfo(e){var t,s,r,i,n,o,a,u,l,c,d,p=this._core["utils"]["isEmpty"];return p(e)?{}:({CreateTime:p,CustomString:e,FaceUrl:t,GroupId:s,LastMsgTime:r,NextMsgSeq:i,Introduction:n,Notification:o,ShutUpAllFlag:a,TopicId:u,TopicName:l,LastMsg:c,AtInfoList:d}=e,{createTime:p,customData:e,avatar:t,groupID:s,lastMessageTime:r,nextMessageSeq:i,introduction:n,notification:o,muteAllMembers:a,topicID:u,topicName:l,lastMsg:this._convertLastMsg(c),groupAtInfoList:this._convertAtInfoList({groupID:s,topicID:u,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:i,atInfoList:t=[]}=e;if(0===t.length)return[];let n=[];return t.forEach(e=>{var{AtFlagList:e,AtMsgSeq:t,From_Account:s}=e;n.push({groupID:r,topicID:i,groupAtType:e,sequence:t,from:s})}),n}_convertSelfInfo(e){var t,s,r,i=this._core["utils"]["isEmpty"];return i(e)?{}:({InheritGroupReceiveOption:i,MsgFlag:e,MsgSeq:t,NoUnreadSeqList:s,ShutUpTime:r}=e,{inheritGroupReceiveOption:i,messageRemindType:e,readedSequence:t,excludedUnreadSequenceList:s,muteTime:r})}},hl=new class{constructor(){this._name="UpdateTopicHandler"}init(e){e=(this._core=e).helper;e.registerApi({apiName:"updateTopicProfile",context:this})}updateTopicProfile(n){return I(this,void 0,void 0,function*(){var t="updateTopicProfile",{isUndefined:e}=this._core["utils"],{groupID:s,topicID:r,muteAllMembers:i}=n;e(n.muteAllMembers)||(n.muteAllMembers=!0===i?"On":"Off");try{return yield function(u,l){return I(this,void 0,void 0,function*(){var{groupID:e,topicID:t,topicName:s,avatar:r,notification:i,introduction:n,customData:o,muteAllMembers:a}=u;return l.common.buildAndSendPacket({servcmd:"million_group_open_http_svc.modify_topic",data:{GroupId:e,TopicId:t,TopicName:s,FaceUrl:r,Notification:i,Introduction:n,CustomString:o,ShutUpAllMember:a}})})}(n,this._core),console.log(this._name+`.${t} ok, topicID:`+r),L.updateTopic([n]),{code:0,data:{topic:L.getTopic(s,r)}}}catch(e){throw console.error(this._name+`.${t} failed, topicID:${r} error:`,e),e}})}},gl=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(c){return I(this,void 0,void 0,function*(){let{utils:{isEmpty:e},ssoLog:t,helper:{ChatError:r}}=this._core,s=c["conversationID"],i={code:0,data:{}},n=il(s),o=nl(n),a=L.getTopic(o,n),u=this._name+`.setMessageRead topicID:${n} conversationID:${s} unreadCount:`+((null==a?void 0:a.unreadCount)||0);if(i.successLog={message:u},!a)return i;if(e(a.groupAtInfoList)||this._deleteTopicAtTips(o,n),0===a.unreadCount)return i;var l=this._getLocalMessageMaxSequence(a);try{yield this._setTopicMessageRead(o,n,l)}catch(e){let{errorCode:t,errorInfo:s}=e;throw new r({functionName:"setMessageRead",code:t,message:s,moreMessage:u})}return Object.assign(Object.assign({},i),{successLog:{message:u+" lastMessageSequence:"+l}})})}_deleteTopicAtTips(n,o){return I(this,void 0,void 0,function*(){this._core.ssoLog.debug("_deleteTopicAtTips",this._name+`._deleteTopicAtTips groupID:${n} topicID:`+o);let e=L.getTopic(n,o);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 i=[...r];0===(i=r.filter(e=>!e.atTypeArray.includes(s))).length?L.clearGroupAtInfoList(n,o):(yield function(t,s){return I(this,void 0,void 0,function*(){var e=t["messageListToDelete"];return s.common.buildAndSendPacket({servcmd:"openim.deletemsg",data:{DelMsgList:e}})})}({messageListToDelete:i.map(e=>({From_Account:e.from,To_Account:t(),MsgSeq:e.__sequence,MsgRandom:e.__random,GroupId:e.groupID}))},this._core),this._core.ssoLog.debug(this._name+"._deleteTopicAtTips ok. count:"+r.length),L.clearGroupAtInfoList(n,o))}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 i=(null==(r=null==e?void 0:e.lastMessage)?void 0:r.lastSequence)||0;return s>i&&(console.log(`${this._name}._getLocalMessageMaxSequence update lastMessageSequence from ${i} to `+s),i=s),i}_setTopicMessageRead(e,t,s){return I(this,void 0,void 0,function*(){try{yield function(r,i){return I(this,void 0,void 0,function*(){var{groupID:e,topicID:t,lastMessageSequence:s}=r;return i.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),L.updateSelfInfo({groupID:e,topicID:t,selfInfo:{readedSequence:s}}),L.markMessageAsRead(t,s),L.updateUnreadCount(e,t)}catch(e){throw console.error(this._name+"._setTopicMessageRead fail:",e),e}})}},_l=new class{init(e){e.ssoLog.debug("TopicAction.init"),ll.init(e),cl.init(e),dl.init(e),pl.init(e),hl.init(e),gl.init(e)}};let ml={required:!0,rules:["string"],allowEmpty:!1},vl={createTopicInCommunity:{groupID:ml,topicName:ml},deleteTopicFromCommunity:{groupID:ml,topicIDList:{required:!1,rules:["array"],allowEmpty:!0}},getTopicList:{groupID:ml,topicIDList:{required:!1,rules:["array"],allowEmpty:!0}},updateTopicProfile:{groupID:ml,topicID:ml}},fl={getJoinedCommunityList:!0,createTopicInCommunity:!0,deleteTopicFromCommunity:!0,getTopicList:!0,updateTopicProfile:!0},Il=new class{constructor(){this.name="Topic"}install(e){el.init(e),L.init(e),al.init(e),ul.init(e),_l.init(e),e.helper.registerValidateConfig({auth:fl,params:vl})}};function El(e,t){return Math.round(Number(e)*Math.pow(10,t))/Math.pow(10,t)}let Cl="qualityStat",Sl="im-ssolog-quality-stat",Ml=(ol=ol||{},ol[ol.ONLINE=8]="ONLINE","networkRTT"),yl="messageE2EDelay",Tl="sendMessageC2C",Al="sendMessageGroup",Ol="sendMessageGroupAV",Dl="sendMessageRichMedia",Rl="cosUpload",Ll="messageReceivedGroup",Nl="messageReceivedGroupAVPush",bl="messageReceivedGroupAVPull",Gl={networkRTT:2,messageE2EDelay:3,sendMessageC2C:4,sendMessageGroup:5,sendMessageGroupAV:6,sendMessageRichMedia:7,messageReceivedGroup:8,messageReceivedGroupAVPush:9,messageReceivedGroupAVPull:10,cosUpload:11},Pl=[Tl,Al,Ol,Dl,Rl],wl=[Ll,Nl,bl],Ul=[Ml,yl,Tl,Al,Ol,Dl,Rl,Ll,Nl,bl],kl={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},Fl="quality_stat";var ql=new class{constructor(){this._messageStatsMap=new Map,this._userSideErrorCodes=new Set(Object.values(kl))}init(e){this._core=e,Object.values(Pl).forEach(e=>{this._messageStatsMap.set(e,{totalCount:0,successCount:0,failedCountOfUserSide:0,costSum:0,costCount:0,fileSizeSum:0})})}dispatchSendStats(e){var{name:e,message:t,error:s,startTs:r}=e,i=this._core.constants["SEND_MESSAGE_STAT"];switch(e){case i.TOTAL_COUNT:this._handleTotalCount(t);break;case i.SUCCESS_COUNT:this._handleSuccessCount(t);break;case i.FAILED_COUNT:this._handleFailedCount(t,s);break;case i.SEND_COST:this._handleSendCost(t,r)}}getStatResult(e){var t,s,r,i,n,o=this._messageStatsMap.get(e);return o&&0!==o.totalCount?({totalCount:t,successCount:s,failedCountOfUserSide:i}=o,r=El(s/t*100,2),n=El((i=s+i)/t*100,2),o=this._calcAverageValue(o,e),this._resetStat(e),{total_count:t,success_count_business:s,percent_business:r,success_count_platform:i,percent_platform:n,average_value:o}):null}_handleTotalCount(e){e=this._getSendMessageSpecifiedKey(e),e=e&&this._messageStatsMap.get(e);e&&e.totalCount++}_handleSuccessCount(e){e=this._getSendMessageSpecifiedKey(e),e=e&&this._messageStatsMap.get(e);e&&e.successCount++}_handleFailedCount(s,e){var t=null!=(t=null==e?void 0:e.code)?t:null==e?void 0:e.errorCode;if(this._isUserSideError(t)){let e=this._getSendMessageSpecifiedKey(s),t=e&&this._messageStatsMap.get(e);t&&t.failedCountOfUserSide++}}_handleSendCost(e,t){e=this._getSendMessageSpecifiedKey(e),e=e&&this._messageStatsMap.get(e);e&&(e.costSum+=Date.now()-t,e.costCount++)}_isUserSideError(e){return this._userSideErrorCodes.has(e)||120001<=e&&e<=13e4||10100<=e&&e<=10200}_getSendMessageSpecifiedKey(s){let{MSG_IMAGE:e,MSG_AUDIO:t,MSG_VIDEO:r,MSG_FILE:i,CONV_C2C:n,CONV_GROUP:o,GRP_AVCHATROOM:a}=this._core.OuterConstant;if([e,t,r,i].includes(s.type))return Dl;if(s.conversationType===n)return Tl;if(s.conversationType===o){let e=this._core.appStore["groupStore"],t=e.getGroup(s.to);if(t){let e=t["type"];return e===a?Ol:Al}}}_calcAverageValue(e,t){return 0===e.costCount?0:t===Rl?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)}},xl=new class{constructor(){this._lastCycleStats=new Map,this._currentCycleStats=new Map}init(e){var{OuterEvent:e,notificationCenter:t}=this._core=e;this._initStatsMap(),t.subscribeOuterEvent(e.MESSAGE_RECEIVED,this._onMessageReceived,this)}addMessageSequence(e){var t=this._getReceivedMessageSpecifiedKey(e),{utils:{isUndefined:s},OuterConstant:{CONV_GROUP:r},ssoLog:i}=this._core;s(t)||!this._currentCycleStats.has(t)?i.warn("addMessageSequence",Cl+".addMessageSequence invalid key:"+t):({conversationID:s,sequence:i}=e,e=s.replace(r,""),0!==(s=this._lastCycleStats.get(t)).size&&s.has(e)&&i>(r=s.get(e)).minSeq&&i<r.maxSeq?this._insertToLastCycle(i,r):this._addToCurrentCycle(t,e,i))}getStatResult(e){var t=this._lastCycleStats.get(e);if(!t||0===t.size)return this._transferCycleDataOptimized(e),null;let r=0,i=0;return t.forEach(e=>{var{sortedSequences:e,minSeq:t,maxSeq:s}=e;0<e.length&&(i+=e.length,r+=s-t+1)}),0===r?null:(this._transferCycleDataOptimized(e),{total_count:r,success_count_business:i,percent_business:El(i/r*100,2)})}reset(){this._lastCycleStats.clear(),this._currentCycleStats.clear()}dispose(){var{notificationCenter:e,OuterEvent:{MESSAGE_RECEIVED:t}}=this._core;e.unSubscribeOuterEvent(t,this._onMessageReceived,this),this.reset()}_initStatsMap(){Object.values(wl).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?bl:Ll):null}}_insertToLastCycle(e,t){t.dirty&&(t.sortedSequences.sort((e,t)=>e-t),t.dirty=!1);var s=this._findInsertPos(t.sortedSequences,e);t.sortedSequences.splice(s,0,e),t.minSeq=Math.min(t.minSeq,e),t.maxSeq=Math.max(t.maxSeq,e)}_findInsertPos(e,t){let s=0,r=e.length-1;for(;s<=r;){var i=Math.floor((s+r)/2);if(e[i]===t)return i;e[i]<t?s=i+1:r=i-1}return s}_addToCurrentCycle(e,t,s){let r=this._currentCycleStats.get(e).get(t);r?(r.sortedSequences.push(s),r.minSeq=Math.min(r.minSeq,s),r.maxSeq=Math.max(r.maxSeq,s),r.dirty=!0):(r={sortedSequences:[s],minSeq:s,maxSeq:s,dirty:!1},this._currentCycleStats.get(e).set(t,r))}},Vl=new class{constructor(){this._totalDelay=0,this._totalCount=0,this._countLessThan1s=0,this._countLessThan3s=0}init(e){var{OuterEvent:{MESSAGE_RECEIVED:e},notificationCenter:t}=this._core=e;t.subscribeOuterEvent(e,this._onMessageReceived,this)}addMessageDelay(e){var t=this._core.common["timeManager"],t=t.getServerTimeSeconds()-e;0<t&&(this._totalDelay+=t,this._totalCount++,t<=1?this._countLessThan1s++:t<=3&&this._countLessThan3s++)}getStatResult(){var e;return 0===this._totalCount?null:(e={total_count:this._totalCount,success_count_business:this._countLessThan1s,success_count_platform:this._countLessThan3s,percent_business:this._calculatePercentage(this._countLessThan1s,this._totalCount),percent_platform:this._calculatePercentage(this._countLessThan3s,this._totalCount),average_value:this._calculateAverageDelay(this._totalCount)},this.reset(),e)}reset(){this._totalDelay=0,this._totalCount=0,this._countLessThan1s=0,this._countLessThan3s=0}dispose(){var{notificationCenter:e,OuterEvent:{MESSAGE_RECEIVED:t}}=this._core;e.unSubscribeOuterEvent(t,this._onMessageReceived,this),this.reset()}_onMessageReceived(e){let{data:t=[]}=e,{MSG_GRP_TIP:s,MSG_GRP_SYS_NOTICE:r}=this._core["OuterConstant"],i=[s,r];t.forEach(e=>{!i.includes(e.type)&&0<e.clientTime&&this.addMessageDelay(e.clientTime)})}_calculateAverageDelay(e){return 0===e?0:El(this._totalDelay/e,1)}_calculatePercentage(e,t){return El(e/t*100,2)}},Bl=new class{init(e){this.core=e}},n=new class{constructor(){this.name="MessageQualityStat",this._reportIndex=0,this._wholePeriod=!1,this._pendingReports=[],this._failedLogsCache=new Map}install(e){var{helper:t,notificationCenter:s,InnerEvent:{QUALITY_STAT:r,LOGOUT:i,DESTROY:n},constants:{WORKFLOW_NAME:o,WORKFLOW_STEP:a}}=this._core=e;Bl.init(e),ql.init(e),xl.init(e),Vl.init(e),t.registerWorkflowStep(o.SYNC_SERVER_INFO_AFTER_LOGIN,a.QUALITY_REPORT,this.handleLoginSuccess,this),s.subscribeInnerEvent(r,this._handleQualityStat,this),s.subscribeInnerEvent(i,this._reset,this),s.subscribeInnerEvent(n,this._dispose,this)}handleLoginSuccess(){var{store:e,helper:t,utils:{isUndefined:s}}=this._core,e=(e.get("cloudConfig")||{})["q_rpt_interval"],s=s(e)?12e4:Number(e);t.taskScheduler.addTask({id:Fl,intervalMs:s,callback:this.report,context:this})}report(){this._wholePeriod=!0;var e=[...Ul.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&&ql.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:Gl[e],timestamp:Date.now(),network_type:ol.ONLINE,extension:""},Object.assign(Object.assign({},e),t))}_getStatResultByKey(e){switch(e){case yl:return Vl.getStatResult();case Tl:case Al:case Ol:case Dl:case Rl:return ql.getStatResult(e);case Ll:case Nl:case bl:return xl.getStatResult(e);default:return null}}_uploadQualityReports(t){return I(this,void 0,void 0,function*(){try{var r={header:this._core.common.getCommonHead(),quality:t};yield function(){var{common:e,channel:t}=Bl.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=Cl+"._cacheFailedLogs";let s=[...this._failedLogsCache.get(Sl)||[],...e];10<s.length&&(s=s.slice(s.length-10),console.log(t+" logs overflow, keeping last 10 items")),this._failedLogsCache.set(Sl,s),console.log(t+" count: "+s.length),this._pendingReports=[]}_reset(){var e=this._core["helper"];e.taskScheduler.removeTask(Fl)}_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(),Vl.dispose(),xl.dispose()}};let jl=new class{constructor(){this.name="OfflineMessageSynchronizer",this._lastMessageSequenceMapOnDisconnect=new Map}install(e){var{common:{workflowManager:t},constants:{WORKFLOW_NAME:s,WORKFLOW_STEP:r,InnerEvent:i}}=this._core=e;t.registerWorkflowStep(s.SYNC_SERVER_INFO_AFTER_RE_ONLINE,r.HISTORY_MESSAGE_RECOVER,this._syncOfflineMessage,this),e.notificationCenter.subscribeInnerEvent(i.SOCKET_DISCONNECTED,this._updateLastMessageSequenceMapOnDisconnect,this)}_syncOfflineMessage(e){let t=((null==e?void 0:e.result)||{})["conversationList"],{OuterConstant:s,utils:{isArray:r}}=this._core;if(r(t)){let e=t.filter(e=>e.type===s.CONV_GROUP&&e.groupProfile.type!==s.GRP_AVCHATROOM);return this._recoverGroupHistoryMessage(e)}}_recoverGroupHistoryMessage(e){return I(this,void 0,void 0,function*(){let i=this._core["OuterConstant"],n=[],o=[];return yield Promise.all(null==e?void 0:e.map(r=>I(this,void 0,void 0,function*(){var{groupProfile:{groupID:e}={},lastMessage:{lastSequence:t}={}}=r,e=""+i.CONV_GROUP+e,s=this._getLocalLastMessageSequence(e);this._shouldRecoverHistory({localLastMessageSequence:s,serverLastMessageSequence:t})&&(yield this._recoverHistoryForConversation({conversationID:e,localLastMessageSequence:s,serverLastMessageSequence:t,groupTipList:o})),n.push(e.replace(i.CONV_GROUP,""))}))),{recoverRevokeNoticeGroupIDList:n,groupTipList:o}})}_recoverHistoryForConversation(e){return I(this,arguments,void 0,function*({conversationID:I,localLastMessageSequence:E,serverLastMessageSequence:C,groupTipList:S}){try{let{utils:{isArray:e,isObject:t,isEmpty:s},OuterEvent:r,OuterConstant:i,notificationCenter:n,message:o,appStore:a,common:{getMessagePreviewText:u}}=this._core,l=C-E,c=Math.min(20,l),d={},p=yield o.messageHistory.getGroupRoamingMessagesByAnchor({conversationID:I,sequence:E+c,direction:i.Direction.FORWARD,count:c}),{nextReqMessageIDFromServer:h,hasNoMoreHistoryMessage:g,messageList:_,serverGroupTipList:m}=p,v=(e(m)&&S.push(...m),g&&h<0),f=[];if(e(_)&&(_.forEach(e=>{o.messageReceiver.groupMessageReceiver.updateMessageProfile(e),e.from===i.CONV_SYSTEM&&(e.isSystemMessage=!1),o.messageDataHandler.storeConversationMessage(e)&&!s(e.payload)&&(f.push(e),e._isExcludedFromLastMessage||(d.lastMessage=Object.assign({},e)))}),0<f.length)&&n.emitOuterEvent(r.MESSAGE_RECEIVED,{name:r.MESSAGE_RECEIVED,data:f}),!v&&0<_.length){let e=_[_.length-1].sequence;yield this._recoverHistoryForConversation({conversationID:I,localLastMessageSequence:e,serverLastMessageSequence:C,groupTipList:S})}t(d.lastMessage)&&(d.lastMessage.messageForShow=u(d.lastMessage.type,d.lastMessage.payload),a.conversationStore.updateConversation(I,d))}catch(E){this._core.ssoLog.error("_recoverHistoryForConversation","Recovery failed for conversation:"+I,{error:E})}})}_updateLastMessageSequenceMapOnDisconnect(){let e=this._core["message"],r=e.messageDataHandler.getContinuousMessagesByConversation();for(let[t,s]of r)if(!t.startsWith("C2C")){let e=Array.from(s.values());var i;0<(null==e?void 0:e.length)&&(i=e[e.length-1].sequence,this._lastMessageSequenceMapOnDisconnect.set(t,i))}}_getLocalLastMessageSequence(e){var t=this._core["message"];return this._lastMessageSequenceMapOnDisconnect.has(e)?this._lastMessageSequenceMapOnDisconnect.get(e):null==(e=(t=t.messageDataHandler.getLocalMessageList(e))[t.length-1])?void 0:e.sequence}_shouldRecoverHistory(e){var t,{localLastMessageSequence:e,serverLastMessageSequence:s}=e;return"number"==typeof e&&"number"==typeof s&&(t=s-e,0!==s)&&0<e&&1<=t&&t<300}},Kl,Wl;Kl=us.PROFESSIONAL,Wl=[t,dr,e,_,Er,n,jl,yi,_n,Bn,ua,ba,Gu,Ur,nu,vu,Zu,Il];var Hl=Object.freeze({__proto__:null,ChatError:m,WorkflowManager:h,buildAndSendPacket:Ks,get builtInPlugins(){return Wl},checkBusinessCapabilityBits:Fs,deepMerge:zs,getCurrentUserID:g,getErrorMessage:Ds,getMessagePreviewText:Js,isC2CConv:e=>X(e)&&e.slice(0,3)===es.CONV_C2C,isCommunity:xs,isGroupConv:e=>X(e)&&e.slice(0,5)===es.CONV_GROUP,isTopic:Vs,isUnlimitedAVChatRoom:function(){var e;return!(null==(e=k.store.get("instance"))||!e.unlimitedAVChatRoom)},liteChatInstanceMap:qs,registerInterceptor:Us,registerValidateConfig:ks,requireAuth:Rs,get sdkEdition(){return Kl},updateGroupAtInfo:(t,s)=>{var{CONV_AT_ME:r,CONV_AT_ALL:i,CONV_AT_ALL_AT_ME:n}=S;if(!function(t,e){let{CONV_AT_ME:s,CONV_AT_ALL:r,CONV_AT_ALL_AT_ME:i}=S,{groupID:n,sequence:o}=t,a=!1;return xs({groupID:n})&&e.forEach(e=>{e.messageSequence===o&&(e.atTypeArray.includes(s)&&t.groupAtType.includes(r)&&(e.atTypeArray=[i]),e.atTypeArray.includes(r)&&t.groupAtType.includes(s)&&(e.atTypeArray=[i],e.__random=t.__random,e.__sequence=t.__sequence),a=!0)}),a}(t,s)){let e=[...t.groupAtType];e.includes(r)&&e.includes(i)&&(e=[n]);r={from:t.from,groupID:t.groupID,topicID:t.topicID,messageSequence:t.sequence,atTypeArray:e,__random:t.__random,__sequence:t.__sequence};s.push(r)}},validateAndExecute:ws,validateParameters:Ls});class Yl{constructor(){this._builtInPlugins=new Set,this._externalPlugins=new Set}static getInstance(){return Yl._instance||(Yl._instance=new Yl),Yl._instance}static setInstance(e){Yl._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=ee(e)?e:[e]).findIndex(e=>"AVChatRoom"===(null==e?void 0:e.name)),i=-1<r?s.splice(r,1):[];s.forEach(e=>{this._isPluginInstalled(e.name)||(e&&Vt(e.install)?(t.add(e.name),Vt(e.getInstalledSubPlugins)?e.install(G.getInstance().exposeApiForPlugin(),i):e.install(G.getInstance().exposeApiForPlugin()),Vt(e.handleLoginSuccess)&&this._isLoggedIn()&&e.handleLoginSuccess()):Vt(e)?(t.add(e.name),e(G.getInstance().exposeApiForPlugin()),Vt(e.handleLoginSuccess)&&this._isLoggedIn()&&e.handleLoginSuccess()):console.warn('A plugin must either be a function or an object with an "install" function.'))})}_isPluginInstalled(e){return this._builtInPlugins.has(e)||this._externalPlugins.has(e)}_isLoggedIn(){var e;return!0===(null==(e=k.store.get("login"))?void 0:e.isLoggedIn)}}var F,$l,zl,N,b,Jl,Ql=new class{constructor(){this._conversationMap=new Map}getConversationMap(){return this._conversationMap}getConversation(e){return this._conversationMap.get(e)}updateConversation(e,t,s={emit:!0,needSort:!1}){let{emit:r,needSort:i}=s,n=this._conversationMap.get(e);n&&!ze(t)&&(Object.keys(t).forEach(e=>{n[e]=t[e]}),r)&&k.notificationCenter.emitInnerEvent(d.CONVERSATION_UPDATED,{needSort:i})}deleteConversation(e){this._conversationMap.has(e)&&(this._conversationMap.delete(e),k.notificationCenter.emitInnerEvent(d.CONVERSATION_UPDATED))}},Xl=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&&!ze(t)&&Object.keys(t).forEach(e=>{s[e]=t[e]})}},Zl=new class{constructor(){this._messagesByConversation=new Map}updateMessage(s,t,e){let r,{operation:i,updateUnreadCount:n=!0}=e,o=f(e,["operation","updateUnreadCount"]),a=[];for(let e of t){let t=null==(r=this._messagesByConversation.get(s))?void 0:r.get(e);if(!t)return!1;Object.keys(o).forEach(e=>{t[e]=o[e]}),a.push(t)}return this._emitMessageStoreOperationEvent(i,{conversationID:s,messageList:a,updateUnreadCount:n}),a}getMessagesByConversation(e){return[...(null==(e=this._messagesByConversation.get(e))?void 0:e.values())||[]]}getMessages(){return this._messagesByConversation}_emitMessageStoreOperationEvent(e,t){var s=t["conversationID"];Vs(s)?k.notificationCenter.emitInnerEvent(Qt[e],t):k.notificationCenter.emitInnerEvent(e,t)}},ec=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)}},tc=Object.freeze({__proto__:null,conversationStore:Ql,groupStore:Xl,messageStore:Zl,userStore:ec});class G{static getInstance(){return G._instance||(G._instance=new G),G._instance}static setInstance(e){G._instance=e}constructor(){this._experimentalApiMap={statTUIKeyFeatures:this.statKeyFeatureUsage.bind(this),setApplicationID:this.setApplicationID.bind(this)},this._apiHandlersMap={},this._apiMap={on:k.notificationCenter.subscribeOuterEvent.bind(k.notificationCenter),off:k.notificationCenter.unSubscribeOuterEvent.bind(k.notificationCenter),destroy:this.destroy.bind(this),callExperimentalAPI:this.callExperimentalAPI.bind(this),use:Yl.getInstance().installExternalPlugin.bind(Yl.getInstance()),registerPlugin:this.registerPlugin.bind(this),setLogLevel:this.setLogLevel.bind(this)}}registerPlugin(e){k.ssoLog.debug("registerPlugin",e)}statKeyFeatureUsage(e){k.ssoLog.debug("statTUIKeyFeatures",e)}setLogLevel(e){k.ssoLog.debug("setLogLevel",e),k.ssoLog.setLogLevel(e)}setApplicationID(e){k.store.set("instance",{applicationID:e})}getApiMap(){return this._apiMap}setApiMap(e){this._apiMap=e}registerApi(e){let{common:{timeManager:n},utils:{safeStringify:t}}=k,{apiName:o,context:s,methodName:a=o,matcher:r}=e;this._apiHandlersMap[o]||(this._apiHandlersMap[o]=[]),this._apiHandlersMap[o].push({context:s,methodName:a,matcher:r}),this._apiMap[o]&&1!==this._apiHandlersMap[o].length||(this._apiMap[o]=(...s)=>{let r=n.getServerTimeMs(),i=0;"login"===o&&(i=4),ps.includes(o)&&k.ssoLog.debug(o,o+" start params: "+t(s)),ws(a,s);for(let t of this._apiHandlersMap[o])if(!t.matcher||t.matcher(s))try{let e=t.context[t.methodName].bind(t.context)(...s);return this._isPromiseLike(e)?this._handleAsyncResult(e,o,i,r):(this._reportApiSuccessLog({result:e,apiName:o,eventType:i,startTime:r}),e)}catch(s){throw k.ssoLog.error(o,`${o} fail ${null==s?void 0:s.message})`,{error:s,costTime:n.getServerTimeMs()-r,eventType:i,method:o}),s}})}registerExperimentalAPI(e,t,s){this._experimentalApiMap[e]=t[s||e].bind(t)}destroy(){return I(this,void 0,void 0,function*(){var e,t;try{null!=(e=k.store.get("login"))&&e.isLogin&&(yield this._apiMap.logout()),k.notificationCenter.emitInnerEvent(d.DESTROY)}catch(e){console.debug("destroy error: ",e)}finally{k.notificationCenter.emitOuterEvent(jt.SDK_DESTROY,{SDKAppID:null==(t=k.store.get("instance"))?void 0:t.sdkAppId}),qs.clear(),Yl.getInstance().clear(),h.getInstance().destroy(),k.destroy()}})}exposeApiForClient(){return this._apiMap}exposeApiForPlugin(){return Object.assign(Object.assign({InnerEvent:d,InnerEventSubType:k.notificationCenter.InnerEventSubType,OuterEvent:jt,OuterConstant:S,SignalingEvent:Ht,helper:Object.assign(Object.assign(Object.assign({},k.utils),k.common),{registerApi:this.registerApi.bind(this),registerExperimentalAPI:this.registerExperimentalAPI.bind(this),registerInterceptor:Us,registerValidateConfig:ks,checkBusinessCapabilityBits:Fs,registerWorkflowStep:h.getInstance().registerWorkflowStep.bind(h.getInstance()),ChatError:m}),apiMap:this._apiMap},k),{constants:Object.assign(Object.assign({},_s),k.constants),common:Object.assign(Object.assign(Object.assign({},Hl),k.common),{workflowManager:h.getInstance()}),utils:k.utils,appStore:tc})}callExperimentalAPI(e,t){return this._experimentalApiMap[e]?this._experimentalApiMap[e](t):Promise.reject(new m({code:as.INVALID_OPERATION}))}_isPromiseLike(e){return null!==e&&"object"==typeof e&&"function"==typeof e.then}_handleAsyncResult(e,t,s,r){return e.then(e=>(this._reportApiSuccessLog({result:e,apiName:t,eventType:s,startTime:r}),e)).catch(e=>{throw k.ssoLog.error(t,`${t} fail ${null==e?void 0:e.message})`,{error:e,costTime:k.common.timeManager.getServerTimeMs()-r,eventType:s,method:t}),e})}_reportApiSuccessLog(e){let{result:t,apiName:s,startTime:r,eventType:i}=e;var e=k.common["timeManager"],{successLog:{message:n,moreMessage:o}={message:"",moreMessage:""}}=t||{},a=e.getServerTimeMs();"login"===s&&(r+=e.getTimeOffsetWithServer()),ps.includes(s)&&k.ssoLog.info(s,s+` success ${n} `+o,{costTime:a-r,eventType:i,message:n,moreMessage:o}),null!=t&&t.successLog&&delete t.successLog}}class sc{constructor(){this._latestLoginAt=0,this._latestSendOnlinePresenceRequestTime=0,this._helloInterval=120,this._customLoginInfo=""}init(){var{notificationCenter:e,store:t}=k;t.set("login",{isReady:!1}),G.getInstance().registerApi({apiName:"login",context:this}),G.getInstance().registerApi({apiName:"logout",context:this}),G.getInstance().registerApi({apiName:"getLoginUser",context:this}),G.getInstance().registerApi({apiName:"isReady",context:this}),G.getInstance().registerExperimentalAPI("setCustomLoginInfo",this),e.subscribeInnerEvent(d.RECONNECTED,this._reLogin,this),k.notificationCenter.subscribeInnerEvent(d.DESTROY,this._dispose,this)}login(u){return I(this,void 0,void 0,function*(){var e;let t=(k.store.get("instance")||{})["sdkEdition"];try{if(this._isLoginIn())return this._createRepeatLoginResponse();if(this._isLoginFrequencyExceeded())throw new m({functionName:"login",code:as.REPEAT_LOGIN});var s=yield this._performLogin(u),r=(this._validateAfterLogin(s),this._handleLoginSuccess(s),yield this._ensureAsyncComplete(),this._updateAndEmitSDKReady(),this._latestLoginAt=0,null==(e=k.channel.getSocketAdapter())?void 0:e.getId()),{appId:i,href:n}=k.store.get("instance")||{},{instanceID:o,customStatus:a}=s||{};return{code:0,data:s,successLog:{message:t,moreMessage:`socketID:${r} instanceID:${o} customStatus:${a} href: ${n} appId: `+i}}}catch(e){let t=e["errorCode"],s=(t!==as.REPEAT_LOGIN&&(this._latestLoginAt=0),new m({functionName:"login",code:t}));throw console.error(s),s}})}_reLogin(){return I(this,void 0,void 0,function*(){var e,t,s,r,i;try{this._isLoginIn()&&(t=yield Os(this._customLoginInfo))&&({instanceID:s,customStatus:r}=t,k.store.set("login",{statusInstanceId:s}),h.getInstance().executeWorkflow(p.SYNC_SERVER_INFO_AFTER_RE_ONLINE,{customStatus:r,statusType:Xt.USER_STATUS_ONLINE}),i=null==(e=k.channel.getSocketAdapter())?void 0:e.getId(),k.ssoLog.info("reLogin",`socketId:${i} instanceId:`+s))}catch(e){console.warn(e)}})}logout(){return I(this,arguments,void 0,function*(t=hs.USER_INITIATED){let e=k["ssoLog"];e.debug("logout","logout start logoutReason: "+t);try{yield this._performLogout(t),e.info("logout","logout success"),k.ssoLog.uploadSSOLogData()}catch(t){let e=t["errorCode"];throw new m({functionName:"logout",code:e})}finally{this._handleLogoutCompleted()}return{code:0,data:{}}})}getLoginUser(){return this._isLoginIn()?g():""}isReady(){var e;return null==(e=k.store.get("login"))?void 0:e.isReady}setCustomLoginInfo(e=""){this._customLoginInfo=e}_updateAndEmitSDKReady(){k.store.set("login",{isReady:!0}),setTimeout(()=>{k.notificationCenter.emitOuterEvent(jt.SDK_READY,{name:jt.SDK_READY})},1)}_updateAndEmitSDKNotReady(){k.store.set("login",{isReady:!1}),k.notificationCenter.emitOuterEvent(jt.SDK_NOT_READY,{name:jt.SDK_NOT_READY})}_validateAfterLogin(e){if(!e)throw new m({functionName:"login",message:"login response is empty"});var{tinyID:e,a2Key:t}=e||{};if(!e)throw new m({functionName:"login",code:as.NO_TINYID});if(!t)throw new m({functionName:"login",code:as.NO_A2KEY})}_createRepeatLoginResponse(){var e;return{code:0,data:{actionStatus:"OK",errorCode:0,errorInfo:Ds({code:"RepeatLogin",replacement1:null==(e=k.store.get("login"))?void 0:e.userId}),repeatLogin:!0}}}_performLogin(s){return I(this,void 0,void 0,function*(){var{userID:e,userSig:t}=s;return k.store.set("login",{userId:e,userSig:t}),this._latestLoginAt=Date.now(),Os(this._customLoginInfo)})}_ensureAsyncComplete(){return I(this,void 0,void 0,function*(){yield new Promise(e=>{setTimeout(()=>e(null),1)})})}_handleLoginSuccess(e){var t=k.common["timeManager"],{helloInterval:s,timeStamp:r,customStatus:i,purchaseBits:n}=e;t.calculateTimeOffsetWithServer(this._latestLoginAt,1e3*r),this._helloInterval=s||120,this._updateLoginStore(e),k.user.userStatus.setCustomStatus(i),h.getInstance().executeWorkflow(p.SYNC_SERVER_INFO_AFTER_LOGIN,{purchaseBits:n}),k.common.taskScheduler.addTask({id:vs,intervalMs:1e3*this._helloInterval,callback:this._sendOnlinePresenceRequest,context:this})}_performLogout(e){return function(s){return I(this,void 0,void 0,function*(){var e=s["logoutReason"],t="im_open_status.wslogout",e=k.common.generateProtocolData({servcmd:t,data:{wslogout_type:e,isWebUniapp:0}}),t=e.head.seq+t;return yield k.channel.sendPacket(e,{requestId:t})})}({logoutReason:e})}_handleLogoutCompleted(){this._updateAndEmitSDKNotReady(),this._reset(),h.getInstance().reset(),k.notificationCenter.emitInnerEvent("logout")}_updateLoginStore(e){var{a2Key:e,tinyID:t,instanceID:s,authKey:r}=e;k.store.set("login",{a2Key:e,tinyID:t,statusInstanceId:s,authKey:r,isLoggedIn:!0})}_sendOnlinePresenceRequest(){return I(this,void 0,void 0,function*(){this._latestSendOnlinePresenceRequestTime=Date.now();try{e="im_open_status.wshello",t=k.common.generateProtocolData({servcmd:e,data:{isWebUniapp:0}}),e=t.head.seq+e,yield k.channel.sendPacket(t,{requestId:e})}catch(e){k.ssoLog.warn("_sendOnlinePresenceRequest"," error:"+e.message)}var e,t})}_isLoginIn(){var e;return!0===(null==(e=k.store.get("login"))?void 0:e.isLoggedIn)}_isLoginFrequencyExceeded(){return Date.now()-this._latestLoginAt<=15e3}_reset(){k.common.taskScheduler.removeTask(vs),this._helloInterval=120,this._latestSendOnlinePresenceRequestTime=0,this._latestLoginAt=0,this._customLoginInfo="",k.store.clear("login"),k.store.set("login",{isReady:!1}),k.store.set("instance",{applicationID:0})}_dispose(){this._reset();var e=k["notificationCenter"];e.unSubscribeInnerEvent(d.RECONNECTED,this._reLogin,this),e.unSubscribeInnerEvent(d.DESTROY,this._dispose,this)}}let rc={login:{userID:{required:!0,rules:["string"],allowEmpty:!1},userSig:{required:!0,rules:["string"],allowEmpty:!1}}},ic={logout:!0};class nc{constructor(){this.loginAction=new sc,this.kickedOutHandler=new As,this.loginAction.init(),this.kickedOutHandler.init(),ks({auth:ic,params:rc})}}(b=F=F||{}).CONV_C2C="C2C",b.CONV_GROUP="GROUP",b.CONV_TOPIC="TOPIC",b.CONV_SYSTEM="@TIM#SYSTEM",(N=$l=$l||{}).MSG_PRIORITY_HIGH="High",N.MSG_PRIORITY_NORMAL="Normal",N.MSG_PRIORITY_LOW="Low",N.MSG_PRIORITY_LOWEST="Lowest",(t=zl=zl||{}).MSG_TEXT="TIMTextElem",t.MSG_CUSTOM="TIMCustomElem",t.MSG_LOCATION="TIMLocationElem",t.MSG_FACE="TIMFaceElem",t.MSG_IMAGE="TIMImageElem",t.MSG_AUDIO="TIMSoundElem",t.MSG_FILE="TIMFileElem",t.MSG_VIDEO="TIMVideoFileElem",t.MSG_GRP_TIP="TIMGroupTipElem",t.MSG_GRP_SYS_NOTICE="TIMGroupSystemNoticeElem",t.MSG_MERGER="TIMRelayElem";let oc={1:$l.MSG_PRIORITY_HIGH,2:$l.MSG_PRIORITY_NORMAL,3:$l.MSG_PRIORITY_LOW,4:$l.MSG_PRIORITY_LOWEST},ac=((dr=Jl=Jl||{}).IN="in",dr.OUT="out",{});function uc(e){var t,s,r;return e?(void 0===ac[e]?(t=("3"+(r=new Date).getHours()).slice(-2),s=("0"+r.getMinutes()).slice(-2),r=("0"+r.getSeconds()).slice(-2),ac[e]=parseInt([t,s,r,"0001"].join(""),10),console.log("autoIncrementIndex start index:"+ac[e])):ac[e]+=1,ac[e]):0}class lc{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=$l.MSG_PRIORITY_NORMAL,this._relayFlag=!1;var t,{clientTime:s=k.common.timeManager.getServerTimeSeconds()||0,senderTinyID:r,currentUser:i,needReadReceipt:n,isSupportExtension:o,customModerationConfigurationId:a,to:u,from:l,nick:c="",avatar:d="",time:p,messageControlInfo:h,tinyID:g,cloudCustomData:_="",messageLifeTime:m,messageVersion:v=0,conversationType:f,sequence:I,checkResult:E=0,isPlaceMessage:C=0,messageFlagBits:S,receiverList:M,isSystemMessage:y=!1,status:T=Kt.SUCCESS,revokeReason:A="",conversationSubType:O,clientSequence:D,protocol:R="JSON",revokerInfo:L={userID:"",nick:"",avatar:""},readReceiptInfo:N={readCount:void 0,unreadCount:void 0,isPeerRead:void 0,timestamp:0},random:b,groupProfile:G,atUserList:P,flow:w,isRead:U=!1}=e;this.clientTime=s,this.senderTinyID=r||g,this.needReadReceipt=!0===n||1===n,this.isSupportExtension=!0===o||1===o,this._cmConfigID=a,this.to=u,this.nick=c,this.avatar=d,this.protocol=R,this.random=void 0===b?(t=t||99999999,Math.round(Math.random()*t)):b,this.time=p||Math.ceil(Date.now()/1e3),this._isExcludedFromLastMessage=!(null==h||!h.excludedFromLastMessage),this._isExcludedFromUnreadCount=!(null==h||!h.excludedFromUnreadCount),this.isModified=!!v,this.cloudCustomData=_,this.messageLifeTime=m,this.from=l||null,this.sequence=I||0,this.conversationType=f||F.CONV_C2C,this.hasRiskContent=1<E,this.version=v,this.isPlaceMessage=C,this.isRevoked=2===C||8===S,this.isSystemMessage=y,this.readReceiptInfo=N,this.revokeReason=A,this.revokerInfo=L,this._receiverList=M,this.conversationSubType=O,this.revoker=(null==L?void 0:L.revoker)||"",this.clientSequence=D||I||0,this.status=T,this.atUserList=P||[],this.flow=w,this.isRead=U,this.reInitialize(i),this._initC2CReadReceiptInfo(e),this._extractGroupInfo(G)}getElements(){return this._elements}isOnlineMessage(){return 0===this.messageLifeTime}setElement(e){Array.isArray(e)?this._elements=e:this._elements=[e],this._updatePayloadAndType()}transformElementsToServerFormat(){return this._elements?Array.isArray(this._elements)?this._elements.map(e=>e.transformToServerFormat()):this._elements.transformToServerFormat():null}setRelayFlag(e){this._relayFlag=e}validateBeforeSend(){var e,t;return this._relayFlag?{isValid:!0}:0<(null==(e=this._elements)?void 0:e.length)?null==(t=null==(e=this._elements[0])?void 0:e.validateBeforeSend)?void 0:t.call(e):{isValid:!1}}_updatePayloadAndType(){this._elements[0]&&(this.payload=this._elements[0].content,this.type=this._elements[0].type)}_initC2CReadReceiptInfo(e){var{readReceiptSentByPeer:e,timestamp:t=0}=e;this.conversationType===F.CONV_C2C&&!0===this.needReadReceipt&&(this.readReceiptInfo.isPeerRead=1===e,this.readReceiptInfo.timestamp=t)}_extractGroupInfo(e){var t,s;e&&({From_AccountNick:e,From_AccountHeadurl:t,MsgFrom_AccountExtraInfo:s}=e,s=(s||{})["NameCard"],"string"==typeof e&&(this.nick=e),"string"==typeof t&&(this.avatar=t),"string"==typeof s)&&(this.nameCard=s)}reInitialize(e){e===this.from&&(this.isRead=!0),this._initSequence(e),this._concatConversationID(e),this.generateMessageID()}_concatConversationID(e){var t=this.conversationType;t!==F.CONV_SYSTEM?(e=t!==F.CONV_C2C||e===this.from?this.to:this.from,this.conversationID=e?""+t+e:null):this.conversationID=F.CONV_SYSTEM}_initSequence(e){0===this.clientSequence&&e&&(this.clientSequence=uc(e)),0===this.sequence&&this.conversationType===F.CONV_C2C&&(this.sequence=this.clientSequence)}generateMessageID(){this.from===F.CONV_SYSTEM&&(this.senderTinyID="144115198244471703"),this.ID=`${this.senderTinyID}-${this.clientTime}-`+this.random}setIsRead(e){this.isRead=e}}class cc{static parseServerPushElement(e){var{MsgContent:e={}}=e,{Data:e,Ext:t,Desc:s}=e;return new cc({data:e,description:s,extension:t})}constructor(e){this.type=zl.MSG_CUSTOM;var{data:e="",description:t="",extension:s=""}=e;this.content={data:e,description:t,extension:s}}transformToServerFormat(e){var{isMergerMessage:e=!1}=e||{},{data:e,description:t,extension:s}=e?this.payload:this.content;return{MsgType:this.type,MsgContent:{Data:e,Ext:s,Desc:t}}}validateBeforeSend(){let t=k.utils["isEmpty"],e=[this.content.data,this.content.description,this.content.extension].some(e=>!t(e));return{isValid:e,error:e?null:{message:"content can not be empty"}}}}class dc{static parseServerPushElement(e){var{MsgContent:e={Text:""}}=e,e=e["Text"];return new dc({text:e})}constructor(e){this.type=$t.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 pc=new class{constructor(){this._elementClassMap={[zl.MSG_CUSTOM]:cc,[zl.MSG_TEXT]:dc}}init(){G.getInstance().registerApi({apiName:"createCustomMessage",context:this}),G.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=Jl.OUT}=e,r=(k.store.get("login")||{})["userId"],t=(this._isSendByCurrentInstance({from:t,flow:s,currentUser:r})?this._updateWithSenderInfo(e):this._isMultiEndpointSyncMessage({from:t,flow:s,currentUser:r})&&(e.flow=Jl.OUT),Object.assign(Object.assign({},e),{currentUser:r}));return new lc(t)}createCustomMessage(t){let e=g(),s=this.createMessage(Object.assign(Object.assign({},t),{from:e})),r=this._elementClassMap[zl.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 dc({text:t}),s=g(),(e=k.message.messageFactory.createMessage(Object.assign(Object.assign({},e),{from:s}))).setElement(t),e):null}_updateWithSenderInfo(e){var{nick:t,avatar:s}=e,{userId:r,tinyID:i}=k.store.get("login")||{},n=ec.getUserProfile(r);return e.nick=t||(null==n?void 0:n.nick)||"",e.avatar=s||(null==n?void 0:n.avatar)||"",e.tinyID=e.tinyID||i||"",e.from=r,e.status=Kt.UNSENT,e.flow=Jl.OUT,e}_isMultiEndpointSyncMessage(e){var{from:e,flow:t,currentUser:s}=e;return e===s&&t===Jl.IN}_isSendByCurrentInstance(e){var{from:e,flow:t,currentUser:s}=e;return e===s&&t===Jl.OUT}};let hc={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}},gc={HonorImportance:{range:["LOW","NORMAL"],defaultValue:void 0},MeizuNotifyType:{range:[0,1],defaultValue:void 0}},_c={enableIOSBackgroundNotification:{range:[!0,!1],defaultValue:!1},interruptionLevel:{range:["passive","active","time-sensitive","critical"],defaultValue:"active"}};function mc(r,i){return Object.keys(i).forEach(e=>{var{range:t,defaultValue:s}=i[e];r[e]=t.includes(r[e])?r[e]:s}),r}function vc(e){return k.utils.isPlainObject(e)?{PushFlag:!0===e.disablePush?1:0,Title:e.title||"",Desc:e.description||"",Ext:e.extension||"",ApnsInfo:function(e){var{apnsInfo:e={},ignoreIOSBadge:t=!1,disableVoipPush:s}=e,{ignoreIOSBadge:r,disableVoipPush:i,enableIOSBackgroundNotification:n}=e=mc(e,_c),e=f(e,["ignoreIOSBadge","disableVoipPush","enableIOSBackgroundNotification"]),r=!0===r||!0===t?1:0;let o;return Q(s)||(o=!1===s?1:0),Q(i)||(o=!1===i?1:0),Object.assign(Object.assign({},e),{BadgeMode:r,IsVoipPush:o,ContentAvailable:n?1:0})}(e),AndroidInfo:function(e){var{androidInfo:e={},androidOPPOChannelID:t=""}=e,t=e.OPPOChannelID||t,{sound:s="",FCMChannelID:r=""}=e=mc(e,gc),e=f(e,["sound","FCMChannelID"]);return Object.assign(Object.assign({},e),{Sound:-1===(s=(e=s).lastIndexOf("."))?e:e.slice(0,s),OPPOChannelID:t,GoogleChannelID:r})}(e)}:hc}function fc(e){let{From_AccountHeadurl:t,From_AccountNick:s,IsNeedReadReceipt:r,IsPeerRead:i,IsSyncMsg:n,MsgBody:o,MsgClientTime:a,MsgLifeTime:u,MsgRandom:l,MsgSeq:c,MsgTimeStamp:d,SendMsgControl:p,SupportMessageExtension:h,TinyId:g,MsgCheckResult:_,CloudCustomData:m,MsgVersion:v,MsgFlagBits:f,RevokerInfo:I}=e,E,{From_Account:C,To_Account:S}=e;if(1===n){let e=S;S=C,C=e}if(I){let{Reason:e,Revoker_Account:t,Revoker_FromUin:s}=I;E={reason:e,revoker:t,revokerFromUin:s,userID:t}}return{from:C,avatar:t,nick:s,needReadReceipt:1===r,isSyncMessage:n,clientTime:a,messageLifeTime:u,random:l,sequence:c,time:d,messageControlInfo:{excludedFromLastMessage:1===(null==p?void 0:p.NoLastMsg),excludedFromUnreadCount:1===(null==p?void 0:p.NoUnread)},isSupportExtension:h,to:S,tinyID:g,checkResult:_,cloudCustomData:m,revokerInfo:E,messageVersion:v,messageFlagBits:f,readReceiptSentByPeer:i,elements:Cc(o)}}function Ic(e){var{From_Account:e,MsgBody:t,MsgClientTime:s,MsgRandom:r,MsgSeq:i,MsgTimeStamp:n,To_Account:o,MsgVersion:a,CloudCustomData:u}=e;return{from:e,clientTime:s,random:r,sequence:i,time:n,to:o,elements:Cc(t),messageVersion:a,cloudCustomData:u}}function Ec(e){let{ClientSeq:t,From_Account:s,GroupInfo:r,MsgBody:i,MsgClientTime:n,MsgRandom:o,MsgSeq:a,MsgTimeStamp:u,SendMsgControl:l,SupportMessageExtension:c,TinyId:d,CloudCustomData:p,MsgVersion:h,MsgCheckResult:g,NeedReadReceipt:_,IsPlaceMsg:m,RevokerInfo:v,GroupAtInfo:f}=e,I,E=$l.MSG_PRIORITY_NORMAL;if(Object.keys(oc).includes(String(e.MsgPriority))&&(E=oc[e.MsgPriority]),v){let{Reason:e,Revoker_Account:t,Revoker_FromUin:s}=v;I={reason:e,revoker:t,revokerFromUin:s,userID:t}}var C=function(e){let t=[];return Array.isArray(e)&&e.forEach(e=>{0===e.GroupAtAllFlag?t.push(e.GroupAt_Account):1===e.GroupAtAllFlag&&t.push(S.MSG_AT_ALL)}),t}(f);return{clientSequence:t,from:s,groupProfile:r,clientTime:n,priority:E,random:o,sequence:a,time:u,messageControlInfo:{excludedFromLastMessage:1===(null==l?void 0:l.NoLastMsg),excludedFromUnreadCount:1===(null==l?void 0:l.NoUnread)},isSupportExtension:c,tinyID:d,cloudCustomData:p,messageVersion:h,messageCheckResult:g,needReadReceipt:_,isPlaceMessage:m,revokerInfo:I,atUserList:C,elements:Cc(i),to:function(e){var{utils:{isEmpty:t},constants:{IS_TOPIC_MESSAGE:s}}=k,{ToGroupId:e,GroupInfo:{MillionGroupFlag:r=0,TopicId:i}={}}=e;return r!==s||t(i)?e:i}(e)}}function Cc(e){var t;return e?Array.isArray(e)?e.map(e=>{var t=k.message.messageFactory.getElementClass(e.MsgType);return null==t?void 0:t.parseServerPushElement(e)}):null==(t=k.message.messageFactory.getElementClass(e.MsgType))?void 0:t.parseServerPushElement(e):null}function Sc(e){var{From_Account:e,MsgBody:t,MsgClientTime:s,MsgRandom:r,MsgSeq:i,MsgTimeStamp:n,GroupId:o,TopicId:a,MsgVersion:u,CloudCustomData:l}=e;return{from:e,clientTime:s,random:r,sequence:i,time:n,groupID:o,topicID:a,elements:Cc(t),messageVersion:u,cloudCustomData:l}}function Mc({conversationUpdateFields:e,message:t}){var{conversationID:s,conversationType:r,conversationSubType:i,flow:n,_isExcludedFromUnreadCount:o,_isExcludedFromLastMessage:a}=t,a=a?"":t,t=!o&&n===Jl.IN;e.has(s)?(e.get(s).lastMessage=a,t&&e.get(s).unreadCount++):e.set(s,{conversationID:s,type:r,subType:i,unreadCount:t?1:0,lastMessage:a})}function yc(e){return e.filter(e=>{var t=!ze(null==e?void 0:e.getElements()),s=1===(null==e?void 0:e.isPlaceMessage);return t||k.ssoLog.error("emptyMessageBody",`from:${e.from} to:${e.to} sequence:`+e.sequence),t&&!s})}function Tc(e){var t=k.message["messageDataHandler"];return!t.isInMessageList(e)&&!t.isMessageSentByCurrentInstance(e)}var Ac=Object.freeze({__proto__:null,autoIncrementIndex:uc,filterValidMessages:yc,parseServerGroupMessage:Ec,parseServerPushC2CModifyMessage:Ic,parseServerPushGroupModifyMessage:Sc,parseServerPushMessage:fc,parseServerPushMessageElement:Cc,shouldStoreMessage:Tc,updateConversationFields:Mc});let Oc=k.utils["isPlainObject"];function Dc(e,t={}){let{onlineUserOnly:s,messageControlInfo:r}=t,i=t["offlinePushInfo"],n=(e.conversationType===F.CONV_C2C&&!0===s&&(i?i.disablePush=!0:i={disablePush:!0}),"");"string"==typeof e.cloudCustomData&&0<e.cloudCustomData.length&&(n=e.cloudCustomData);var o=[];if(r&&Oc(r)){let{excludedFromUnreadCount:e,excludedFromLastMessage:t,excludedFromContentModeration:s}=r;!0===e&&o.push("NoUnread"),!0===t&&o.push("NoLastMsg"),!0===s&&o.push("NoMsgCheck")}return{onlineUserOnly:s,cloudCustomData:n,messageControlInfo:o,offlinePushInfo:i}}function Rc(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 Lc(t,s){return I(this,void 0,void 0,function*(){var e=yield Ks((t.conversationType===F.CONV_GROUP?function(e,t){var s,{onlineUserOnly:r,cloudCustomData:i,messageControlInfo:n,offlinePushInfo:o}=Dc(e,t),a=JSON.parse(JSON.stringify(e.transformElementsToServerFormat()));let u;return ee(e._receiverList)&&0<e._receiverList.length&&(u=e._receiverList,50<e._receiverList.length)&&(u=e._receiverList.slice(0,50),console.warn("ReceiverListLimit")),{servcmd:"group_open_http_svc.send_group_msg",data:{From_Account:null==(s=k.store.get("login"))?void 0:s.userId,GroupId:e.to,MsgBody:a,CloudCustomData:i,Random:e.random,MsgPriority:e.priority,ClientSeq:e.clientSequence,GroupAtInfo:e._groupAtInfoList,OnlineOnlyFlag:r?1:0,MsgClientTime:e.clientTime,OfflinePushInfo:vc(o),SendMsgControl:r?void 0:n,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:Rc(t)}}}:function(e,t){var s,{onlineUserOnly:r,cloudCustomData:i,messageControlInfo:n,offlinePushInfo:o}=Dc(e,t),r=!0===r?0:void 0,a=JSON.parse(JSON.stringify(e.transformElementsToServerFormat()));return{servcmd:"openim.sendmsg",data:{From_Account:null==(s=k.store.get("login"))?void 0:s.userId,To_Account:e.to,MsgBody:a,CloudCustomData:i,MsgSeq:e.sequence,MsgRandom:e.random,MsgLifeTime:r,From_AccountNick:e.nick,From_AccountHeadurl:e.avatar,SendMsgControl:0!==r?n:void 0,MsgClientTime:e.clientTime,IsNeedReadReceipt:!0===e.needReadReceipt?1:0,SupportMessageExtension:!0===e.isSupportExtension?1:0,IsRelayMsg:!0===e._relayFlag?1:0,CustomModerationConfigID:e._cmConfigID,OfflinePushInfo:vc(o),forbidCallbackControl:Rc(t)}}})(t,s));return e?{time:e.MsgTime,messageDropReason:e.MsgDropReason,sequence:e.MsgSeq}:null})}let Nc=k.utils["isPlainObject"],{MSG_AUDIO:bc,MSG_FILE:Gc,MSG_IMAGE:Pc,MSG_VIDEO:wc,MSG_MERGER:Uc}=S;class kc{init(){G.getInstance().registerApi({apiName:"sendMessage",context:this,matcher:e=>![bc,Gc,Pc,wc,Uc].includes(e[0].type)})}sendMessage(c,d){return I(this,void 0,void 0,function*(){let{TOTAL_COUNT:e,SEND_COST:o,SUCCESS_COUNT:a,FAILED_COUNT:t}=ds;if(!(c instanceof lc))throw new m({code:as.MSG_INSTANCE_REQUIRED});let s=c.validateBeforeSend();if(!s.isValid){let{code:e,message:t=""}=s.error||{};throw new m({code:e,message:t})}this._reportMessageSendQuality({name:e,message:c});let u=!1;var l=(k.message||{})["messageDataHandler"];try{let r=(d||{})["messageControlInfo"],i=null,n=(l.addRandomOfSentMessage(c.random),Date.now());if(c.conversationType===F.CONV_C2C?(u=!0===(null==d?void 0:d.onlineUserOnly),i=yield Lc(c,d)):c.conversationType===F.CONV_GROUP&&(yield this._validateBeforeSendGroupMessage(c),i=yield Lc(c,d)),i){let{messageDropReason:e,sequence:t,time:s}=i;if(this._updateNickAndAvatarOfSentMessageByMe(c),e&&this._logRateLimitInfo(c,t,e),this._reportMessageSendQuality({name:a,message:c}),this._reportMessageSendQuality({name:o,message:c,startTs:n}),!0===c.isResend){let e=l.findMessage(c.ID);e&&(k.ssoLog.debug("sendMessage","sendMessage resend ok. ID:"+e.ID),l.deleteConversationMessage(e))}return c.status=Kt.SUCCESS,c.time=s,c.conversationType===F.CONV_GROUP&&(c.sequence=t),u?c._onlineOnlyFlag=!0:(l.storeConversationMessage(c),this._applySentMessageControlInfo(c,r),this._emitOnlineMessageSent(c)),{code:0,data:{message:c}}}}catch(e){c.status=Kt.FAIL,l.removeRandomOfSentMessage(c.random);var r=(e||{})["errorCode"],i=(null==e?void 0:e.errorMessage)||(null==e?void 0:e.message)||"";throw this._hasRiskContent(r)&&(c.hasRiskContent=!0),u||this._isRejectedByRestApi(r)||l.storeConversationMessage(c),this._reportMessageSendQuality({name:t,message:c,error:e}),i=`type:${c.type} from:${c.from} to:${c.to} `+i,new m({code:r,message:i,data:{message:c}})}})}_hasRiskContent(e){return 80001===e||80004===e}_isRejectedByRestApi(e){return 10100<=e&&e<=10200||120001<=e&&e<=13e4}_emitOnlineMessageSent(e){var t=e._isExcludedFromLastMessage?"":e,{conversationID:s,conversationType:r}=e,i=Vs(s)?d.TOPIC_NEW_MESSAGE:d.NEW_MESSAGE;k.notificationCenter.emitInnerEvent(i,{result:{conversationUpdateFieldList:[{conversationID:s,type:r,message:e,lastMessage:t,unreadCount:0}]}})}_applySentMessageControlInfo(e,t){t&&Nc(t)&&(!0===t.excludedFromLastMessage&&(e._isExcludedFromLastMessage=!0),!0===t.excludedFromUnreadCount)&&(e._isExcludedFromUnreadCount=!0)}_logRateLimitInfo(e,t,s){e=`from:${e.from} to:${e.to} sequence:${t} messageDropReason:`+s;k.ssoLog.warn("messageDropReason",e)}_updateNickAndAvatarOfSentMessageByMe(e){var t=(k.message||{})["messageDataHandler"];let s=!1;var r,i=e["conversationID"],n=t.getLatestMsgSentByMe(i);n&&({nick:n,avatar:r}=n,s=n!==e.nick||r!==e.avatar||s)&&t.updateNickAndAvatarOfSentMessage({conversationID:i,latestNick:e.nick,latestAvatar:e.avatar,isSentByMe:!0})}_validateBeforeSendGroupMessage(i){return I(this,void 0,void 0,function*(){var{to:t,from:s}=i;let r=t,e=Xl.getGroup(r);if(xs({groupID:r})&&null!=e&&e.isSupportTopic)throw new m({code:as.MSG_SEND_GRP_WITH_TOPIC_FAIL});if(Vs(t)&&([r]=t.split(is.TOPIC),e=Xl.getGroup(r)),!e&&"function"==typeof(null==(t=G.getInstance().getApiMap())?void 0:t.getGroupProfile)){let e=yield G.getInstance().getApiMap().getGroupProfile({groupID:r});if((null==(t=null==(t=null==e?void 0:e.data)?void 0:t.group)?void 0:t.type)===S.GRP_AVCHATROOM){let e=Ds({code:as.MSG_SEND_FAIL_NOT_IN_AV,replacement1:s,replacement2:r});throw new m({code:as.MSG_SEND_FAIL_NOT_IN_AV,message:e})}}return!0})}_reportMessageSendQuality(e){k.notificationCenter.emitInnerEvent(d.QUALITY_STAT,{label:cs.MESSAGE_SEND_SUCCESS_RATE,data:e})}}class Fc{constructor(e){this.value=e,this.next=null}}class qc{constructor(e){this.head=null,this.tail=null,this.size=0,this.capacity=e}append(e){this.size>=this.capacity&&this.removeHead();e=new Fc(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 xc=new class{constructor(){this._sparseMessagesByConversation=new Map,this._latestMessageSentByPeerMap=new Map,this._latestMessageSentByMeMap=new Map,this._randomOfSentMessageList=new qc(100)}init(){k.notificationCenter.subscribeInnerEvent(d.LOGOUT,this._reset,this),k.notificationCenter.subscribeInnerEvent(d.DESTROY,this._dispose,this)}get _messagesByConversation(){return Zl.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 u;if(this._messagesByConversation.has(a)||this._sparseMessagesByConversation.has(a)){let e=this._getUniqueIdOfMessage(t),o=this._getMessageFromLocalMessage(a,e);if(o){let{messageVersion:s,elements:r,cloudCustomData:i,checkResult:e=0}=t,n=1<e;if(console.log(`conversationToMessageMap modifyConversationMessage localVersion:${o.version} remoteVersion:`+s),o.version<s){let e=this._getUniqueIdOfMessage(o),t=Je(r);return null!=(u=this._messagesByConversation.get(a))&&u.has(e)?Zl.updateMessage(a,[e],{isModified:!0,version:s,_elements:t,payload:t[0].content,type:t[0].type,cloudCustomData:i,hasRiskContent:n,operation:zt.modify}):(o.version=s,o._elements=t,o.payload=o._elements[0].content,o.type=o._elements[0].type,o.cloudCustomData=i,o.isModified=!0,o.hasRiskContent=n),{isUpdated:!0,message:o}}return{isUpdated:!1,message:o}}}return{isUpdated:!1,message:null}}_getMessageFromLocalMessage(e,s){var t;if(this._messagesByConversation.has(e))return null==(t=this._messagesByConversation.get(e))?void 0:t.get(s);if(this._sparseMessagesByConversation.has(e)){let t=[...this._sparseMessagesByConversation.get(e).values()];for(let e=0;e<t.length;e++)if(this._getUniqueIdOfMessage(t[e])===s)return t[e]}return null}findMessage(t){let s=null,e=Array.from(this._messagesByConversation.values());for(var r of e)if(s=Array.from(r.values()).find(e=>e.ID===t)||null)break;if(!s){let e=Array.from(this._sparseMessagesByConversation.values());for(var i of e)if(s=i.get(t)||null,s)break}return s}deleteConversationMessageList(e){this._messagesByConversation.has(e)&&(this._messagesByConversation.delete(e),this._latestMessageSentByMeMap.delete(e),this._latestMessageSentByPeerMap.delete(e)),this._sparseMessagesByConversation.has(e)&&this._sparseMessagesByConversation.delete(e)}revokeMessage({conversationID:t,sequence:s,random:r,revoker:i}){let e=this._messagesByConversation.get(t),n=null;if(e){var o=Array.from(e.values());if(n=this._findMessageBySequenceAndRandom({messageList:o,random:r,sequence:s})){let e=this._getUniqueIdOfMessage(n);return Zl.updateMessage(t,[e],{isRevoked:!0,revoker:i,operation:zt.revoke}),n}}if(this._sparseMessagesByConversation.has(t)){let e=Array.from(this._sparseMessagesByConversation.get(t).values());if(n=this._findMessageBySequenceAndRandom({messageList:e,random:r,sequence:s}))return n.isRevoked=!0,n.revoker=i,n}}_findMessageBySequenceAndRandom({messageList:t,sequence:s,random:r}){for(let e=0;e<t.length;e+=1){var i=t[e];if(i.sequence===s&&(Q(r)||i.random===r))return i}return null}prependLocalMessageList(e){let{messageList:s,conversationID:t}=e;if(0===s.length)return[];var r=[],i=[],n=this._messagesByConversation.get(t)||new Map;for(let t of s){let e=this._getUniqueIdOfMessage(t);n.has(e)||(r.push(t),i.push([e,t]))}if(0<i.length){let e=new Map([...i,...n.entries()]);this._messagesByConversation.set(t,e),this._updateLatestMessageSentByMe(t),this._updateLatestMessageSentByPeer(t)}return r}storeSparseMessageList(r){if(0!==r.length){let e=r[0]["conversationID"],s=r.length;this._sparseMessagesByConversation.has(e)||this._sparseMessagesByConversation.set(e,new Map);var i=this._sparseMessagesByConversation.get(e);for(let t=0;t<s;t++){let e=r[t];i.has(e.ID)||i.set(e.ID,e)}}}_updateLatestMessageSentByMe(t){var e,s=Array.from((null==(e=this._messagesByConversation.get(t))?void 0:e.values())||[]);if(0!==s.length)for(let e=s.length-1;0<=e;e--)if("out"===s[e].flow){this._setLatestMsgSentByMe(t,s[e]);break}}_updateLatestMessageSentByPeer(t){var e,s=Array.from((null==(e=this._messagesByConversation.get(t))?void 0:e.values())||[]);if(0!==s.length&&t.startsWith("C2C"))for(let e=s.length-1;0<=e;e--)if("in"===s[e].flow){this._setLatestMsgSentByPeer(t,s[e]);break}}_getUniqueIdOfMessage(e){var{from:e,to:t,random:s,sequence:r,time:i}=e;return e+`-${t}-${s}-${r}-`+i}_setLatestMsgSentByPeer(e,t){this._latestMessageSentByPeerMap.set(e,t)}_setLatestMsgSentByMe(e,t){this._latestMessageSentByMeMap.set(e,t)}getLatestMsgSentByPeer(e){return this._latestMessageSentByPeerMap.get(e)}getLatestMsgSentByMe(e){return this._latestMessageSentByMeMap.get(e)}addRandomOfSentMessage(e){this._randomOfSentMessageList.append(e)}removeRandomOfSentMessage(e){this._randomOfSentMessageList.delete(e)}updateNickAndAvatarOfSentMessage(e){let{conversationID:t="",latestAvatar:n,latestNick:o,isSentByMe:s=!0}=e,r=this._messagesByConversation.get(t);if(r){let e=Array.from(r.values()),i=s?"out":"in";e.forEach(e=>{var{nick:t,avatar:s,flow:r}=e;r===i&&(t!==o&&(e.nick=o),s!==n)&&(e.avatar=n)})}}isInMessageList(e){var t=e["conversationID"];return!!t&&!!this._messagesByConversation.has(t)&&(e=this._getUniqueIdOfMessage(e),null==(t=this._messagesByConversation.get(t))?void 0:t.has(e))}isMessageSentByCurrentInstance(e){e=e.random;return this._randomOfSentMessageList.has(e)}getContinuousMessagesByConversation(){return this._messagesByConversation}getLocalMessageList(e){e=this._messagesByConversation.get(e);return e?[...e.values()]:[]}getSparseMessageList(e){e=this._sparseMessagesByConversation.get(e);return e?[...e.values()]:[]}_reset(){this._messagesByConversation.clear(),this._latestMessageSentByPeerMap.clear(),this._latestMessageSentByMeMap.clear(),this._randomOfSentMessageList.clear()}_dispose(){this._reset(),k.notificationCenter.unSubscribeInnerEvent(d.LOGOUT,this._reset,this),k.notificationCenter.unSubscribeInnerEvent(d.DESTROY,this._dispose,this)}};function Vc(e,t){var s,r,i,n,o,a,u,l=Ql.getConversation(e);null!=l&&l.lastMessage&&(l=l["lastMessage"],{lastTime:s,lastSequence:r,version:i}=l,{time:t,sequence:n,messageVersion:o,elements:a,cloudCustomData:u}=t,s===t)&&r===n&&i!==o&&(l.type=a[0].type,l.payload=a[0].content,l.messageForShow=Js(l.type,l.payload),l.cloudCustomData=u,l.version=o,Ql.updateConversation(e,{lastMessage:l}))}class Bc{init(){G.getInstance().registerApi({apiName:"modifyMessage",context:this})}modifyMessage(l){return I(this,void 0,void 0,function*(){let{to:r,payload:t,sequence:i,conversationType:n,random:o,time:a,from:u,type:s}=l;if(this._canModifyMessageElement(s)){let e=l.getElements();1<e.length&&(e[0].type=s,e[0].content=t)}try{let t=null,s;if(n===F.CONV_C2C?t=yield function(c){return I(this,void 0,void 0,function*(){let{from:e,to:t,version:s=0,sequence:r,random:i,time:n,type:o,cloudCustomData:a}=c,u={From_Account:e,To_Account:t,MsgVersion:s,MsgSeq:r,MsgRandom:i,MsgTime:n,MsgType:o,MsgBody:c.transformElementsToServerFormat(),CloudCustomData:a},l=yield Ks({servcmd:"openim.modify_c2c_msg",data:u});if(l){let{MsgBody:e,MsgVersion:t,CloudCustomData:s}=l;return{elements:Cc(e),messageVersion:t,cloudCustomData:s}}})}(l):n===F.CONV_GROUP&&(t=yield function(o){return I(this,void 0,void 0,function*(){let{to:e,version:t=0,sequence:s,cloudCustomData:r}=o,i={GroupId:e,MsgVersion:t,MsgSeq:s,MsgBody:o.transformElementsToServerFormat(),CloudCustomData:r},n=yield Ks({servcmd:"openim.modify_group_msg",data:i});if(n){let{MsgBody:e,MsgVersion:t,CloudCustomData:s}=n;return{elements:Cc(e),messageVersion:t,cloudCustomData:s}}})}(l)),t){let e=""+n+r;return r===g()&&n===F.CONV_C2C&&(e=""+n+u),s={conversationType:n,from:u,to:r,time:a,random:o,sequence:i,elements:null==t?void 0:t.elements,cloudCustomData:null==t?void 0:t.cloudCustomData,messageVersion:null==t?void 0:t.messageVersion,conversationID:e},this._handleModifyMessageSuccess(s),{code:0,data:{message:l},successLog:{message:"to:"+r}}}}catch(e){let t=(e||{})["errorCode"];throw new m({functionName:"modifyMessage",code:t})}})}_handleModifyMessageSuccess(e){var t=e["conversationID"],{isUpdated:s,message:r}=k.message.messageDataHandler.modifyConversationMessage(t,e);!0===s&&k.notificationCenter.emitOuterEvent(jt.MESSAGE_MODIFIED,{name:jt.MESSAGE_MODIFIED,data:[r]}),k.notificationCenter.emitInnerEvent(d.MESSAGE_MODIFIED,{conversationID:t,message:r}),Vc(t,e)}_canModifyMessageElement(e){return[zl.MSG_TEXT,zl.MSG_CUSTOM,zl.MSG_LOCATION,zl.MSG_FACE].includes(e)}}class jc{init(){var e=k["notificationCenter"],t=e["InnerEventSubType"];h.getInstance().registerWorkflowStep(p.RECEIVE_C2C_NEW_MESSAGE,o.HANDLE_C2C_NEW_MESSAGE,this._handleC2CMessagePush,this),h.getInstance().registerWorkflowStep(p.RECEIVE_C2C_NEW_MESSAGE,o.EMIT_C2C_MESSAGE_EVENT,this._emitMessageEventsAfterReceiveNewMessage,this),h.getInstance().registerWorkflowStep(p.SYNC_SERVER_INFO_AFTER_RE_ONLINE,o.EMIT_C2C_MESSAGE_EVENT,this._emitMessageEventsAfterSyncUnreadMessage,this),e.subscribeInnerEvent(d.MESSAGE_PUSH,t.C2C_REALTIME_MESSAGE,this._executeReceiverNewMessageWorkFlow,this),e.subscribeInnerEvent(d.MESSAGE_PUSH,t.C2C_MESSAGE_MODIFIED,this._handleC2CMessageModify,this),e.subscribeInnerEvent(d.DESTROY,this._dispose,this)}_executeReceiverNewMessageWorkFlow(e){h.getInstance().executeWorkflow(p.RECEIVE_C2C_NEW_MESSAGE,e)}_handleC2CMessagePush(e){let t=e.data||{},s=(k.message||{})["messageDataHandler"],r=[],i=new Map;return t.C2cMsgArray.forEach(e=>{e=this._generateC2CMessage(e);this._updateMessageProfile(e);let t=1===e.isModified;s.isMessageSentByCurrentInstance(e)?e.isModified=t:t=!1,e.isOnlineMessage()?(e._onlineOnlyFlag=!0,s.isMessageSentByCurrentInstance(e)||r.push(e)):Tc(e)&&(s.storeConversationMessage(e)&&Mc({conversationUpdateFields:i,message:e}),s.isMessageSentByCurrentInstance(e)&&!t||r.push(e))}),{conversationUpdateFieldList:[...i.values()],messages:r}}_emitMessageEventsAfterReceiveNewMessage(e){var{messages:e=[]}=(null==(e=e.result)?void 0:e[o.HANDLE_C2C_NEW_MESSAGE])||{};this._emitMessageEvents(e)}_emitMessageEventsAfterSyncUnreadMessage(e){var{messages:e=[]}=(null==(e=e.result)?void 0:e[o.UNREAD_MESSAGE_SYNC])||{};this._emitMessageEvents(e)}_emitMessageEvents(e){var t=(null==e?void 0:e.filter(e=>!0===(null==e?void 0:e.isModified)))||[],t=(0<t.length&&k.notificationCenter.emitOuterEvent("onMessageModified",{name:"onMessageModified",data:t}),null==e?void 0:e.filter(e=>!(null!=e&&e.isModified)));0<t.length&&k.notificationCenter.emitOuterEvent("onMessageReceived",{name:"onMessageReceived",data:t})}_generateC2CMessage(e){var t=F.CONV_C2C,e=fc(e),t=k.message.messageFactory.createMessage(Object.assign(Object.assign({},e),{conversationType:t,flow:Jl.IN})),e=e["elements"];return t.setElement(e),t}_updateMessageProfile(r){var e;let i=(k.message||{})["messageDataHandler"],t=null==(e=k.store.get("login"))?void 0:e.userId,{from:s,nick:n,avatar:o,conversationID:a=""}=r;if(s!==t){let s=i.getLatestMsgSentByPeer(a);if(s){let{nick:e,avatar:t}=s;Q(n)||Q(o)?(r.nick=X(e)?e:r.nick,r.avatar=X(t)?t:r.avatar):n===e&&o===t||(i.updateNickAndAvatarOfSentMessage({conversationID:a,latestNick:n,latestAvatar:o,isSentByMe:!1}),this._updateConversationUserProfile({conversationID:a,nick:n,avatar:o}))}}else{let e=i.getLatestMsgSentByMe(a);!e||n===e.nick&&o===e.avatar||i.updateNickAndAvatarOfSentMessage({conversationID:a,latestNick:n,latestAvatar:o,isSentByMe:!0})}}_updateConversationUserProfile(e){var{conversationID:e,nick:t,avatar:s}=e,{userProfile:r={}}=Ql.getConversation(e)||{};r.avatar===s&&r.nick===t||Ql.updateConversation(e,{userProfile:Object.assign(Object.assign({},r),{nick:t,avatar:s})})}_updateMessageListDueToModify(e){var t=e["conversationID"],{isUpdated:s,message:r}=k.message.messageDataHandler.modifyConversationMessage(t,e);!0===s&&k.notificationCenter.emitOuterEvent("onMessageModified",{name:"onMessageModified",data:[r]}),k.notificationCenter.emitInnerEvent("ModifyMessageSuccess",e),Vc(t,e)}_handleC2CMessageModify(e){e.C2cMsgModNotifys.forEach(e=>{var t=F.CONV_C2C,e=Ic(e),{to:s,from:r}=e;let i=""+t+s;s===(null==(s=k.store.get("login"))?void 0:s.userId)&&(i=""+t+r),e=Object.assign({conversationType:t,conversationID:i},e),this._updateMessageListDueToModify(e)})}_dispose(){var e=k["notificationCenter"],e=e["InnerEventSubType"];k.notificationCenter.unSubscribeInnerEvent(d.MESSAGE_PUSH,e.C2C_REALTIME_MESSAGE,this._handleC2CMessagePush,this),k.notificationCenter.unSubscribeInnerEvent(d.MESSAGE_PUSH,e.C2C_MESSAGE_MODIFIED,this._handleC2CMessageModify,this),k.notificationCenter.unSubscribeInnerEvent(d.DESTROY,this._dispose,this)}}class Kc{init(){var e=k["notificationCenter"],t=e["InnerEventSubType"];h.getInstance().registerWorkflowStep(p.RECEIVE_GROUP_NEW_MESSAGE,o.HANDLE_GROUP_NEW_MESSAGE,this._handleGroupMessagePush,this),h.getInstance().registerWorkflowStep(p.RECEIVE_GROUP_NEW_MESSAGE,o.EMIT_GROUP_MESSAGE_EVENT,this._emitMessageEvents,this),e.subscribeInnerEvent(d.MESSAGE_PUSH,t.GROUP_REALTIME_MESSAGE,this._executeReceiverNewMessageWorkFlow,this),e.subscribeInnerEvent(d.MESSAGE_PUSH,t.GROUP_MESSAGE_MODIFIED,this._handleGroupMessageModify,this),e.subscribeInnerEvent(d.DESTROY,this._dispose,this)}_executeReceiverNewMessageWorkFlow(e){this._canExecuteReceiverNewMessageWorkFlow(e)&&h.getInstance().executeWorkflow(p.RECEIVE_GROUP_NEW_MESSAGE,e)}_handleGroupMessagePush(e){let t=e.data||{},s=k.message["messageDataHandler"],r=[],i=new Map,n=null==t?void 0:t.GroupMsgArray;return null!=n&&n.forEach(e=>{var t;1!==e.GroupInfo.NotVisible&&(e=this._generateGroupMessage(e),this.updateMessageProfile(e),t=1===e.isModified,s.isMessageSentByCurrentInstance(e)&&(e.isModified=t),e.isOnlineMessage()?(e._onlineOnlyFlag=!0,s.isMessageSentByCurrentInstance(e)||r.push(e)):Tc(e)&&s.storeConversationMessage(e)&&(r.push(e),Mc({conversationUpdateFields:i,message:e})))}),{conversationUpdateFieldList:[...i.values()],messages:r}}_emitMessageEvents(e){var e=((null==(e=e.result)?void 0:e[o.HANDLE_GROUP_NEW_MESSAGE])||{})["messages"],t=(null==e?void 0:e.filter(e=>!0===(null==e?void 0:e.isModified)))||[],t=(0<t.length&&k.notificationCenter.emitOuterEvent("onMessageModified",{name:"onMessageModified",data:t}),(null==e?void 0:e.filter(e=>!(null!=e&&e.isModified)))||[]);0<t.length&&k.notificationCenter.emitOuterEvent("onMessageReceived",{name:"onMessageReceived",data:t})}_generateGroupMessage(e){var t=F.CONV_GROUP,e=Ec(e),t=k.message.messageFactory.createMessage(Object.assign(Object.assign({},e),{conversationType:t,flow:Jl.IN})),e=e["elements"];return t.setElement(e),t}updateMessageProfile(i){var e;let t=(k.message||{})["messageDataHandler"],s=null==(e=k.store.get("login"))?void 0:e.userId,{from:r,nick:n,avatar:o,conversationID:a="",_elements:u}=i;if(r===s){let e=t.getLatestMsgSentByMe(a);!e||n===e.nick&&o===e.avatar||t.updateNickAndAvatarOfSentMessage({conversationID:a,latestNick:n,latestAvatar:o,isSentByMe:!0})}else if(r===S.CONV_SYSTEM){let{operationType:e,memberInfoList:t,operatorInfo:s}=u,r={};if(ze(t)?ze(s)||(r=s):[ns.JOINED,ns.KICKED,ns.ADMIN_SET,ns.ADMIN_CANCELED].includes(e)&&(r=Object.assign({},t[0])),!ze(r)){let{nick:e="",avatar:t=""}=r;i.nick=e,i.avatar=t}}}_updateMessageListDueToModify(e){var t=e["conversationID"],{isUpdated:s,message:r}=k.message.messageDataHandler.modifyConversationMessage(t,e);!0===s&&k.notificationCenter.emitOuterEvent("onMessageModified",{name:"onMessageModified",data:[r]}),Vc(t,e)}_handleGroupMessageModify(e){e.GroupMsgModNotifys.forEach(e=>{var t=F.CONV_GROUP,{topicID:s,groupID:r}=e=Sc(e),s=s||r,e=Object.assign({conversationType:t,conversationID:""+t+s,to:s},e);this._updateMessageListDueToModify(e)})}_dispose(){var e=k["notificationCenter"],{GROUP_REALTIME_MESSAGE:t,GROUP_MESSAGE_MODIFIED:s}=e["InnerEventSubType"];e.unSubscribeInnerEvent(d.MESSAGE_PUSH,t,this._handleGroupMessagePush,this),e.unSubscribeInnerEvent(d.MESSAGE_PUSH,s,this._handleGroupMessageModify,this),e.unSubscribeInnerEvent(d.DESTROY,this._dispose,this)}_canExecuteReceiverNewMessageWorkFlow(e){var{GroupId:e,GroupType:t}=(null==(e=null==(e=null==e?void 0:e.GroupMsgArray)?void 0:e[0])?void 0:e.GroupInfo)||{},t=t===rs.GRP_AVCHATROOM;return!(!Xl.getGroup(e)&&t)}}var Wc=new class{constructor(){this.c2cMessageReceiver=new jc,this.groupMessageReceiver=new Kc}init(){this.c2cMessageReceiver.init(),this.groupMessageReceiver.init()}};let Hc={createCustomMessage:{to:{required:!0,rules:["string"],allowEmpty:!1},conversationType:{required:!0,rules:["string"],allowEmpty:!1},payload:{required:!0,rules:["object"],allowEmpty:!1},cloudCustomData:{required:!1,rules:["string"],allowEmpty:!1},priority:{required:!1,rules:["string"],allowEmpty:!1},customModerationConfigurationID:{required:!1,rules:["string"],allowEmpty:!1}},sendMessage:[{key:"message",required:!0,rules:["object"],allowEmpty:!1},{key:"options",required:!1,rules:["object"],allowEmpty:!1}],createTextMessage:{to:{required:!0,rules:["string"],allowEmpty:!1},conversationType:{required:!0,rules:["string"],allowEmpty:!1,customValidator:e=>!(!e.startsWith("C2C")&&!e.startsWith("GROUP"))||"conversationType is invalid."},payload:{required:!0,rules:["object"],allowEmpty:!1,customValidator:e=>{return"string"==typeof(null==e?void 0:e.text)&&("string"!=typeof e.text||0!==(null==(e=null==e?void 0:e.text)?void 0:e.length))||"payload.text must be a string"}}}},Yc={createCustomMessage:!0,sendMessage:!0,modifyMessage:!0};var $c=new class{getGroupRoamingMessagesByAnchor(i){return I(this,void 0,void 0,function*(){try{var{conversationID:t,count:s,direction:u,sequence:l,messageSequenceList:e,getType:r}=i,c=t.replace(es.CONV_GROUP,""),d=[];let a=l;if(u===Wt.BACKWARD){if("number"!=typeof l)return{messageList:[],hasNoMoreHistoryMessage:!1,nextReqMessageIDFromServer:""};a=l+s-1}var p=yield function(n){return I(this,void 0,void 0,function*(){var{groupID:e,count:t,messageSequence:s,messageSequenceList:r,getType:i}=n,e={GroupId:e,ReqMsgNumber:t,WithRecalledMsg:1,Version:1,GetType:i};return s&&(e.ReqMsgSeq=s),ee(r)&&0<r.length&&(e.ReqMsgSeqList=r),yield Ks({servcmd:"group_open_http_svc.group_msg_get",data:e})})}({groupID:c,count:s,messageSequence:a,messageSequenceList:e,getType:r});if(p){let{RspMsgList:t=[],NextReqMsgSeq:e=0,IsFinished:s,InvisibleMsgSeq:r}=p,i=`groupID:${c} sequence:${l} reqSeq:${a} direction:${u} complete:${s} nextSequence:${e} remoteMsgCount:${t.length} invisibleSequenceList:`+r,n=[];for(let e=0;e<t.length;e++){var h=t[e],g=(h.From_Account===S.CONV_SYSTEM&&d.push(h),this._parseMessage(h));n.push(g)}n.reverse();let o=2===s;u===Wt.BACKWARD&&(o=n[n.length-1].sequence>=l);var _=yc(n);return k.ssoLog.info("getGroupRoamingMessagesByAnchor",i),{messageList:_,invisibleSequenceList:r,nextReqMessageIDFromServer:e,hasNoMoreHistoryMessage:o,serverGroupTipList:d}}}catch(e){var{errorCode:t,errorInfo:s}=e||{};throw new m({code:t,message:s})}})}_parseMessage(e){var t=es.CONV_GROUP,e=(4===e.Event&&(e.MsgBody.MsgType=S.MSG_GRP_TIP),Ec(e)),t=pc.createMessage(Object.assign(Object.assign({},e),{conversationType:t,flow:"in"}));return t.setElement(e.elements),t}};class zc{constructor(){this.messageHelper=Ac,this.messageFactory=pc,this.messageSender=new kc,this.messageAction=new Bc,this.messageReceiver=Wc,this.messageDataHandler=xc,this.messageHistory=$c,this.messageSender.init(),this.messageFactory.init(),this.messageAction.init(),this.messageReceiver.init(),this.messageDataHandler.init(),ks({auth:Yc,params:Hc})}}let Jc="Tag_Profile_IM_",Qc={NICK:Jc+"Nick",GENDER:Jc+"Gender",BIRTHDAY:Jc+"BirthDay",LOCATION:Jc+"Location",SELFSIGNATURE:Jc+"SelfSignature",ALLOWTYPE:Jc+"AllowType",LANGUAGE:Jc+"Language",AVATAR:Jc+"Image",MESSAGESETTINGS:Jc+"MsgSettings",ADMINFORBIDTYPE:Jc+"AdminForbidType",LEVEL:Jc+"Level",ROLE:Jc+"Role"},Xc="Tag_Profile_Custom",Zc="profileCustomField",ed={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:[]},td=new Map([[Qc.NICK,"nick"],[Qc.GENDER,"gender"],[Qc.BIRTHDAY,"birthday"],[Qc.LOCATION,"location"],[Qc.SELFSIGNATURE,"selfSignature"],[Qc.ALLOWTYPE,"allowType"],[Qc.LANGUAGE,"language"],[Qc.AVATAR,"avatar"],[Qc.MESSAGESETTINGS,"messageSettings"],[Qc.ADMINFORBIDTYPE,"adminForbidType"],[Qc.LEVEL,"level"],[Qc.ROLE,"role"]]);var sd=new class{createProfile(e,t){let s={userID:e,profileCustomField:[]};return t.forEach(e=>{var{tag:e,value:t}=e;e&&-1<e.indexOf(Xc)?s.profileCustomField.push({key:e,value:t}):td.has(e)&&(s[td.get(e)]=t)}),Object.assign(Object.assign({},ed),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!==Zc&&s.push({tag:Qc[e.toUpperCase()],value:t[e]})}),t.profileCustomField&&ee(t.profileCustomField)&&t.profileCustomField.forEach(e=>{s.push({tag:e.key,value:e.value})}),s}normalizeProfileFields(e){let r={},i=[];return e.forEach(e=>{var{tag:t,value:s}=e;if(t&&-1<t.indexOf(Xc)&&i.push({key:t,value:s}),td.has(t)&&void 0!==s){let e=td.get(t);r[e]=s}}),0<i.length&&(r.profileCustomField=i),r}};let rd=k.common["generateProtocolData"];function id(r){return I(this,void 0,void 0,function*(){let e="profile.portrait_get_all",t={From_Account:g(),UserItem:[]};r.forEach(e=>{t.UserItem.push({CustomSequence:0,StandardSequence:0,To_Account:e})});var n=rd({servcmd:e,data:t}),s=n.head.seq+e,n=yield k.channel.sendPacket(n,{requestId:s});if(n){let{ActionStatus:e,ErrorCode:t,ErrorDisplay:s,ErrorInfo:r,UserProfileItem:i}=n,o=[];return i.map(e=>{var{To_Account:e,CustomSequence:t,ResultCode:s,ResultInfo:r,StandardSequence:i,ProfileItem:n}=e,n=sd.parseProfileItem(n);o.push({userId:e,customSequence:t,resultCode:s,resultInfo:r,standardSequence:i,profileItem:n})}),{actionStatus:e,errorCode:t,errorDisplay:s,errorInfo:r,userProfile:o}}})}function nd(e){return ec.getFriendMap().has(e)}let od=k.utils["isEmpty"];class ad{constructor(){this._strangerProfileMap=new Map}init(){G.getInstance().registerApi({apiName:"getMyProfile",context:this}),G.getInstance().registerApi({apiName:"getUserProfile",context:this}),G.getInstance().registerApi({apiName:"updateMyProfile",context:this}),this.createProfile=sd.createProfile.bind(sd);var e=k["notificationCenter"];h.getInstance().registerWorkflowStep(p.SYNC_SERVER_INFO_AFTER_LOGIN,o.USER_PROFILE_SYNC,this.getMyProfileCacheThenServer,this),e.subscribeInnerEvent(d.MESSAGE_PUSH,e.InnerEventSubType.PROFILE_MODIFIED,this._onProfileDataModify,this),e.subscribeInnerEvent(d.LOGOUT,this._reset,this),e.subscribeInnerEvent(d.DESTROY,this._dispose,this)}getMyProfile(){return I(this,void 0,void 0,function*(){try{var e,t=g(),s=yield id([t]);if(s)return e=this._handleProfileFormResponse(s)[0],ec.getUserProfileMap().set(t,e),{code:0,data:e}}catch(e){var{errorCode:s,errorInfo:t}=e;throw new m({functionName:"getMyProfile",code:s,message:t})}})}getUserProfile(u){return I(this,void 0,void 0,function*(){try{var t=u["userIDList"],{userIdListToRequest:e,profileFromCache:s}=this._filterRequestAndCacheUsers(t);if(0===e.length)return{code:0,data:s,successLog:{message:"userIDList.length:"+t.length}};1e3<e.length&&(k.ssoLog.warn("getUserProfile","userIdListToRequest.length > 1000"),e.length=1e3);var{data:r,error:i}=yield this._batchFetchUserProfiles(e),n=e.length,o=r.length,a=n-o;if(0===s.length&&n===a&&!od(i))throw i;if(ee(r)){r.forEach(e=>{(nd(e.userID)?ec.getUserProfileMap():this._strangerProfileMap).set(e.userID,e)});let e=r.concat(s);return{code:0,data:e,successLog:{message:`getUserProfile query:${n} success:${o} fail:${a} from cache:`+s.length}}}}catch(e){t=e["errorCode"];throw new m({functionName:"getUserProfile",code:t})}})}getMyProfileCacheThenServer(){return I(this,void 0,void 0,function*(){var e=g(),e=ec.getUserProfileMap().has(e);return e?{code:0,data:e}:this.getMyProfile()})}updateMyProfile(a){return I(this,void 0,void 0,function*(){let t=g(),s={};for(let e in a)void 0!==a[e]&&(s[e]=a[e]);var r=sd.convertParamsToProfile(s);try{let e={From_Account:t,ProfileItem:r};yield function(r){return I(this,void 0,void 0,function*(){let e="profile.portrait_set",t=rd({servcmd:e,data:r}),s=""+t.head.seq+e,i=yield k.channel.sendPacket(t,{requestId:s});if(i){let{ActionStatus:e,ErrorCode:t,ErrorDisplay:s,ErrorInfo:r}=i;return{actionStatus:e,errorCode:t,errorDisplay:s,errorInfo:r}}})}(e);var i=ec.getUserProfile(t),n=i?Object.assign(Object.assign({},i),s):sd.createProfile(t,r),o=!Bt(i,n,["lastUpdatedTime"]);return n.lastUpdatedTime=Date.now(),ec.getUserProfileMap().set(t,n),o&&this._emitProfileUpdated(n),{code:0,data:n,successLog:{message:"profileArray: "+k.utils.safeStringify(r)}}}catch(e){let{errorCode:t,errorInfo:s}=e;throw new m({functionName:"updateMyProfile",code:t,message:s})}})}updateMyNickAndAvatar(i){return I(this,void 0,void 0,function*(){var e=g(),t=Date.now(),s=ec.getUserProfile(e),r={};(r=s?Object.assign(s,i):sd.createProfile(e,i)).lastUpdatedTime=t,ec.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:sd.parseProfileList(s)}}();od(t)||({isProfileUpdated:t,profile:e}=this._handleProfileModified(t),t&&this._emitProfileUpdated(e))}_emitProfileUpdated(e){k.notificationCenter.emitInnerEvent(d.PROFILE_UPDATE,{name:d.PROFILE_UPDATE,data:[e]}),k.notificationCenter.emitOuterEvent(jt.PROFILE_UPDATED,{name:jt.PROFILE_UPDATED,data:[e]}),Ql.updateConversation("C2C"+(null==e?void 0:e.userID),{userProfile:e})}_dispose(){var e=k["notificationCenter"];e.unSubscribeInnerEvent(d.LOGOUT,this._reset,this),e.unSubscribeInnerEvent(d.MESSAGE_PUSH,e.InnerEventSubType.PROFILE_MODIFIED,this._onProfileDataModify,this),e.unSubscribeInnerEvent(d.DESTROY,this._dispose,this),this._reset()}_handleProfileModified(e){let{userId:t,profileList:s}=e,r=ec.getUserProfile(t);if(!(g()===t||nd(t)&&r))return{isProfileUpdated:!1,profile:null};let i=sd.normalizeProfileFields(s),n=Object.keys(i).some(e=>e===Zc?!Bt(r.profileCustomField,i.profileCustomField):r[e]!==i[e]);return n?(e=Date.now(),e=Object.assign(Object.assign(Object.assign({},r),i),{lastUpdatedTime:e}),ec.getUserProfileMap().set(t,e),{isProfileUpdated:n,profile:e}):{isProfileUpdated:!1,profile:r}}_filterRequestAndCacheUsers(e){let s=[],r=[];return e.forEach(e=>{var t=ec.getUserProfileMap().has(e);nd(e)&&t?r.push(ec.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&&!od(e.profileItem)),s=Date.now();return t.map(e=>{e=sd.createProfile(e.userId,e.profileItem);return e.lastUpdatedTime=s,e})}_isStrangerAndProfileValid(e){var t;return!nd(e)&&({lastUpdatedTime:e=0}=this._strangerProfileMap.get(e)||{},t=(null==(t=k.store.get("cloudConfig"))?void 0:t.stranger_profile_expiration_time)||6e5,Date.now()-e<=t)}_chunkUserIDList(s,r){return Array.from({length:Math.ceil(s.length/r)},(e,t)=>s.slice(t*r,(t+1)*r))}_batchFetchUserProfiles(e){return I(this,void 0,void 0,function*(){let t=[],r=[],i={};return this._chunkUserIDList(e,100).forEach(e=>{t.push(id(e))}),(yield Promise.allSettled(t)).forEach(s=>{if("fulfilled"===s.status){let e=s.value,t=this._handleProfileFormResponse(e);ee(t)&&r.push(...t)}else if("rejected"===s.status){let{code:e,message:t}=s.reason||{};i={errorCode:e,message:t}}}),{data:r,error:i}})}_reset(){ec.getUserProfileMap().clear(),this._strangerProfileMap.clear()}}var ud,ld,cd,dd=new Map,pd=["0","1","2","3","4","5","6","7","8","9","A","B","C","D","E","F"];for(let e=0,t=pd.length;e<t;e++)dd.set(e,pd[e]);function hd(e){if(!e)return"";var i=String(e).replace(/[=]+$/,"");let n="";if(i.length%4==1)return"";for(let e,t,s=0,r=0;t=i.charAt(r++);~t&&(e=s%4?64*e+t:t,s++%4)&&(n+=String.fromCharCode(255&e>>(-2*s&6))))t="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=".indexOf(t);try{return decodeURIComponent(escape(n))}catch(e){return console.warn(e),""}}let gd=k.utils["isEmpty"],_d=k.common["generateProtocolData"];function md(i){return I(this,void 0,void 0,function*(){var e,t,s="im_open_status.ws_get_user_status",r=_d({servcmd:s,data:{To_Account:i}}),s=r.head.seq+s,r=yield k.channel.sendPacket(r,{requestId:s});if(r)return{ErrorCode:s,ErrorInfo:r,ErrorList:e=[],UserStatusList:t=[]}=r,{errorCode:s,errorInfo:r,successUserList:t.map(e=>{var{To_Account:e,Status:t,CustomStatus:s}=e;return{userID:e,statusType:t,customStatus:hd(s)}}),failureUserList:e.map(e=>{var{To_Account:e,Invalid_Account:t,ErrorCode:s,ErrorInfo:r}=e;return{userID:gd(t)?e:t,code:s,message:r}})}})}class vd{constructor(){this._customStatus=""}init(){var e=k["notificationCenter"];G.getInstance().registerApi({apiName:"getUserStatus",context:this}),G.getInstance().registerApi({apiName:"setSelfStatus",context:this}),G.getInstance().registerApi({apiName:"subscribeUserStatus",context:this}),G.getInstance().registerApi({apiName:"unsubscribeUserStatus",context:this}),h.getInstance().registerWorkflowStep(p.SYNC_SERVER_INFO_AFTER_RE_ONLINE,o.USER_STATUS_UPDATE,this._onReOnline,this),e.subscribeInnerEvent(d.MESSAGE_PUSH,e.InnerEventSubType.USER_STATUS_UPDATE,this._onUserStatusUpdate,this),e.subscribeInnerEvent(d.LOGOUT,this._reset,this),e.subscribeInnerEvent(d.DESTROY,this._dispose,this)}setSelfStatus(s){return I(this,void 0,void 0,function*(){let e=g(),t=s["customStatus"];try{return yield function(i){return I(this,void 0,void 0,function*(){let e="im_open_status.ws_set_custom_status",t=_d({servcmd:e,data:{CustomStatus:i}}),s=""+t.head.seq+e,r=yield k.channel.sendPacket(t,{requestId:s});if(r){let{ErrorCode:e,ErrorInfo:t}=r;return{errorCode:e,errorInfo:t}}})}(t),this._customStatus=t,{code:0,data:{userID:e,statusType:1,customStatus:t},successLog:{message:"customStatus: "+t}}}catch(e){let{errorCode:t,errorInfo:s}=e;throw new m({functionName:"setSelfStatus",code:t,message:s})}})}getUserStatus(s){return I(this,void 0,void 0,function*(){var{userIDList:e=[]}=s;let t={};return this._isOnlyMeInArray(e)&&(t=this._getMyStatus()),t=yield this._getUserStatus(e),Object.assign(Object.assign({},t),{successLog:{message:"userIDList length: "+e.length}})})}setCustomStatus(e){e=hd(e);this._customStatus=e}subscribeUserStatus(i){return I(this,void 0,void 0,function*(){try{var{userIDList:e=[]}=i,t=(this._checkBusinessCapabilityBits("subscribeUserStatus"),this._getMaxUserCount("subscribe")),s=yield function(r){return I(this,void 0,void 0,function*(){var e=k["channel"],t="im_open_status.ws_status_subscribe",s=_d({servcmd:t,data:{To_Account:r}}),t=s.head.seq+t;return yield e.sendPacket(s,{requestId:t})})}(this._sliceUserIDList(e,t)),r=this._parseResponse(s);return{code:0,data:{failureUserList:r},successLog:{message:`userID length:${e.length} failCount: `+r.length}}}catch(e){t=e["errorCode"];throw new m({functionName:"subscribeUserStatus",code:t})}})}unsubscribeUserStatus(i){return I(this,void 0,void 0,function*(){try{this._checkBusinessCapabilityBits("unsubscribeUserStatus");var{userIDList:e=[]}=i,t=this._getMaxUserCount("unsubscribe"),s=yield function(r){return I(this,void 0,void 0,function*(){var e=k["channel"],t="im_open_status.ws_status_unsubscribe",s=0===r.length?{UnsubscribeAll:1}:{To_Account:r},s=_d({servcmd:t,data:s}),t=s.head.seq+t;return yield e.sendPacket(s,{requestId:t})})}(this._sliceUserIDList(e,t)),r=this._parseResponse(s);return{code:0,data:{failureUserList:r},successLog:{message:`userID length:${e.length} failCount: `+r.length}}}catch(e){t=e["errorCode"];throw new m({functionName:"unsubscribeUserStatus",code:t})}})}_onUserStatusUpdate(e){var{UserStatusList:e=[]}=e||{},e=e.map(e=>{var{To_Account:e,Status:t,CustomStatus:s}=e;return{userID:e,statusType:t,customStatus:hd(s)}});this._emitUserStatusUpdatedEvent(e)}_onReOnline(e){var e=hd(e.data.customStatus);this._customStatus!==e&&(this._customStatus=e,e={userID:g(),statusType:1,customStatus:e},this._emitUserStatusUpdatedEvent(e))}_emitUserStatusUpdatedEvent(e){k.notificationCenter.emitOuterEvent(jt.USER_STATUS_UPDATED,{name:jt.USER_STATUS_UPDATED,data:e})}_sliceUserIDList(e,t){return e.slice(0,t)}_parseResponse(e){var{ErrorList:e=[]}=e;return e.map(e=>{var{To_Account:e,Invalid_Account:t,ErrorCode:s,ErrorInfo:r}=e;return{userID:k.utils.isEmpty(t)?e:t,code:s,message:r}})}_checkBusinessCapabilityBits(e){if(!k.store.get("commercialConfig").get("USER_STATUS"))throw new m({functionName:e,code:as.NO_USE,replacement1:e})}_getMaxUserCount(e){var t=k.store.get("cloudConfig")||{},{key:e,default:s}={query:{key:"status_query_count",default:500},subscribe:{key:"status_sub_count",default:100},unsubscribe:{key:"status_unsub_count",default:100}}[e],t=t[e]||s;return parseInt(t,10)}_getMyStatus(){return{code:0,data:{successUserList:[{userID:g(),statusType:1,customStatus:this._customStatus}],failureUserList:[]}}}_getUserStatus(r){return I(this,void 0,void 0,function*(){try{this._checkBusinessCapabilityBits("getUserStatus");var t=this._getMaxUserCount("query"),{successUserList:e,failureUserList:s}=(yield md(this._sliceUserIDList(r,t)))||{};return{code:0,data:{successUserList:e,failureUserList:s}}}catch(e){t=e["errorCode"];throw new m({functionName:"getUserStatus",code:t})}})}_isOnlyMeInArray(e){var t=g();return 1===e.length&&-1<e.indexOf(t)}_dispose(){var e=k["notificationCenter"];e.unSubscribeInnerEvent(d.MESSAGE_PUSH,e.InnerEventSubType.USER_STATUS_UPDATE,this._onUserStatusUpdate,this),e.unSubscribeInnerEvent(d.DESTROY,this._dispose,this),e.unSubscribeInnerEvent(d.LOGOUT,this._reset,this),this._reset()}_reset(){this._customStatus=""}}let fd={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(Xc))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}}},Id={getMyProfile:!0,getUserProfile:!0,updateMyProfile:!0,setSelfStatus:!0,getUserStatus:!0,subscribeUserStatus:!0,unsubscribeUserStatus:!0};class Ed{constructor(){this.userProfile=new ad,this.userStatus=new vd,this.userProfile.init(),this.userStatus.init(),ks({auth:Id,params:fd})}}function Cd(t){var s=[];if(X(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}(e=ud=ud||{}).NOT_START="notStart",e.PENDING="pending",e.RESOLVED="resolved",e.REJECTED="rejected",(_=ld=ld||{})[_.C2C=1]="C2C",_[_.GROUP=2]="GROUP",(n=cd=cd||{})[n.C2C=8]="C2C",n[n.GROUP=2]="GROUP";class Sd{constructor(){this._name="SyncConversationHandler",this._pagingStatus=ud.NOT_START,this._pagingTimeStamp=0,this._pagingStartIndex=0,this._pagingPinnedTimeStamp=0,this._pagingPinnedStartIndex=0}init(){var e=k["notificationCenter"];h.getInstance().registerWorkflowStep(p.SYNC_SERVER_INFO_AFTER_RE_ONLINE,o.CONVERSATION_RECOVER,this._syncConversationList,this),h.getInstance().registerWorkflowStep(p.SYNC_SERVER_INFO_AFTER_LOGIN,o.CONVERSATION_LIST_SYNC,this._syncConversationListAfterLogin,this),e.subscribeInnerEvent(d.LOGOUT,this._reset,this),e.subscribeInnerEvent(d.DESTROY,this._dispose,this),k.ssoLog.debug(this._name+".init")}isSyncCompleted(){return this._pagingStatus===ud.RESOLVED}_syncConversationListAfterLogin(){return I(this,void 0,void 0,function*(){return this._pagingStatus=ud.NOT_START,this._pagingTimeStamp=0,this._pagingStartIndex=0,this._pagingPinnedTimeStamp=0,this._pagingPinnedStartIndex=0,this._syncConversationList()})}_syncConversationList(){return I(this,void 0,void 0,function*(){let{ssoLog:t,utils:{safeStringify:s}}=k;t.debug("_syncConversationList","start");try{let e=yield this._pagingGetConversationList(!0);this._pagingStatus=ud.RESOLVED;var{conversationList:r=[]}=e||{};return t.info("_syncConversationList","success count:"+r.length),e}catch(e){var{errorCode:r,errorInfo:i}=e,r=new m({code:r,message:i});t.error("_syncConversationList","fail "+s(e),{error:r})}})}_pagingGetConversationList(c){return I(this,void 0,void 0,function*(){try{var e,t=[],s=(this._pagingStatus=ud.PENDING,yield function(n){return I(this,void 0,void 0,function*(){var{fromAccount:e,pagingTimeStamp:t,pagingStartIndex:s,pagingPinnedTimeStamp:r,pagingPinnedStartIndex:i}=n;return Ks({servcmd:"recentcontact.page_get",data:{AssistFlags:31,MsgAssistFlags:15,OrderType:1,From_Account:e,StartIndex:s,TimeStamp:t,TopStartIndex:i,TopTimeStamp:r}})})}({fromAccount:g(),pagingTimeStamp:c?this._pagingTimeStamp:0,pagingStartIndex:c?this._pagingStartIndex:0,pagingPinnedTimeStamp:c?this._pagingPinnedTimeStamp:0,pagingPinnedStartIndex:c?this._pagingPinnedStartIndex:0})),{CompleteFlag:r,SessionItem:i=[],TimeStamp:n,StartIndex:o,TopTimeStamp:a,TopStartIndex:u}=s||{};if(0<i.length){let e=this._getConversationOptions(i);t.push(...e);var l=k["notificationCenter"];l.emitInnerEvent(d.SYNC_CONVERSATION_LIST,{conversationUpdateFieldList:e})}return this._pagingTimeStamp=n,this._pagingStartIndex=o,this._pagingPinnedTimeStamp=a,this._pagingPinnedStartIndex=u,1!==r&&(e=(yield this._pagingGetConversationList(c))["conversationList"],t.push(...e)),{conversationList:t}}catch(e){throw e}})}_getConversationOptions(e){let{isUndefined:t}=k["utils"],s=this._convertConversationKey(e);return this._filterValidConversations(s).map(e=>(t(e.lastMsg)&&(e.lastMsg={elements:[]}),e.type===ld.C2C?this._assembleC2COption(e):this._assembleGroupOption(e)))}_filterValidConversations(e){return e.filter(({type:e,userID:t})=>e===ld.C2C&&!function(e){let t;return"@TLS#ERROR"===(t=e.startsWith(S.CONV_C2C)?e.replace(S.CONV_C2C,""):t)||"@TLS#NOT_FOUND"===t}(t)||2===e)}_assembleC2COption(e){var t,s=this._createUserprofile(e);return{conversationID:""+S.CONV_C2C+e.userID,type:S.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===cd.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:Cd(e.standardMark),conversationGroupList:[],remark:e.friendRemark||"",messageRemindType:this._transMsgRemindType(e.messageRemindType)}}_createUserprofile(e){var{userID:e,nick:t,peerAvatar:s}=e,t=[{tag:"Tag_Profile_IM_Nick",value:t},{tag:"Tag_Profile_IM_Image",value:s}];return null==(s=k.user.userProfile)?void 0:s.createProfile(e,t)}_computeIsPeerRead(e){var{lastC2CMsgFromAccount:e,time:t,c2cPeerReadTime:s}=e;return e===g()&&t<=s}_assembleGroupOption(e){var t;return{conversationID:""+S.CONV_GROUP+e.groupID,type:S.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===cd.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:Cd(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(s){var e,t,r=k["utils"]["isEmpty"];if(r(s))return null;let i="",n=null;if(!r(s.GroupTips)){let{From_Account:e,GroupName:t}=(null==(r=s.GroupTips)?void 0:r.GroupInfo)||{};i=S.MSG_GRP_TIP,n=Object.assign(Object.assign({},this._parseContent(i,s.GroupTips.MsgBody)),{groupProfile:{from:e,groupName:t}})}return s.MsgBody&&(i=null==(e=s.MsgBody[0])?void 0:e.MsgType,n=this._parseContent(i,s.MsgBody[0])),{event:s.Event,elements:[{type:i,content:n,cloudCustomData:s.CloudCustomData}],revokerInfo:{revoker:null==(t=s.RevokerInfo)?void 0:t.revoker}}}_parseContent(e,t){return t&&((e=k.message.messageFactory.getElementClass(e))?null==(e=e.parseServerPushElement(t))?void 0:e.content:t)}_amendLayersOverLimitProp(e){var t=e["LayersOverLimit"];return f(e,["LayersOverLimit"]).layersOverLimit=1===t,e}_transMsgRemindType(e){let t="";return 0===e?t=S.MSG_REMIND_ACPT_AND_NOTE:1===e?t=S.MSG_REMIND_DISCARD:2===e?t=S.MSG_REMIND_ACPT_NOT_NOTE:3===e&&(t=S.NOT_RECEIVE_OFFLINE_PUSH_EXCEPT_AT),t}_patchTypeAndPayload(e){var t=k["utils"]["isUndefined"],{event:e,elements:s=[]}=e.lastMsg||{};return t(e)?{type:s[0]?s[0].type:null,payload:s[0]?this._amendLayersOverLimitProp(s[0].content):null}:{type:S.MSG_GRP_TIP,payload:(null==(t=null==s?void 0:s[0])?void 0:t.content)||{}}}_computeGroupUnreadCount(e){var{unreadCount:e=0,noUnreadCount:t=0}=e,e=e-t;return 0<e?e:0}_reset(){this._pagingStatus=ud.NOT_START,this._pagingTimeStamp=0,this._pagingStartIndex=0,this._pagingPinnedTimeStamp=0,this._pagingPinnedStartIndex=0}_dispose(){this._reset();var e=k["notificationCenter"];e.unSubscribeInnerEvent(d.LOGOUT,this._reset,this),e.unSubscribeInnerEvent(d.DESTROY,this._dispose,this)}}class Md{constructor(){this.syncConversationHandler=new Sd,this.syncConversationHandler.init()}}return k.ssoLog.debug("TencentCloudLiteChat.VERSION:"+lt),{create:function(e){var{SDKAppID:e,testEnv:t=!1,devMode:s=!1,unlimitedAVChatRoom:r=!1,scene:i="",oversea:n=!1,instance:o,disableIndependentDomain:a=!1}=e,u=e;if("number"!=typeof u&&(e=Number(u),Number.isNaN(e)))return console.error("Create SDK instance failed. Failed to parse the SDKAppID, please check the arguments"),null;if(u=Number(u),qs.has(u))return qs.get(u);let l=null;if(o)(l=o)._workflowManager&&h.setInstance(l._workflowManager),l._pluginManager&&l._pluginManager.installBuiltInPlugin(Wl),!o.isReady()||null!=(o=(e=h.getInstance()).executeWorkflow)&&o.call(e,p.SYNC_SERVER_INFO_AFTER_LOGIN);else{let e=""+(c()+c())+c()+c()+c()+c()+c()+c();k.init({sdkAppId:u,instanceId:e,testEnv:t,devMode:s,unlimitedAVChatRoom:r,disableIndependentDomain:a,scene:i,oversea:n,sdkEdition:Kl}),h.getInstance().init(),k.message=new zc,k.user=new Ed,k.login=new nc,k.conversation=new Md,Yl.getInstance().installBuiltInPlugin(Wl),(l=G.getInstance().exposeApiForClient())._workflowManager=h.getInstance(),l._pluginManager=Yl.getInstance()}function c(){return(65536*(1+Math.random())|0).toString(16).substring(1)}return qs.set(u,l),l},TSignaling:Ht,EVENT:jt,VERSION:lt,TYPES:S}});