@tencentcloud/lite-chat 1.2.0 → 1.2.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +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(){"use strict";class e{constructor(){this.listeners={}}on(e,t,s){this.listeners[e]||(this.listeners[e]=[]),this.listeners[e].push({fn:t,context:s})}off(e,t,s){var o;t&&(this.listeners[e]=null===(o=this.listeners[e])||void 0===o?void 0:o.filter((e=>{const o=e.fn===t,n=!s||e.context===s;return!(o&&n)})))}emit(e,...t){const s=this.listeners[e];s&&s.forEach((e=>{const{fn:s,context:o}=e;s.apply(o,t)}))}once(e,t,s){const o=(...n)=>{t.apply(s,n),this.off(e,o)};this.on(e,o)}}var t;!function(e){e.BUSINESS_COMMAND="business_command",e.C2C_REALTIME_MESSAGE="c2c_realtime_message",e.C2C_MESSAGE_MODIFIED="c2c_message_modified",e.C2C_REVOKED_MESSAGE="c2c_message_revoked",e.GROUP_REALTIME_MESSAGE="group_realtime_message",e.GROUP_MESSAGE_MODIFIED="group_message_modified",e.GROUP_MESSAGE_REVOKED="group_message_revoked",e.C2C_MESSAGE_READ_RECEIPT="c2c_message_read_receipt",e.MESSAGE_REACTION_UPDATED="message_reaction_updated",e.MESSAGE_REACTION_UPDATED_SYNC="message_reaction_updated_sync",e.GROUP_AT_TIPS="group_at_tips",e.USER_STATUS_UPDATE="user_status_update",e.FRIEND_LIST_MODIFIED="friend_list_modified",e.PROFILE_MODIFIED="profile_modified",e.CONV_MODIFIED="conversation_modified",e.GROUP_TIPS_NOTIFICATION="group_tips_notification",e.GROUP_MESSAGE_READ_RECEIPT="group_message_read_receipt",e.GROUP_MESSAGE_READ_SYNC="group_message_read_sync",e.GROUP_SYSTEM_NOTIFICATION="group_system_notification",e.C2C_MESSAGE_PEER_READ="c2c_message_peer_read",e.C2C_MESSAGE_READ_SYNC="c2c_message_read_sync",e.C2C_REMIND_TYPE_SYNC="c2c_remind_type_sync",e.FOLLOW_LIST_UPDATED="follow_list_updated"}(t||(t={}));const s=[{conditions:[{type:"event",value:100}],subType:t.BUSINESS_COMMAND},{conditions:[{type:"hasKey",value:"C2cMsgArray"}],subType:t.C2C_REALTIME_MESSAGE},{conditions:[{type:"hasKey",value:"C2cMsgModNotifys"}],subType:t.C2C_MESSAGE_MODIFIED},{conditions:[{type:"hasKey",value:"ProfileDataMod"}],subType:t.PROFILE_MODIFIED},{conditions:[{type:"hasKey",value:"UserStatusList"}],subType:t.USER_STATUS_UPDATE},{conditions:[{type:"hasKey",value:"FriendListMod"}],subType:t.FRIEND_LIST_MODIFIED},{conditions:[{type:"hasKey",value:"GroupMsgArray"}],subType:t.GROUP_REALTIME_MESSAGE},{conditions:[{type:"hasKey",value:"GroupMsgModNotifys"}],subType:t.GROUP_MESSAGE_MODIFIED},{conditions:[{type:"hasKey",value:"C2cNotifyMsgArray"}],subTypeParser:function(e){var s;const o=[];return null===(s=null==e?void 0:e.C2cNotifyMsgArray)||void 0===s||s.forEach((e=>{e.WithdrawC2cMsgNotify&&o.push(t.C2C_REVOKED_MESSAGE),e.C2cReadedReceipt&&o.push(t.C2C_MESSAGE_PEER_READ),e.ReadC2cMsgNotify&&o.push(t.C2C_MESSAGE_READ_SYNC),e.MuteNotificationsSync&&o.push(t.C2C_REMIND_TYPE_SYNC)})),o}},{conditions:[{type:"hasKey",value:"GroupTips"},{type:"event",value:4}],subType:t.GROUP_TIPS_NOTIFICATION},{conditions:[{type:"hasKey",value:"GroupTips"},{type:"event",value:5}],subTypeParser:function(e){var s;const o=[];return null===(s=null==e?void 0:e.GroupTips)||void 0===s||s.forEach((e=>{Array.isArray(e.MsgBody.GroupWithdrawInfoArray)&&o.push(t.GROUP_MESSAGE_REVOKED),Array.isArray(e.MsgBody.GroupMsgReceiptList)&&o.push(t.GROUP_MESSAGE_READ_RECEIPT),Array.isArray(e.MsgBody.GroupReadInfoArray)?o.push(t.GROUP_MESSAGE_READ_SYNC):o.push(t.GROUP_SYSTEM_NOTIFICATION)})),o}},{conditions:[{type:"hasKey",value:"GroupTips"},{type:"event",value:6}],subType:t.GROUP_TIPS_NOTIFICATION},{conditions:[{type:"hasKey",value:"GroupTips"},{type:"event",value:12}],subType:t.GROUP_AT_TIPS},{conditions:[{type:"hasKey",value:"RecentContactMod"}],subType:t.CONV_MODIFIED},{conditions:[{type:"hasKey",value:"MsgReactionNotifyList"}],subType:t.MESSAGE_REACTION_UPDATED},{conditions:[{type:"hasKey",value:"MsgReactionNotify"}],subType:t.MESSAGE_REACTION_UPDATED_SYNC},{conditions:[{type:"hasKey",value:"C2cMsgInfo"}],subType:t.C2C_MESSAGE_READ_RECEIPT},{conditions:[{type:"hasKey",value:"FollowChangeList"}],subType:t.FOLLOW_LIST_UPDATED}];var o;!function(e){e.SERVER_PUSH_MESSAGE="im_open_push.msg_push",e.ERROR="error"}(o||(o={}));const n={[o.SERVER_PUSH_MESSAGE]:function(e){var t;const n=Array.isArray(null===(t=null==e?void 0:e.body)||void 0===t?void 0:t.EventArray)?e.body.EventArray:[],i=[];return n.forEach((t=>{t.Flag=e.body.Flag;const n=s.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(!n)return null;let r=[];"function"==typeof n.subTypeParser?r=n.subTypeParser(t):n.subType&&(r=n.subType),Array.isArray(r)?r.forEach((e=>{i.push({type:`${o.SERVER_PUSH_MESSAGE}:${e}`,data:t})})):i.push({type:`${o.SERVER_PUSH_MESSAGE}:${r}`,data:t})})),i},[o.ERROR]:function(e){const{errorCode:t}=e;return[{type:`error:${t}`,data:e}]}};const i=new class{constructor(){this._outerEventEmitter=null,this._innerEventEmitter=null,this._outerEventEmitter=new e,this._innerEventEmitter=new e,this.InnerEventSubType=t}subscribeInnerEvent(e,t,s,o){var n,i;if(["string","number"].includes(typeof t)){const i=t,r=s;null===(n=this._innerEventEmitter)||void 0===n||n.on(`${e}:${i}`,r,o)}else{const o=t;null===(i=this._innerEventEmitter)||void 0===i||i.on(e,o,s)}}emitInnerEvent(e,t){var s,o;if(null===(s=this._innerEventEmitter)||void 0===s||s.emit(e,t),Object.keys(n).includes(e)){const s=null===(o=n[e])||void 0===o?void 0:o.call(n,t);null==s||s.forEach((e=>{var t;e&&(null===(t=this._innerEventEmitter)||void 0===t||t.emit(e.type,e.data))}))}}unSubscribeInnerEvent(e,t,s,o){var n,i;if(["string","number"].includes(typeof t)){const i=t,r=s;null===(n=this._innerEventEmitter)||void 0===n||n.off(`${e}:${i}`,r,o)}else{const o=t;null===(i=this._innerEventEmitter)||void 0===i||i.off(e,o,s)}}subscribeOuterEvent(e,t,s){var o;null===(o=this._outerEventEmitter)||void 0===o||o.on(e,t,s)}unSubscribeOuterEvent(e,t,s){var o;null===(o=this._outerEventEmitter)||void 0===o||o.off(e,t,s)}emitOuterEvent(e,t){var s;null===(s=this._outerEventEmitter)||void 0===s||s.emit(e,t)}getOuterEventEmitter(){return this._outerEventEmitter}rest(){this._outerEventEmitter=null,this._innerEventEmitter=null}};function r(e,t){var s={};for(var o in e)Object.prototype.hasOwnProperty.call(e,o)&&t.indexOf(o)<0&&(s[o]=e[o]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var n=0;for(o=Object.getOwnPropertySymbols(e);n<o.length;n++)t.indexOf(o[n])<0&&Object.prototype.propertyIsEnumerable.call(e,o[n])&&(s[o[n]]=e[o[n]])}return s}function a(e,t,s,o){return new(s||(s=Promise))((function(n,i){function r(e){try{c(o.next(e))}catch(e){i(e)}}function a(e){try{c(o.throw(e))}catch(e){i(e)}}function c(e){var t;e.done?n(e.value):(t=e.value,t instanceof s?t:new s((function(e){e(t)}))).then(r,a)}c((o=o.apply(e,t||[])).next())}))}"function"==typeof SuppressedError&&SuppressedError;const c=e=>void 0===e,l=e=>"string"==typeof e,u=e=>{var t;return null===(t=Object.prototype.toString.call(e).match(/^\[object (.*)\]$/))||void 0===t?void 0:t[1].toLowerCase()},d=e=>"function"==typeof Array.isArray?Array.isArray(e):"array"===u(e),h=e=>null!==e&&"object"==typeof e,p=e=>d(e)||h(e),g=e=>{if("string"!=typeof e)return!1;const t=e[0];return!/[^a-zA-Z0-9]/.test(t)},_=e=>{if("object"!=typeof e||null===e)return!1;const t=Object.getPrototypeOf(e);if(null===t)return!0;let s=t;for(;null!==Object.getPrototypeOf(s);)s=Object.getPrototypeOf(s);return t===s};function m(e=99999999){return Math.round(Math.random()*e)}const f=(e,t,s,o)=>{if(!p(e)||!p(t))return 0;let n=0;const i=Object.keys(t);let r;for(let a=0,l=i.length;a<l;a++)if(r=i[a],!(c(t[r])||s&&s.includes(r)))if(p(e[r])&&p(t[r]))n+=f(e[r],t[r],s,o);else{if(o&&o.includes(t[r]))continue;e[r]!==t[r]&&(e[r]=t[r],n+=1)}return n};function v(e){let t,s,o=e;e.length%8!=0&&(o="0".repeat(8-e.length%8)+e);let n="";for(let e=0,{length:i}=o;e<i;e+=8)t=parseInt(o.slice(e,e+4),2),s=parseInt(o.slice(e+4,e+8),2),n+=base16Map.get(t)+base16Map.get(s);return n}const I={ANDROID:2,IOS:3,MAC:4,WEB:7,WX_MP:8,QQ_MP:9,TT_MP:10,BAIDU_MP:11,ALI_MP:12,IPAD:13,UNI_NATIVE_APP:15,DONUT_NATIVE_APP:19,NS_NATIVE_APP:20,RN_NATIVE_APP:21},S=["heartbeat.alive","im_open_status.wslogin","im_open_status.wslogout","group_open_long_polling_http_svc.get_msg","group_open_long_polling_http_noauth_svc.get_msg"];var E=Object.freeze({__proto__:null,ENUM_PLATFORM:I,NOT_NEED_CRC_SERVCMD:S});const C="undefined"!=typeof wx&&"function"==typeof wx.getSystemInfoSync&&Boolean(wx.getSystemInfoSync().fontSizeSetting),y=C&&"function"==typeof wx.createGamePortal,M="undefined"!=typeof qq&&"function"==typeof qq.getSystemInfoSync&&Boolean(qq.getSystemInfoSync().fontSizeSetting),A="undefined"!=typeof tt&&"function"==typeof tt.getSystemInfoSync&&Boolean(tt.getSystemInfoSync().fontSizeSetting),O="undefined"!=typeof swan&&"function"==typeof swan.getSystemInfoSync&&Boolean(swan.getSystemInfoSync().fontSizeSetting),T="undefined"!=typeof my&&"function"==typeof my.getSystemInfoSync&&Boolean(my.getSystemInfoSync().fontSizeSetting),D="undefined"!=typeof jd&&"function"==typeof jd.getSystemInfoSync,R="undefined"!=typeof uni&&"undefined"==typeof window&&"function"==typeof uni.requireNativePlugin,L=C&&"object"==typeof wx.miniapp,N="undefined"!=typeof uni,b=C||M||A||O||T||R||D,w="undefined"==typeof window&&!b&&"undefined"!=typeof global&&void 0!==global.NativeScriptGlobals,P="undefined"!=typeof global&&(void 0!==global.nativeModuleProxy||void 0!==global.ReactNative),U="undefined"!=typeof wx&&"function"==typeof wx.getAccountInfoSync&&Boolean(wx.getAccountInfoSync().plugin),G="undefined"!=typeof uni?!b:"undefined"!=typeof window&&!b&&!P,k=M?qq:A?tt:O?swan:T?my:C?wx:R?uni:D?jd:{},F=G&&window&&window.navigator&&window.navigator.userAgent||"",$=/(micromessenger|webbrowser)/i.test(F),q=function(){let e="WEB";return $?e="WEB":M?e="QQ_MP":A?e="TT_MP":O?e="BAIDU_MP":T?e="ALI_MP":C?e=L?"DONUT_NATIVE_APP":"WX_MP":R?e="UNI_NATIVE_APP":w?e="NS_NATIVE_APP":P&&(e="RN_NATIVE_APP"),I[e]}(),x=/iPad/i.test(F),V=/iPhone/i.test(F)&&!x,B=/iPod/i.test(F),j=V||x||B,W=function(){const e=F.match(/OS (\d+)_/i);return e&&e[1]?e[1]:null}(),K=/Android/i.test(F),H=function(){const e=F.match(/Android (\d+)(?:\.(\d+))?(?:\.(\d+))*/i);if(!e)return null;const t=e[1]&&parseFloat(e[1]),s=e[2]&&parseFloat(e[2]);return t&&s?parseFloat(`${e[1]}.${e[2]}`):t||null}(),Y=/Firefox/i.test(F),z=/Edge/i.test(F),J=!z&&/Chrome/i.test(F),Z=/MSIE/.test(F)||F.indexOf("Trident")>-1&&F.indexOf("rv:11.0")>-1,X=function(){const e=/MSIE\s(\d+)\.\d/.exec(F);let t=e&&parseFloat(e[1]);return!t&&/Trident\/7.0/i.test(F)&&/rv:11.0/.test(F)&&(t=11),t}(),Q=/Safari/i.test(F)&&!J&&!K&&!z,ee=/Windows/i.test(F),te=/MAC OS X/i.test(F),se=G&&"undefined"!=typeof Worker&&!Z,oe=K||j,ne=G&&void 0!==window.tencent_cloud_im_csig_flutter_for_web_25F_cy,ie=function(){if("undefined"==typeof window||void 0===window.navigator)return!1;const{standalone:e}=window.navigator;return!(!j||e||Q)}();function re(){let e="unknown";if(te&&(e="mac"),ee&&(e="windows"),j&&(e="ios"),K&&(e="android"),b)try{const{platform:t}=wx.getSystemInfoSync();void 0!==t&&(e=t)}catch(e){console.error(e)}return e}const ae=2800,ce=2801,le=3e3,ue="application/x-www-form-urlencoded;charset=UTF-8";function de(e){return a(this,arguments,void 0,(function*({method:e,url:t,data:s,timeout:o=le}){return new Promise(b?(n,i)=>{k.request({url:t,data:s,method:e,timeout:o,header:{"content-type":ue},success:e=>n(e.data),fail:()=>i(new Error(`{"message":"Network error","code":${ae}}`))})}:(n,i)=>{const r=new XMLHttpRequest,a=setTimeout((()=>{r.abort(),i(new Error(`{"message":"Request timeout","code":${ce}}`))}),o);r.onreadystatechange=function(){if(4===r.readyState)if(clearTimeout(a),200===r.status||304===r.status)try{n(r.responseText?JSON.parse(r.responseText):null)}catch(e){n(r.responseText)}else i(new Error(`{"message":"Network error","code":${ae}}`))},r.open(e,t,!0),r.setRequestHeader("Content-type",ue),r.send(s||null)})}))}function he(e){if(null==e)return!0;if("boolean"==typeof e)return!1;if("number"==typeof e)return 0===e;if("string"==typeof e)return 0===e.length;if("function"==typeof e)return 0===e.length;if(Array.isArray(e))return 0===e.length;if(e instanceof Error)return""===e.message;if(_(e)){for(const t in e)if(Object.prototype.hasOwnProperty.call(e,t))return!1;return!0}return("[object Map]"===Object.prototype.toString.call(e)||"[object Set]"===Object.prototype.toString.call(e)||"[object File]"===Object.prototype.toString.call(e))&&0===e.size}function pe(e){if(null===e||"object"!=typeof e)return e;if(e instanceof Date)return new Date(e.getTime());if(e instanceof RegExp)return new RegExp(e.source,e.flags);if(e instanceof Map){const t=new Map;return e.forEach(((e,s)=>{t.set(pe(s),pe(e))})),t}if(e instanceof Set){const t=new Set;return e.forEach((e=>{t.add(pe(e))})),t}if(Array.isArray(e))return e.map((e=>pe(e)));const t=Object.getPrototypeOf(e),s=Object.create(t);return[...Object.getOwnPropertyNames(e),...Object.getOwnPropertySymbols(e)].forEach((t=>{const o=Object.getOwnPropertyDescriptor(e,t);o&&(o.get||o.set?Object.defineProperty(s,t,o):s[t]=pe(e[t]))})),s}function ge(){let e,t;return{promise:new Promise(((s,o)=>{e=s,t=o})),resolve:e,reject:t}}var _e=Object.freeze({__proto__:null,ANDROID_VERSION:H,IE_VERSION:X,IN_ALIPAY_MINI_APP:T,IN_BAIDU_MINI_APP:O,IN_BROWSER:G,IN_DONUT_NATIVE_APP:L,IN_JD_MINI_APP:D,IN_MINI_APP:b,IN_NS_NATIVE_APP:w,IN_QQ_MINI_APP:M,IN_RN_APP:P,IN_TT_MINI_APP:A,IN_UNI_APP:N,IN_UNI_NATIVE_APP:R,IN_WX_MINI_APP:C,IN_WX_MINI_GAME:y,IN_WX_MINI_PLUGIN:U,IOS_VERSION:W,IS_ANDROID:K,IS_CHROME:J,IS_EDGE:z,IS_FIREFOX:Y,IS_IE:Z,IS_IOS:j,IS_IPAD:x,IS_IPHONE:V,IS_IPOD:B,IS_MAC:te,IS_SAFARI:Q,IS_WECHAT:$,IS_WIN:ee,IS_WORKER_AVAILABLE:se,MINI_APP_NAMESPACE:k,USER_AGENT:F,base16EncodeBinaryString:v,deepCopyWithMethods:pe,deepMerge:f,generatePromise:ge,getPlatformType:re,getType:u,httpRequest:de,isArray:d,isArrayOrObject:p,isEmpty:he,isFlutterWeb:ne,isH5:oe,isIOSWebView:ie,isNumber:e=>null!==e&&("number"==typeof e&&!Number.isNaN(e-0)||"object"==typeof e&&e.constructor===Number),isObject:h,isPlainObject:_,isString:l,isUndefined:c,isValidRequestKey:g,platform:q,randomInt:m,randomString:function(){const e="0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";let t="";for(let s=32;s>0;--s)t+=e[Math.floor(62*Math.random())];return t}});class me{constructor(){this._socket=null}connectSocket(e){return this._socket=new WebSocket(e),this._socket}send(e){var t,s;try{null===(t=this._socket)||void 0===t||t.send(e)}catch(e){null===(s=this._onSendFail)||void 0===s||s.call(this,e)}}bindSocketHandlers(e){const{onOpen:t,onMessage:s,onClose:o,onError:n,onSendFail:i}=e;this._socket&&(this._socket.binaryType="arraybuffer",this._socket.onopen=t,this._socket.onmessage=s,this._socket.onclose=o,this._socket.onerror=n,this._onSendFail=i)}unbindSocketHandlers(){this._socket&&(this._socket.onopen=null,this._socket.onmessage=null,this._socket.onclose=null,this._socket.onerror=null)}disconnect(){this._socket&&(this._socket.close(),this._socket=null)}}class fe{connectSocket(e){return this._socket=wx.connectSocket({url:e,header:{"content-type":"application/json"},complete:()=>{}}),this._socket}send(e){var t;null===(t=this._socket)||void 0===t||t.send({data:e,fail:this._onSendFail})}bindSocketHandlers(e){const{onOpen:t,onMessage:s,onClose:o,onError:n,onSendFail:i}=e;this._socket.onClose(o),this._socket.onOpen(t),this._socket.onMessage(s),this._socket.onError(n),this._onSendFail=i}unbindSocketHandlers(){this._socket&&(this._socket.onClose((()=>{})),this._socket.onOpen((()=>{})),this._socket.onMessage((()=>{})),this._socket.onError((()=>{})))}disconnect(){this._socket&&(this._socket.close(),this._socket=null)}}const ve="CONNECT",Ie="SEND",Se="DISCONNECT",Ee="OPEN",Ce="MESSAGE",ye="CLOSE",Me="ERROR",Ae="SEND_FAIL";class Oe{constructor(){this._worker=null,this._blobUrl=null}connectSocket(e){const t=new Blob(["\n let _socket = null;\n\n self.onmessage = (event) => {\n const { type, url, data } = event.data;\n\n switch (type) {\n case 'CONNECT':\n connectSocket(url);\n break;\n case 'SEND':\n send(data);\n break;\n case 'DISCONNECT':\n disconnect();\n break;\n }\n };\n\n function connectSocket(url) {\n _socket = new WebSocket(url);\n _socket.binaryType = 'arraybuffer';\n bindSocketHandlers();\n return _socket;\n }\n\n function send(packet) {\n try {\n _socket?.send(packet);\n } catch (error) {\n self.postMessage({\n type: 'SEND_FAIL', \n error: {\n message: error.message,\n name: error.name,\n },\n });\n }\n }\n\n function bindSocketHandlers() {\n if (_socket) {\n _socket.onopen = (event) => {\n self.postMessage({\n type: 'OPEN',\n data: {\n type: event.type,\n timeStamp: event.timeStamp,\n },\n });\n };\n\n _socket.onmessage = (event) => {\n self.postMessage({ \n type: 'MESSAGE',\n data: event.data,\n });\n };\n\n _socket.onclose = (event) => {\n self.postMessage({ \n type: 'CLOSE', \n data: { \n code: event.code,\n reason: event.reason,\n timeStamp: event.timeStamp,\n },\n });\n };\n\n _socket.onerror = (error) => {\n self.postMessage({\n type: 'ERROR',\n data: {\n message: error.message,\n name: error.name\n },\n });\n };\n }\n }\n\n function unbindSocketHandlers() {\n if (_socket) {\n _socket.onopen = null;\n _socket.onmessage = null;\n _socket.onclose = null;\n _socket.onerror = null;\n }\n }\n\n function disconnect() {\n if (_socket) {\n _socket.close();\n _socket = null;\n }\n }\n"],{type:"application/javascript"});this._worker=new Worker(URL.createObjectURL(t)),this._worker.postMessage({type:ve,url:e})}send(e){var t,s;try{null===(t=this._worker)||void 0===t||t.postMessage({type:Ie,data:e})}catch(e){null===(s=this._onSendFail)||void 0===s||s.call(this,e)}}bindSocketHandlers(e){const{onOpen:t,onMessage:s,onClose:o,onError:n,onSendFail:i}=e;if(this._worker){const e={[Ee]:t,[Ce]:s,[ye]:o,[Me]:n,[Ae]:i};this._onSendFail=i,this._worker.onmessage=t=>{var s;const{type:o}=(null==t?void 0:t.data)||{};"function"==typeof e[o]&&(null===(s=e[o])||void 0===s||s.call(e,null==t?void 0:t.data))}}}unbindSocketHandlers(){this._worker&&(this._worker.onmessage=null)}disconnect(){this._worker&&(this._worker.postMessage({type:Se}),this._worker.terminate(),this._worker=null),this._blobUrl&&(URL.revokeObjectURL(this._blobUrl),this._blobUrl=null)}}var Te,De=new class{constructor(){this._store=new Map}get(e){return this._store.get(e)}getStorage(e){if(b){if(T){return my.getStorageSync({key:e}).data}return k.getStorageSync(e)}return this._canUseLocalStorage()?localStorage.getItem(e):{}}set(e,t){const s=this._store.get(e)||{};t instanceof Map?this._store.set(e,t):this._store.set(e,Object.assign(Object.assign({},s),t))}setStorage(e,t){b?T?my.setStorageSync({key:e,data:JSON.stringify(t)}):k.setStorageSync(e,JSON.stringify(t)):this._canUseLocalStorage()&&localStorage.setItem(e,JSON.stringify(t))}clear(e){"string"==typeof e?this._store.set(e,{}):this._store.clear()}clearLocalStorage(e){this._canUseLocalStorage()&&("string"==typeof e?localStorage.setItem(e,""):localStorage.clear())}reset(){this.clear()}_canUseLocalStorage(){return"undefined"!=typeof window&&(navigator&&navigator.cookieEnabled&&localStorage)}};!function(e){e[e.CONNECTED=0]="CONNECTED",e[e.CONNECTING=1]="CONNECTING",e[e.DISCONNECTED=2]="DISCONNECTED"}(Te||(Te={}));class Re{constructor(t){this._url="",this._readyState=Te.DISCONNECTED,this._url=t,this._id=m(),this._emitter=new e,C?this._socket=new fe:this._canUseWebWorker()?this._socket=new Oe:this._socket=new me,this.connect()}connect(){this.doOpen(),this._bindSocketHandlers()}doOpen(){[Te.CONNECTED,Te.CONNECTING].includes(this._readyState)||(this._readyState=Te.CONNECTING,this._ws=this._socket.connectSocket(this._url))}send(e){this._readyState!==Te.CONNECTED?this.reconnect():this._socket.send(e)}reconnect(){[Te.CONNECTED,Te.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===Te.CONNECTED}disconnect(){this._readyState=Te.DISCONNECTED,this._unbindSocketHandlers(),this._socket.disconnect()}_onOpen(e){this._readyState===Te.CONNECTING&&(this._readyState=Te.CONNECTED,this._emitter.emit("connect",{socketId:this._id,event:e}))}_onMessage(e){this._emitter.emit("message",e)}_onClose(e){this._readyState=Te.DISCONNECTED,this._emitter.emit("close",{socketId:this._id,event:e})}_onError(e){this._readyState=Te.DISCONNECTED,this._emitter.emit("error",{socketId:this._id,error:e})}_onSendFail(e){this._readyState=Te.DISCONNECTED,this._emitter.emit("sendFail",{socketId:this._id,error:e})}_bindSocketHandlers(){this._socket.bindSocketHandlers({onOpen:this._onOpen.bind(this),onMessage:this._onMessage.bind(this),onClose:this._onClose.bind(this),onError:this._onError.bind(this),onSendFail:this._onSendFail.bind(this)})}_unbindSocketHandlers(){this._socket.unbindSocketHandlers()}_canUseWebWorker(){const e=De.get("cloudConfig")||{};return(c(e.isWorkerEnabled)||"1"===e.isWorkerEnabled)&&se}}const Le="CHINA",Ne="SINGAPORE",be="KOREA",we="GERMANY",Pe="IND",Ue="JPN",Ge="USA",ke="INDONESIA",Fe={TEST:{CHINA:{DEFAULT:"wss://wss-dev.tim.qq.com"},OVERSEA:{DEFAULT:"wss://wss-dev.tim.qq.com"},SINGAPORE:{DEFAULT:"wss://wsssgp-dev.im.qcloud.com"},KOREA:{DEFAULT:"wss://wsskr-dev.im.qcloud.com"},GERMANY:{DEFAULT:"wss://wssger-dev.im.qcloud.com"},IND:{DEFAULT:"wss://wssind-dev.im.qcloud.com"},JPN:{DEFAULT:"wss://wssjpn-dev.im.qcloud.com"},USA:{DEFAULT:"wss://wssusa-dev.im.qcloud.com"},INDONESIA:{DEFAULT:"wss://wssidn-dev.im.qcloud.com"}},PRODUCTION:{CHINA:{INITIAL:"wss://*w4c.my-imcloud.com",DEFAULT:"wss://wss.im.qcloud.com",BACKUP:"wss://wss.tim.qq.com",STAT:"https://events.im.qcloud.com",ANYCAST:"wss://162.14.13.203"},OVERSEA:{INITIAL:"wss://*w4c.my-imcloud.com",DEFAULT:"wss://wss.im.qcloud.com",BACKUP:"wss://wss.my-imcloud.com",STAT:"https://api.my-imcloud.com"},SINGAPORE:{INITIAL:"wss://*w4s.my-imcloud.com",DEFAULT:"wss://wsssgp.im.qcloud.com",BACKUP:"wss://wsssgp.my-imcloud.com",STAT:"https://apisgp.my-imcloud.com",ANYCAST:"wss://162.14.19.159"},KOREA:{INITIAL:"wss://*w4k.my-imcloud.com",DEFAULT:"wss://wsskr.im.qcloud.com",BACKUP:"wss://wsskr.my-imcloud.com",STAT:"https://apikr.my-imcloud.com",ANYCAST:"wss://162.14.13.104"},GERMANY:{INITIAL:"wss://*w4g.my-imcloud.com",DEFAULT:"wss://wssger.im.qcloud.com",BACKUP:"wss://wssger.my-imcloud.com",STAT:"https://apiger.my-imcloud.com",ANYCAST:"wss://162.14.3.17"},IND:{INITIAL:"wss://*w4i.my-imcloud.com",DEFAULT:"wss://wssind.my-imcloud.com",BACKUP:"wss://wssind.im.qcloud.com",STAT:"https://apiind.my-imcloud.com",ANYCAST:"wss://162.14.18.188"},JPN:{INITIAL:"wss://*w4j.my-imcloud.com",DEFAULT:"wss://wssjpn.im.qcloud.com",BACKUP:"wss://wssjpn.my-imcloud.com",STAT:"https://apijpn.my-imcloud.com"},USA:{INITIAL:"wss://*w4u.my-imcloud.com",DEFAULT:"wss://wssusa.im.qcloud.com",BACKUP:"wss://wssusa.my-imcloud.com",STAT:"https://apiusa.my-imcloud.com",ANYCAST:"wss://162.14.10.42"},INDONESIA:{INITIAL:"wss://*w4y.my-imcloud.com",DEFAULT:"wss://wssidn.im.qcloud.com",BACKUP:"wss://wssidn.my-imcloud.com",STAT:"https://apiidn.my-imcloud.com",ANYCAST:"wss://43.129.34.169"}}},$e={[Ne]:[[2e7,3e7],[172e7,173e7]],[be]:[[3e7,4e7],[173e7,174e7]],[we]:[[4e7,5e7],[174e7,175e7]],[Pe]:[[5e7,6e7],[175e7,176e7]],[Ue]:[[6e7,7e7],[176e7,177e7]],[Ge]:[[7e7,8e7],[177e7,178e7]],[ke]:[[8e7,9e7],[178e7,179e7]]};function qe(e){for(const t of Object.keys($e))for(const[s,o]of $e[t])if(e>=s&&e<o)return t;return Le}var xe,Ve="1.2.1";!function(e){e.INITIAL="INITIAL",e.DEFAULT="DEFAULT",e.BACKUP="BACKUP",e.ANYCAST="ANYCAST"}(xe||(xe={}));let Be=xe.INITIAL;function je(){const e=Math.random();return 0===e?je():e}function We(e,t){const{isBinary:s=!1}=t||{},o=De.get("instance"),{sdkAppId:n,instanceId:i}=o,r=je(),a=re(),c=function(){const e=re();let t=-1;"ios"===e?t=W||-1:"android"===e&&(t=H||-1);return t}(),l=(u={sdkappid:n,instanceid:i,random:r,platform:q,host:a,version:c,sdkversion:Ve},Object.keys(u).map((e=>`${e}=${u[e]}`)).join("&"));var u;return s?`${e}/binfo?${l}&compress=gzip`:`${e}/info?${l}`}var Ke=new class{constructor(){this._timeOffsetWithServer=0}getServerTimeMs(){return Date.now()+this._timeOffsetWithServer}getServerTimeSeconds(){return Math.floor(this.getServerTimeMs()/1e3)}getTimeOffsetWithServer(){return this._timeOffsetWithServer}calculateTimeOffsetWithServer(e,t){const s=Date.now(),o=s-e;this._timeOffsetWithServer=t+o-s}};const He=16;var Ye=new class{constructor(){this._tasks=[],this._timer=null,this._taskMap=new Map}_addTaskToScheduler(e){const{id:t}=e;this.removeTask(t),this._tasks.push(e),this._taskMap.set(t,e),this._sort(),this._scheduleNextTask()}_createTask(e){const{id:t,callback:s,context:o,isOnce:n=!1,intervalMs:i=He}=e,r=Math.max(i,He);return{id:t,nextExecuteTime:Date.now()+r,intervalMs:i,callback:s,context:o,isOnce:n}}addTask(e){const t=this._createTask(e);this._addTaskToScheduler(t)}addOnceTask(e){const t=this._createTask(Object.assign(Object.assign({},e),{isOnce:!0}));this._addTaskToScheduler(t)}removeTask(e){const t=this._tasks.findIndex((t=>t.id===e));t>-1&&(this._tasks.splice(t,1),this._taskMap.delete(e),this._scheduleNextTask())}updateTaskInterval(e,t){const s=this._taskMap.get(e);s&&(s.intervalMs=t,s.nextExecuteTime=Date.now()+t,this._sort(),this._scheduleNextTask())}clearAllTasks(){this._tasks=[],this._taskMap.clear(),this._timer&&(clearTimeout(this._timer),this._timer=null)}dispose(){this.clearAllTasks()}_sort(){this._tasks.sort(((e,t)=>e.nextExecuteTime-t.nextExecuteTime))}_scheduleNextTask(){this._timer&&(clearTimeout(this._timer),this._timer=null);const e=this._tasks[0];if(e){const t=Math.max(0,e.nextExecuteTime-Date.now());this._timer=setTimeout((()=>this._execute()),t)}}_execute(){const e=Date.now();for(;this._tasks.length&&this._tasks[0].nextExecuteTime<=e;){const t=this._tasks[0];try{t.context?t.callback.call(t.context):t.callback(),t.isOnce?this.removeTask(t.id):(t.nextExecuteTime=e+t.intervalMs,this._sort())}catch(e){console.warn(`Task ${t.id} execution failed:`,e),t.isOnce&&this.removeTask(t.id)}}this._scheduleNextTask()}};function ze(e){const t=[];for(let s=0;s<e.length;s+=1){const o=e.charCodeAt(s);if(o>=55296&&o<=56319){const n=e.charCodeAt(++s)-56320+(o-55296<<10)+65536;t.push(240|n>>18,128|n>>12&63,128|n>>6&63,128|63&n)}else o<=127?t.push(o):o<=2047?t.push(192|o>>6,128|63&o):t.push(224|o>>12,128|o>>6&63,128|63&o)}return new Uint8Array(t)}function Je(e){const t=Array.isArray(e)?[]:Object.create(null);for(const s in e)Object.prototype.hasOwnProperty.call(e,s)&&g(s)&&null!=e[s]&&(null===e[s]||"object"!=typeof e[s]?t[s]=e[s]:t[s]=Je(e[s]));return t}function Ze(e,t){if(S.includes(e))return 0;const s=ze(JSON.stringify(t));let o=4294967295;const{length:n}=s;for(let e=0;e<n;e++){o^=s[e];for(let e=0;e<8;e++)1&~o?o>>>=1:o=o>>>1^3988292384}return(4294967295^o)>>>0}function Xe(e){const{servcmd:t,data:s}=e,o=function(e){const t=De.get("login")||{},s=De.get("instance")||{};return{servcmd:e,ver:"v4",platform:q,websdkappid:537048168,websdkversion:"1.7.3",a2:t.a2Key||void 0,tinyid:t.tinyID||void 0,status_instid:t.statusInstanceId||0,sdkappid:s.sdkAppId,contenttype:"json",reqtime:Math.floor(Date.now()/1e3),identifier:t.a2Key?void 0:t.userId,usersig:t.a2Key?void 0:t.userSig,sdkability:75689843,sdkability_ext:v(""),cappid:t.cappid||0,tjgID:"",seq:st(),cs:0}}(t),n=Je(s);return o.cs=Ze(t,n),{head:o,body:n}}function Qe(e){const{servcmd:t,data:s}=e,o=function(e){const t=De.get("login")||{},s=De.get("instance")||{};return{servcmd:e,ver:"v4",platform:q,websdkappid:537048168,websdkversion:"1.7.3",sdkappid:s.sdkAppId,contenttype:"",reqtime:Math.floor(Date.now()/1e3),identifier:"",usersig:"",status_instid:t.statusInstanceId||0,sdkability:75689843,sdkability_ext:v(""),cappid:t.cappid||0,seq:st(),cs:0}}(t),n=Je(s);return o.cs=Ze(t,n),{head:o,body:n}}let et=m();function st(){return et=et<2415919103?et+1:m(),et}var ot,nt=Object.freeze({__proto__:null,generateCosSpecifiedData:function(e){const{servcmd:t,data:s}=e,o=function(e){const t=De.get("login")||{},s=De.get("instance")||{};return{servcmd:e,ver:"v4",platform:q,websdkappid:537048168,websdkversion:"1.7.3",sdkappid:s.sdkAppId,contenttype:"json",reqtime:Math.floor(Date.now()/1e3),identifier:t.userId,usersig:t.userSig,status_instid:t.statusInstanceId||0,sdkability:75689843,sdkability_ext:v(""),cappid:t.cappid||0,seq:st(),cs:0}}(t),n=Je(s);return o.cs=Ze(t,n),{head:o,body:n}},generateProtocolData:Xe,generateSSOLogProtocolData:Qe,generateSequence:st,taskScheduler:Ye,timeManager:Ke});!function(e){e[e.info=4]="info",e[e.warning=5]="warning",e[e.error=6]="error"}(ot||(ot={}));const it={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 rt{constructor(e){this.level=ot.info,this._canSendLog=!0,this._logCreatedAt=Ke.getServerTimeMs(),this.timestamp=0,this.networkType=8,this.code=0,this.moreMessage="",this.method="",this.message="",this.costTime=0,this.duplicate=!1,this.eventType=0,this.uiPlatform=void 0;const{method:t,eventType:s=0}=e||{};this.eventType=s,this.method=t}setMoreMessage(e){this.moreMessage=`${this.moreMessage} ${e}`}updateLogCreatedAtByTimeOffset(){this._logCreatedAt+=Ke.getTimeOffsetWithServer()}end(e=!1){if(!this._canSendLog)return;const t=Ke.getServerTimeMs();0===this.costTime&&(this.costTime=t-this._logCreatedAt),this.setMoreMessage(`startts:${this._logCreatedAt} endts:${t}`),e?(this._canSendLog=!1,this.timestamp=Ke.getServerTimeMs(),this._ssoLogModule.pushToLogQueue(this._convertSSOLogDataKeyToServe())):setTimeout((()=>{this._canSendLog=!1,this.timestamp=Ke.getServerTimeMs(),this._ssoLogModule.pushToLogQueue(this._convertSSOLogDataKeyToServe())}),0)}setError(e){var t;if(!(e instanceof Error))return console.warn("SSOLogData.setError value not instanceof Error, please check!"),this;if(!this._canSendLog)return this;return(null===(t=De.get("netWorkMonitor"))||void 0===t?void 0:t.isNetworkOnline)&&(e.errorCode&&(this.code=e.errorCode),e.errorMessage&&this.setMoreMessage(e.errorMessage)),this.level=ot.error,this}setLogInfo(e){return Object.keys(e).forEach((t=>{Object.keys(it).includes(t)&&(this[t]=e[t])})),this}setSSOLogModule(e){this._ssoLogModule=e}_convertSSOLogDataKeyToServe(){const e={};return Object.keys(this).forEach((t=>{const s=t;it[s]&&(e[it[s]]=this[s])})),e}}var at;function ct(){const e=De.get("login")||{},t=De.get("instance")||{};return{sdk_type:30,sdk_app_id:t.sdkAppId,sdk_version:"1.2.1",tiny_id:Number(e.tinyID),user_id:e.userId,platform:q,instance_id:t.instanceId,trace_id:(new Date).getTime()}}!function(e){e.RECONNECTED="reconnected",e.CLOUD_CONFIG_UPDATE="cloud_config_update",e.SOCKET_DISCONNECTED="socket_disconnected"}(at||(at={}));var lt=at;const ut=20,dt=6e4,ht=[4,5,6],pt=[],gt=[],_t="report-logger";var mt=new class{constructor(){this._sdkAppIdBlackList=[],this._tinyIdWhiteList=[],this._reportLevel=[4,5,6],this._minThreshold=ut,this._maxThreshold=100,this._waitingTime=dt,this._lastReportAt=Date.now(),this._ssoLogMap=new Map,i.subscribeInnerEvent(lt.CLOUD_CONFIG_UPDATE,this._handleCloudConfigUpdate,this),Ye.addTask({id:_t,intervalMs:1e3,callback:this._checkAndReportIfDue,context:this}),this._logQueue=[],this._savePlatFormInfo()}_handleCloudConfigUpdate(e){const{evt_rpt_threshold:t=ut,evt_rpt_waiting:s=dt,evt_rpt_level:o=ht,evt_rpt_sdkappid_bl:n=pt,evt_rpt_tinyid_wl:i=gt}=e||{};this._sdkAppIdBlackList=n,this._waitingTime=s,this._minThreshold=t,this._reportLevel=o,this._tinyIdWhiteList=i}createSSOLogData(e){const t=new rt(e);return t.setSSOLogModule(this),this._ssoLogMap.set(e.method,t),t}getSSOLogData(e){return this._ssoLogMap.get(e)||{}}pushToLogQueue(e){e&&(this._logQueue.push(e),this._shouldUploadImmediately()&&this._uploadSSOLogData())}_shouldUploadImmediately(){return this._logQueue.length>=this._minThreshold}_isReportDue(){return Date.now()>=this._lastReportAt+this._waitingTime}_checkAndReportIfDue(){this._isReportDue()&&this._logQueue.length>0&&this._uploadSSOLogData()}_uploadSSOLogData(){return a(this,void 0,void 0,(function*(){if(0===this._logQueue.length)return;const e=this._logQueue.slice(),t=this._filterLogs(e);if(this._logQueue=[],0===t.length)return void(this._lastReportAt=Date.now());const s={Header:ct(),Event:t};yield function(e){const t="imopenstat.tim_web_report_v2",s=Qe({servcmd:t,data:e}),o=`${s.head.seq}${t}`;Gt.sendPacket(s,{requestId:o})}(s),this._lastReportAt=Date.now()}))}_savePlatFormInfo(){var e,t;if(C){const s=null===(t=null===(e=wx.getAccountInfoSync)||void 0===e?void 0:e.call(wx))||void 0===t?void 0:t.miniProgram;if(s){const{appId:e,envVersion:t}=s;De.set("instance",{appId:e,envVersion:t})}}else G&&De.set("instance",{href:window.location.href})}_filterLogs(e){const{tinyID:t}=De.get("login")||{},{sdkAppId:s}=De.get("instance")||{};return this._sdkAppIdBlackList.includes(s)&&!this._tinyIdWhiteList.includes(t)?[]:e.filter((e=>this._reportLevel.includes(e.level)))}reset(){console.log("SSO_LOG_MODULE.reset"),Ye.removeTask(_t),i.unSubscribeInnerEvent(lt.CLOUD_CONFIG_UPDATE,this._handleCloudConfigUpdate,this),this._lastReportAt=0,this._uploadSSOLogData(),this._sdkAppIdBlackList=[],this._tinyIdWhiteList=[],this._minThreshold=ut,this._maxThreshold=100,this._waitingTime=dt,this._logQueue=[]}};const ft=15e3,vt="Channel",It="channel_schedule_task",St="channel_reconnect_task",Et="connected",Ct="connecting",yt="disconnected",Mt=500,At="network_status_change",Ot="activity_status_change",Tt="send_fail",Dt="reconnect_failed",Rt="socket_error",Lt="socket_close";function Nt(e){return Nt="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},Nt(e)}function bt(e){throw new Error('Could not dynamically require "'+e+'". Please configure the dynamicRequireTargets or/and ignoreDynamicRequires option of @rollup/plugin-commonjs appropriately for this require call to work.')}var wt,Pt={exports:{}};var Ut=(wt||(wt=1,function(e){e.exports=function e(t,s,o){function n(r,a){if(!s[r]){if(!t[r]){if(!a&&bt)return bt(r);if(i)return i(r,!0);var c=new Error("Cannot find module '"+r+"'");throw c.code="MODULE_NOT_FOUND",c}var l=s[r]={exports:{}};t[r][0].call(l.exports,(function(e){return n(t[r][1][e]||e)}),l,l.exports,e,t,s,o)}return s[r].exports}for(var i=bt,r=0;r<o.length;r++)n(o[r]);return n}({1:[function(e,t,s){var o="undefined"!=typeof Uint8Array&&"undefined"!=typeof Uint16Array&&"undefined"!=typeof Int32Array;s.assign=function(e){for(var t,s,o=Array.prototype.slice.call(arguments,1);o.length;){var n=o.shift();if(n){if("object"!=Nt(n))throw new TypeError(n+"must be non-object");for(var i in n)t=n,s=i,Object.prototype.hasOwnProperty.call(t,s)&&(e[i]=n[i])}}return e},s.shrinkBuf=function(e,t){return e.length===t?e:e.subarray?e.subarray(0,t):(e.length=t,e)};var n={arraySet:function(e,t,s,o,n){if(t.subarray&&e.subarray)e.set(t.subarray(s,s+o),n);else for(var i=0;i<o;i++)e[n+i]=t[s+i]},flattenChunks:function(e){var t,s,o,n,i,r;for(t=o=0,s=e.length;t<s;t++)o+=e[t].length;for(r=new Uint8Array(o),t=n=0,s=e.length;t<s;t++)i=e[t],r.set(i,n),n+=i.length;return r}},i={arraySet:function(e,t,s,o,n){for(var i=0;i<o;i++)e[n+i]=t[s+i]},flattenChunks:function(e){return[].concat.apply([],e)}};s.setTyped=function(e){e?(s.Buf8=Uint8Array,s.Buf16=Uint16Array,s.Buf32=Int32Array,s.assign(s,n)):(s.Buf8=Array,s.Buf16=Array,s.Buf32=Array,s.assign(s,i))},s.setTyped(o)},{}],2:[function(e,t,s){var o=e("./common"),n=!0,i=!0;try{String.fromCharCode.apply(null,[0])}catch(e){n=!1}try{String.fromCharCode.apply(null,new Uint8Array(1))}catch(e){i=!1}for(var r=new o.Buf8(256),a=0;a<256;a++)r[a]=252<=a?6:248<=a?5:240<=a?4:224<=a?3:192<=a?2:1;function c(e,t){if(t<65534&&(e.subarray&&i||!e.subarray&&n))return String.fromCharCode.apply(null,o.shrinkBuf(e,t));for(var s="",r=0;r<t;r++)s+=String.fromCharCode(e[r]);return s}r[254]=r[254]=1,s.string2buf=function(e){var t,s,n,i,r,a=e.length,c=0;for(i=0;i<a;i++)55296==(64512&(s=e.charCodeAt(i)))&&i+1<a&&56320==(64512&(n=e.charCodeAt(i+1)))&&(s=65536+(s-55296<<10)+(n-56320),i++),c+=s<128?1:s<2048?2:s<65536?3:4;for(t=new o.Buf8(c),i=r=0;r<c;i++)55296==(64512&(s=e.charCodeAt(i)))&&i+1<a&&56320==(64512&(n=e.charCodeAt(i+1)))&&(s=65536+(s-55296<<10)+(n-56320),i++),s<128?t[r++]=s:(s<2048?t[r++]=192|s>>>6:(s<65536?t[r++]=224|s>>>12:(t[r++]=240|s>>>18,t[r++]=128|s>>>12&63),t[r++]=128|s>>>6&63),t[r++]=128|63&s);return t},s.buf2binstring=function(e){return c(e,e.length)},s.binstring2buf=function(e){for(var t=new o.Buf8(e.length),s=0,n=t.length;s<n;s++)t[s]=e.charCodeAt(s);return t},s.buf2string=function(e,t){var s,o,n,i,a=t||e.length,l=new Array(2*a);for(s=o=0;s<a;)if((n=e[s++])<128)l[o++]=n;else if(4<(i=r[n]))l[o++]=65533,s+=i-1;else{for(n&=2===i?31:3===i?15:7;1<i&&s<a;)n=n<<6|63&e[s++],i--;1<i?l[o++]=65533:n<65536?l[o++]=n:(n-=65536,l[o++]=55296|n>>10&1023,l[o++]=56320|1023&n)}return c(l,o)},s.utf8border=function(e,t){var s;for((t=t||e.length)>e.length&&(t=e.length),s=t-1;0<=s&&128==(192&e[s]);)s--;return s<0||0===s?t:s+r[e[s]]>t?s:t}},{"./common":1}],3:[function(e,t,s){t.exports=function(e,t,s,o){for(var n=65535&e,i=e>>>16&65535,r=0;0!==s;){for(s-=r=2e3<s?2e3:s;i=i+(n=n+t[o++]|0)|0,--r;);n%=65521,i%=65521}return n|i<<16}},{}],4:[function(e,t,s){t.exports={Z_NO_FLUSH:0,Z_PARTIAL_FLUSH:1,Z_SYNC_FLUSH:2,Z_FULL_FLUSH:3,Z_FINISH:4,Z_BLOCK:5,Z_TREES:6,Z_OK:0,Z_STREAM_END:1,Z_NEED_DICT:2,Z_ERRNO:-1,Z_STREAM_ERROR:-2,Z_DATA_ERROR:-3,Z_BUF_ERROR:-5,Z_NO_COMPRESSION:0,Z_BEST_SPEED:1,Z_BEST_COMPRESSION:9,Z_DEFAULT_COMPRESSION:-1,Z_FILTERED:1,Z_HUFFMAN_ONLY:2,Z_RLE:3,Z_FIXED:4,Z_DEFAULT_STRATEGY:0,Z_BINARY:0,Z_TEXT:1,Z_UNKNOWN:2,Z_DEFLATED:8}},{}],5:[function(e,t,s){var o=function(){for(var e,t=[],s=0;s<256;s++){e=s;for(var o=0;o<8;o++)e=1&e?3988292384^e>>>1:e>>>1;t[s]=e}return t}();t.exports=function(e,t,s,n){var i=o,r=n+s;e^=-1;for(var a=n;a<r;a++)e=e>>>8^i[255&(e^t[a])];return~e}},{}],6:[function(e,t,s){t.exports=function(){this.text=0,this.time=0,this.xflags=0,this.os=0,this.extra=null,this.extra_len=0,this.name="",this.comment="",this.hcrc=0,this.done=!1}},{}],7:[function(e,t,s){t.exports=function(e,t){var s,o,n,i,r,a,c,l,u,d,h,p,g,_,m,f,v,I,S,E,C,y,M,A,O;s=e.state,o=e.next_in,A=e.input,n=o+(e.avail_in-5),i=e.next_out,O=e.output,r=i-(t-e.avail_out),a=i+(e.avail_out-257),c=s.dmax,l=s.wsize,u=s.whave,d=s.wnext,h=s.window,p=s.hold,g=s.bits,_=s.lencode,m=s.distcode,f=(1<<s.lenbits)-1,v=(1<<s.distbits)-1;e:do{g<15&&(p+=A[o++]<<g,g+=8,p+=A[o++]<<g,g+=8),I=_[p&f];t:for(;;){if(p>>>=S=I>>>24,g-=S,0==(S=I>>>16&255))O[i++]=65535&I;else{if(!(16&S)){if(!(64&S)){I=_[(65535&I)+(p&(1<<S)-1)];continue t}if(32&S){s.mode=12;break e}e.msg="invalid literal/length code",s.mode=30;break e}E=65535&I,(S&=15)&&(g<S&&(p+=A[o++]<<g,g+=8),E+=p&(1<<S)-1,p>>>=S,g-=S),g<15&&(p+=A[o++]<<g,g+=8,p+=A[o++]<<g,g+=8),I=m[p&v];s:for(;;){if(p>>>=S=I>>>24,g-=S,!(16&(S=I>>>16&255))){if(!(64&S)){I=m[(65535&I)+(p&(1<<S)-1)];continue s}e.msg="invalid distance code",s.mode=30;break e}if(C=65535&I,g<(S&=15)&&(p+=A[o++]<<g,(g+=8)<S&&(p+=A[o++]<<g,g+=8)),c<(C+=p&(1<<S)-1)){e.msg="invalid distance too far back",s.mode=30;break e}if(p>>>=S,g-=S,(S=i-r)<C){if(u<(S=C-S)&&s.sane){e.msg="invalid distance too far back",s.mode=30;break e}if(M=h,(y=0)===d){if(y+=l-S,S<E){for(E-=S;O[i++]=h[y++],--S;);y=i-C,M=O}}else if(d<S){if(y+=l+d-S,(S-=d)<E){for(E-=S;O[i++]=h[y++],--S;);if(y=0,d<E){for(E-=S=d;O[i++]=h[y++],--S;);y=i-C,M=O}}}else if(y+=d-S,S<E){for(E-=S;O[i++]=h[y++],--S;);y=i-C,M=O}for(;2<E;)O[i++]=M[y++],O[i++]=M[y++],O[i++]=M[y++],E-=3;E&&(O[i++]=M[y++],1<E&&(O[i++]=M[y++]))}else{for(y=i-C;O[i++]=O[y++],O[i++]=O[y++],O[i++]=O[y++],2<(E-=3););E&&(O[i++]=O[y++],1<E&&(O[i++]=O[y++]))}break}}break}}while(o<n&&i<a);o-=E=g>>3,p&=(1<<(g-=E<<3))-1,e.next_in=o,e.next_out=i,e.avail_in=o<n?n-o+5:5-(o-n),e.avail_out=i<a?a-i+257:257-(i-a),s.hold=p,s.bits=g}},{}],8:[function(e,t,s){var o=e("../utils/common"),n=e("./adler32"),i=e("./crc32"),r=e("./inffast"),a=e("./inftrees"),c=1,l=2,u=0,d=-2,h=1,p=852,g=592;function _(e){return(e>>>24&255)+(e>>>8&65280)+((65280&e)<<8)+((255&e)<<24)}function m(){this.mode=0,this.last=!1,this.wrap=0,this.havedict=!1,this.flags=0,this.dmax=0,this.check=0,this.total=0,this.head=null,this.wbits=0,this.wsize=0,this.whave=0,this.wnext=0,this.window=null,this.hold=0,this.bits=0,this.length=0,this.offset=0,this.extra=0,this.lencode=null,this.distcode=null,this.lenbits=0,this.distbits=0,this.ncode=0,this.nlen=0,this.ndist=0,this.have=0,this.next=null,this.lens=new o.Buf16(320),this.work=new o.Buf16(288),this.lendyn=null,this.distdyn=null,this.sane=0,this.back=0,this.was=0}function f(e){var t;return e&&e.state?(t=e.state,e.total_in=e.total_out=t.total=0,e.msg="",t.wrap&&(e.adler=1&t.wrap),t.mode=h,t.last=0,t.havedict=0,t.dmax=32768,t.head=null,t.hold=0,t.bits=0,t.lencode=t.lendyn=new o.Buf32(p),t.distcode=t.distdyn=new o.Buf32(g),t.sane=1,t.back=-1,u):d}function v(e){var t;return e&&e.state?((t=e.state).wsize=0,t.whave=0,t.wnext=0,f(e)):d}function I(e,t){var s,o;return e&&e.state?(o=e.state,t<0?(s=0,t=-t):(s=1+(t>>4),t<48&&(t&=15)),t&&(t<8||15<t)?d:(null!==o.window&&o.wbits!==t&&(o.window=null),o.wrap=s,o.wbits=t,v(e))):d}function S(e,t){var s,o;return e?(o=new m,(e.state=o).window=null,(s=I(e,t))!==u&&(e.state=null),s):d}var E,C,y=!0;function M(e){if(y){var t;for(E=new o.Buf32(512),C=new o.Buf32(32),t=0;t<144;)e.lens[t++]=8;for(;t<256;)e.lens[t++]=9;for(;t<280;)e.lens[t++]=7;for(;t<288;)e.lens[t++]=8;for(a(c,e.lens,0,288,E,0,e.work,{bits:9}),t=0;t<32;)e.lens[t++]=5;a(l,e.lens,0,32,C,0,e.work,{bits:5}),y=!1}e.lencode=E,e.lenbits=9,e.distcode=C,e.distbits=5}function A(e,t,s,n){var i,r=e.state;return null===r.window&&(r.wsize=1<<r.wbits,r.wnext=0,r.whave=0,r.window=new o.Buf8(r.wsize)),n>=r.wsize?(o.arraySet(r.window,t,s-r.wsize,r.wsize,0),r.wnext=0,r.whave=r.wsize):(n<(i=r.wsize-r.wnext)&&(i=n),o.arraySet(r.window,t,s-n,i,r.wnext),(n-=i)?(o.arraySet(r.window,t,s-n,n,0),r.wnext=n,r.whave=r.wsize):(r.wnext+=i,r.wnext===r.wsize&&(r.wnext=0),r.whave<r.wsize&&(r.whave+=i))),0}s.inflateReset=v,s.inflateReset2=I,s.inflateResetKeep=f,s.inflateInit=function(e){return S(e,15)},s.inflateInit2=S,s.inflate=function(e,t){var s,p,g,m,f,v,I,S,E,C,y,O,T,D,R,L,N,b,w,P,U,G,k,F,$=0,q=new o.Buf8(4),x=[16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15];if(!e||!e.state||!e.output||!e.input&&0!==e.avail_in)return d;12===(s=e.state).mode&&(s.mode=13),f=e.next_out,g=e.output,I=e.avail_out,m=e.next_in,p=e.input,v=e.avail_in,S=s.hold,E=s.bits,C=v,y=I,G=u;e:for(;;)switch(s.mode){case h:if(0===s.wrap){s.mode=13;break}for(;E<16;){if(0===v)break e;v--,S+=p[m++]<<E,E+=8}if(2&s.wrap&&35615===S){q[s.check=0]=255&S,q[1]=S>>>8&255,s.check=i(s.check,q,2,0),E=S=0,s.mode=2;break}if(s.flags=0,s.head&&(s.head.done=!1),!(1&s.wrap)||(((255&S)<<8)+(S>>8))%31){e.msg="incorrect header check",s.mode=30;break}if(8!=(15&S)){e.msg="unknown compression method",s.mode=30;break}if(E-=4,U=8+(15&(S>>>=4)),0===s.wbits)s.wbits=U;else if(U>s.wbits){e.msg="invalid window size",s.mode=30;break}s.dmax=1<<U,e.adler=s.check=1,s.mode=512&S?10:12,E=S=0;break;case 2:for(;E<16;){if(0===v)break e;v--,S+=p[m++]<<E,E+=8}if(s.flags=S,8!=(255&s.flags)){e.msg="unknown compression method",s.mode=30;break}if(57344&s.flags){e.msg="unknown header flags set",s.mode=30;break}s.head&&(s.head.text=S>>8&1),512&s.flags&&(q[0]=255&S,q[1]=S>>>8&255,s.check=i(s.check,q,2,0)),E=S=0,s.mode=3;case 3:for(;E<32;){if(0===v)break e;v--,S+=p[m++]<<E,E+=8}s.head&&(s.head.time=S),512&s.flags&&(q[0]=255&S,q[1]=S>>>8&255,q[2]=S>>>16&255,q[3]=S>>>24&255,s.check=i(s.check,q,4,0)),E=S=0,s.mode=4;case 4:for(;E<16;){if(0===v)break e;v--,S+=p[m++]<<E,E+=8}s.head&&(s.head.xflags=255&S,s.head.os=S>>8),512&s.flags&&(q[0]=255&S,q[1]=S>>>8&255,s.check=i(s.check,q,2,0)),E=S=0,s.mode=5;case 5:if(1024&s.flags){for(;E<16;){if(0===v)break e;v--,S+=p[m++]<<E,E+=8}s.length=S,s.head&&(s.head.extra_len=S),512&s.flags&&(q[0]=255&S,q[1]=S>>>8&255,s.check=i(s.check,q,2,0)),E=S=0}else s.head&&(s.head.extra=null);s.mode=6;case 6:if(1024&s.flags&&(v<(O=s.length)&&(O=v),O&&(s.head&&(U=s.head.extra_len-s.length,s.head.extra||(s.head.extra=new Array(s.head.extra_len)),o.arraySet(s.head.extra,p,m,O,U)),512&s.flags&&(s.check=i(s.check,p,O,m)),v-=O,m+=O,s.length-=O),s.length))break e;s.length=0,s.mode=7;case 7:if(2048&s.flags){if(0===v)break e;for(O=0;U=p[m+O++],s.head&&U&&s.length<65536&&(s.head.name+=String.fromCharCode(U)),U&&O<v;);if(512&s.flags&&(s.check=i(s.check,p,O,m)),v-=O,m+=O,U)break e}else s.head&&(s.head.name=null);s.length=0,s.mode=8;case 8:if(4096&s.flags){if(0===v)break e;for(O=0;U=p[m+O++],s.head&&U&&s.length<65536&&(s.head.comment+=String.fromCharCode(U)),U&&O<v;);if(512&s.flags&&(s.check=i(s.check,p,O,m)),v-=O,m+=O,U)break e}else s.head&&(s.head.comment=null);s.mode=9;case 9:if(512&s.flags){for(;E<16;){if(0===v)break e;v--,S+=p[m++]<<E,E+=8}if(S!==(65535&s.check)){e.msg="header crc mismatch",s.mode=30;break}E=S=0}s.head&&(s.head.hcrc=s.flags>>9&1,s.head.done=!0),e.adler=s.check=0,s.mode=12;break;case 10:for(;E<32;){if(0===v)break e;v--,S+=p[m++]<<E,E+=8}e.adler=s.check=_(S),E=S=0,s.mode=11;case 11:if(0===s.havedict)return e.next_out=f,e.avail_out=I,e.next_in=m,e.avail_in=v,s.hold=S,s.bits=E,2;e.adler=s.check=1,s.mode=12;case 12:if(5===t||6===t)break e;case 13:if(s.last){S>>>=7&E,E-=7&E,s.mode=27;break}for(;E<3;){if(0===v)break e;v--,S+=p[m++]<<E,E+=8}switch(s.last=1&S,E-=1,3&(S>>>=1)){case 0:s.mode=14;break;case 1:if(M(s),s.mode=20,6!==t)break;S>>>=2,E-=2;break e;case 2:s.mode=17;break;case 3:e.msg="invalid block type",s.mode=30}S>>>=2,E-=2;break;case 14:for(S>>>=7&E,E-=7&E;E<32;){if(0===v)break e;v--,S+=p[m++]<<E,E+=8}if((65535&S)!=(S>>>16^65535)){e.msg="invalid stored block lengths",s.mode=30;break}if(s.length=65535&S,E=S=0,s.mode=15,6===t)break e;case 15:s.mode=16;case 16:if(O=s.length){if(v<O&&(O=v),I<O&&(O=I),0===O)break e;o.arraySet(g,p,m,O,f),v-=O,m+=O,I-=O,f+=O,s.length-=O;break}s.mode=12;break;case 17:for(;E<14;){if(0===v)break e;v--,S+=p[m++]<<E,E+=8}if(s.nlen=257+(31&S),S>>>=5,E-=5,s.ndist=1+(31&S),S>>>=5,E-=5,s.ncode=4+(15&S),S>>>=4,E-=4,286<s.nlen||30<s.ndist){e.msg="too many length or distance symbols",s.mode=30;break}s.have=0,s.mode=18;case 18:for(;s.have<s.ncode;){for(;E<3;){if(0===v)break e;v--,S+=p[m++]<<E,E+=8}s.lens[x[s.have++]]=7&S,S>>>=3,E-=3}for(;s.have<19;)s.lens[x[s.have++]]=0;if(s.lencode=s.lendyn,s.lenbits=7,k={bits:s.lenbits},G=a(0,s.lens,0,19,s.lencode,0,s.work,k),s.lenbits=k.bits,G){e.msg="invalid code lengths set",s.mode=30;break}s.have=0,s.mode=19;case 19:for(;s.have<s.nlen+s.ndist;){for(;L=($=s.lencode[S&(1<<s.lenbits)-1])>>>16&255,N=65535&$,!((R=$>>>24)<=E);){if(0===v)break e;v--,S+=p[m++]<<E,E+=8}if(N<16)S>>>=R,E-=R,s.lens[s.have++]=N;else{if(16===N){for(F=R+2;E<F;){if(0===v)break e;v--,S+=p[m++]<<E,E+=8}if(S>>>=R,E-=R,0===s.have){e.msg="invalid bit length repeat",s.mode=30;break}U=s.lens[s.have-1],O=3+(3&S),S>>>=2,E-=2}else if(17===N){for(F=R+3;E<F;){if(0===v)break e;v--,S+=p[m++]<<E,E+=8}E-=R,U=0,O=3+(7&(S>>>=R)),S>>>=3,E-=3}else{for(F=R+7;E<F;){if(0===v)break e;v--,S+=p[m++]<<E,E+=8}E-=R,U=0,O=11+(127&(S>>>=R)),S>>>=7,E-=7}if(s.have+O>s.nlen+s.ndist){e.msg="invalid bit length repeat",s.mode=30;break}for(;O--;)s.lens[s.have++]=U}}if(30===s.mode)break;if(0===s.lens[256]){e.msg="invalid code -- missing end-of-block",s.mode=30;break}if(s.lenbits=9,k={bits:s.lenbits},G=a(c,s.lens,0,s.nlen,s.lencode,0,s.work,k),s.lenbits=k.bits,G){e.msg="invalid literal/lengths set",s.mode=30;break}if(s.distbits=6,s.distcode=s.distdyn,k={bits:s.distbits},G=a(l,s.lens,s.nlen,s.ndist,s.distcode,0,s.work,k),s.distbits=k.bits,G){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<=v&&258<=I){e.next_out=f,e.avail_out=I,e.next_in=m,e.avail_in=v,s.hold=S,s.bits=E,r(e,y),f=e.next_out,g=e.output,I=e.avail_out,m=e.next_in,p=e.input,v=e.avail_in,S=s.hold,E=s.bits,12===s.mode&&(s.back=-1);break}for(s.back=0;L=($=s.lencode[S&(1<<s.lenbits)-1])>>>16&255,N=65535&$,!((R=$>>>24)<=E);){if(0===v)break e;v--,S+=p[m++]<<E,E+=8}if(L&&!(240&L)){for(b=R,w=L,P=N;L=($=s.lencode[P+((S&(1<<b+w)-1)>>b)])>>>16&255,N=65535&$,!(b+(R=$>>>24)<=E);){if(0===v)break e;v--,S+=p[m++]<<E,E+=8}S>>>=b,E-=b,s.back+=b}if(S>>>=R,E-=R,s.back+=R,s.length=N,0===L){s.mode=26;break}if(32&L){s.back=-1,s.mode=12;break}if(64&L){e.msg="invalid literal/length code",s.mode=30;break}s.extra=15&L,s.mode=22;case 22:if(s.extra){for(F=s.extra;E<F;){if(0===v)break e;v--,S+=p[m++]<<E,E+=8}s.length+=S&(1<<s.extra)-1,S>>>=s.extra,E-=s.extra,s.back+=s.extra}s.was=s.length,s.mode=23;case 23:for(;L=($=s.distcode[S&(1<<s.distbits)-1])>>>16&255,N=65535&$,!((R=$>>>24)<=E);){if(0===v)break e;v--,S+=p[m++]<<E,E+=8}if(!(240&L)){for(b=R,w=L,P=N;L=($=s.distcode[P+((S&(1<<b+w)-1)>>b)])>>>16&255,N=65535&$,!(b+(R=$>>>24)<=E);){if(0===v)break e;v--,S+=p[m++]<<E,E+=8}S>>>=b,E-=b,s.back+=b}if(S>>>=R,E-=R,s.back+=R,64&L){e.msg="invalid distance code",s.mode=30;break}s.offset=N,s.extra=15&L,s.mode=24;case 24:if(s.extra){for(F=s.extra;E<F;){if(0===v)break e;v--,S+=p[m++]<<E,E+=8}s.offset+=S&(1<<s.extra)-1,S>>>=s.extra,E-=s.extra,s.back+=s.extra}if(s.offset>s.dmax){e.msg="invalid distance too far back",s.mode=30;break}s.mode=25;case 25:if(0===I)break e;if(O=y-I,s.offset>O){if((O=s.offset-O)>s.whave&&s.sane){e.msg="invalid distance too far back",s.mode=30;break}O>s.wnext?(O-=s.wnext,T=s.wsize-O):T=s.wnext-O,O>s.length&&(O=s.length),D=s.window}else D=g,T=f-s.offset,O=s.length;for(I<O&&(O=I),I-=O,s.length-=O;g[f++]=D[T++],--O;);0===s.length&&(s.mode=21);break;case 26:if(0===I)break e;g[f++]=s.length,I--,s.mode=21;break;case 27:if(s.wrap){for(;E<32;){if(0===v)break e;v--,S|=p[m++]<<E,E+=8}if(y-=I,e.total_out+=y,s.total+=y,y&&(e.adler=s.check=s.flags?i(s.check,g,y,f-y):n(s.check,g,y,f-y)),y=I,(s.flags?S:_(S))!==s.check){e.msg="incorrect data check",s.mode=30;break}E=S=0}s.mode=28;case 28:if(s.wrap&&s.flags){for(;E<32;){if(0===v)break e;v--,S+=p[m++]<<E,E+=8}if(S!==(4294967295&s.total)){e.msg="incorrect length check",s.mode=30;break}E=S=0}s.mode=29;case 29:G=1;break e;case 30:G=-3;break e;case 31:return-4;default:return d}return e.next_out=f,e.avail_out=I,e.next_in=m,e.avail_in=v,s.hold=S,s.bits=E,(s.wsize||y!==e.avail_out&&s.mode<30&&(s.mode<27||4!==t))&&A(e,e.output,e.next_out,y-e.avail_out)?(s.mode=31,-4):(C-=e.avail_in,y-=e.avail_out,e.total_in+=C,e.total_out+=y,s.total+=y,s.wrap&&y&&(e.adler=s.check=s.flags?i(s.check,g,y,e.next_out-y):n(s.check,g,y,e.next_out-y)),e.data_type=s.bits+(s.last?64:0)+(12===s.mode?128:0)+(20===s.mode||15===s.mode?256:0),(0===C&&0===y||4===t)&&G===u&&(G=-5),G)},s.inflateEnd=function(e){if(!e||!e.state)return d;var t=e.state;return t.window&&(t.window=null),e.state=null,u},s.inflateGetHeader=function(e,t){var s;return e&&e.state&&2&(s=e.state).wrap?((s.head=t).done=!1,u):d},s.inflateSetDictionary=function(e,t){var s,o=t.length;return e&&e.state?0!==(s=e.state).wrap&&11!==s.mode?d:11===s.mode&&n(1,t,o,0)!==s.check?-3:A(e,t,o,o)?(s.mode=31,-4):(s.havedict=1,u):d},s.inflateInfo="pako inflate (from Nodeca project)"},{"../utils/common":1,"./adler32":3,"./crc32":5,"./inffast":7,"./inftrees":9}],9:[function(e,t,s){var o=e("../utils/common"),n=[3,4,5,6,7,8,9,10,11,13,15,17,19,23,27,31,35,43,51,59,67,83,99,115,131,163,195,227,258,0,0],i=[16,16,16,16,16,16,16,16,17,17,17,17,18,18,18,18,19,19,19,19,20,20,20,20,21,21,21,21,16,72,78],r=[1,2,3,4,5,7,9,13,17,25,33,49,65,97,129,193,257,385,513,769,1025,1537,2049,3073,4097,6145,8193,12289,16385,24577,0,0],a=[16,16,16,16,17,17,18,18,19,19,20,20,21,21,22,22,23,23,24,24,25,25,26,26,27,27,28,28,29,29,64,64];t.exports=function(e,t,s,c,l,u,d,h){var p,g,_,m,f,v,I,S,E,C=h.bits,y=0,M=0,A=0,O=0,T=0,D=0,R=0,L=0,N=0,b=0,w=null,P=0,U=new o.Buf16(16),G=new o.Buf16(16),k=null,F=0;for(y=0;y<=15;y++)U[y]=0;for(M=0;M<c;M++)U[t[s+M]]++;for(T=C,O=15;1<=O&&0===U[O];O--);if(O<T&&(T=O),0===O)return l[u++]=20971520,l[u++]=20971520,h.bits=1,0;for(A=1;A<O&&0===U[A];A++);for(T<A&&(T=A),y=L=1;y<=15;y++)if(L<<=1,(L-=U[y])<0)return-1;if(0<L&&(0===e||1!==O))return-1;for(G[1]=0,y=1;y<15;y++)G[y+1]=G[y]+U[y];for(M=0;M<c;M++)0!==t[s+M]&&(d[G[t[s+M]]++]=M);if(0===e?(w=k=d,v=19):1===e?(w=n,P-=257,k=i,F-=257,v=256):(w=r,k=a,v=-1),y=A,f=u,R=M=b=0,_=-1,m=(N=1<<(D=T))-1,1===e&&852<N||2===e&&592<N)return 1;for(;;){for(I=y-R,d[M]<v?(S=0,E=d[M]):d[M]>v?(S=k[F+d[M]],E=w[P+d[M]]):(S=96,E=0),p=1<<y-R,A=g=1<<D;l[f+(b>>R)+(g-=p)]=I<<24|S<<16|E,0!==g;);for(p=1<<y-1;b&p;)p>>=1;if(0!==p?(b&=p-1,b+=p):b=0,M++,0==--U[y]){if(y===O)break;y=t[s+d[M]]}if(T<y&&(b&m)!==_){for(0===R&&(R=T),f+=A,L=1<<(D=y-R);D+R<O&&!((L-=U[D+R])<=0);)D++,L<<=1;if(N+=1<<D,1===e&&852<N||2===e&&592<N)return 1;l[_=b&m]=T<<24|D<<16|f-u}}return 0!==b&&(l[f+b]=y-R<<24|64<<16),h.bits=T,0}},{"../utils/common":1}],10:[function(e,t,s){t.exports={2:"need dictionary",1:"stream end",0:"","-1":"file error","-2":"stream error","-3":"data error","-4":"insufficient memory","-5":"buffer error","-6":"incompatible version"}},{}],11:[function(e,t,s){t.exports=function(){this.input=null,this.next_in=0,this.avail_in=0,this.total_in=0,this.output=null,this.next_out=0,this.avail_out=0,this.total_out=0,this.msg="",this.state=null,this.data_type=2,this.adler=0}},{}],"/lib/inflate.js":[function(e,t,s){var o=e("./zlib/inflate"),n=e("./utils/common"),i=e("./utils/strings"),r=e("./zlib/constants"),a=e("./zlib/messages"),c=e("./zlib/zstream"),l=e("./zlib/gzheader"),u=Object.prototype.toString;function d(e){if(!(this instanceof d))return new d(e);this.options=n.assign({chunkSize:16384,windowBits:0,to:""},e||{});var t=this.options;t.raw&&0<=t.windowBits&&t.windowBits<16&&(t.windowBits=-t.windowBits,0===t.windowBits&&(t.windowBits=-15)),!(0<=t.windowBits&&t.windowBits<16)||e&&e.windowBits||(t.windowBits+=32),15<t.windowBits&&t.windowBits<48&&!(15&t.windowBits)&&(t.windowBits|=15),this.err=0,this.msg="",this.ended=!1,this.chunks=[],this.strm=new c,this.strm.avail_out=0;var s=o.inflateInit2(this.strm,t.windowBits);if(s!==r.Z_OK)throw new Error(a[s]);if(this.header=new l,o.inflateGetHeader(this.strm,this.header),t.dictionary&&("string"==typeof t.dictionary?t.dictionary=i.string2buf(t.dictionary):"[object ArrayBuffer]"===u.call(t.dictionary)&&(t.dictionary=new Uint8Array(t.dictionary)),t.raw&&(s=o.inflateSetDictionary(this.strm,t.dictionary))!==r.Z_OK))throw new Error(a[s])}function h(e,t){var s=new d(t);if(s.push(e,!0),s.err)throw s.msg||a[s.err];return s.result}d.prototype.push=function(e,t){var s,a,c,l,d,h=this.strm,p=this.options.chunkSize,g=this.options.dictionary,_=!1;if(this.ended)return!1;a=t===~~t?t:!0===t?r.Z_FINISH:r.Z_NO_FLUSH,"string"==typeof e?h.input=i.binstring2buf(e):"[object ArrayBuffer]"===u.call(e)?h.input=new Uint8Array(e):h.input=e,h.next_in=0,h.avail_in=h.input.length;do{if(0===h.avail_out&&(h.output=new n.Buf8(p),h.next_out=0,h.avail_out=p),(s=o.inflate(h,r.Z_NO_FLUSH))===r.Z_NEED_DICT&&g&&(s=o.inflateSetDictionary(this.strm,g)),s===r.Z_BUF_ERROR&&!0===_&&(s=r.Z_OK,_=!1),s!==r.Z_STREAM_END&&s!==r.Z_OK)return this.onEnd(s),!(this.ended=!0);h.next_out&&(0!==h.avail_out&&s!==r.Z_STREAM_END&&(0!==h.avail_in||a!==r.Z_FINISH&&a!==r.Z_SYNC_FLUSH)||("string"===this.options.to?(c=i.utf8border(h.output,h.next_out),l=h.next_out-c,d=i.buf2string(h.output,c),h.next_out=l,h.avail_out=p-l,l&&n.arraySet(h.output,h.output,c,l,0),this.onData(d)):this.onData(n.shrinkBuf(h.output,h.next_out)))),0===h.avail_in&&0===h.avail_out&&(_=!0)}while((0<h.avail_in||0===h.avail_out)&&s!==r.Z_STREAM_END);return s===r.Z_STREAM_END&&(a=r.Z_FINISH),a===r.Z_FINISH?(s=o.inflateEnd(this.strm),this.onEnd(s),this.ended=!0,s===r.Z_OK):a!==r.Z_SYNC_FLUSH||(this.onEnd(r.Z_OK),!(h.avail_out=0))},d.prototype.onData=function(e){this.chunks.push(e)},d.prototype.onEnd=function(e){e===r.Z_OK&&("string"===this.options.to?this.result=this.chunks.join(""):this.result=n.flattenChunks(this.chunks)),this.chunks=[],this.err=e,this.msg=this.strm.msg},s.Inflate=d,s.inflate=h,s.inflateRaw=function(e,t){return(t=t||{}).raw=!0,h(e,t)},s.ungzip=h},{"./utils/common":1,"./utils/strings":2,"./zlib/constants":4,"./zlib/gzheader":6,"./zlib/inflate":8,"./zlib/messages":10,"./zlib/zstream":11}]},{},[])("/lib/inflate.js")}(Pt)),Pt.exports);var Gt=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=Mt,this._currentConnectState=Et,this._beforeSendInterceptors=[]}init(){Ye.addTask({id:It,intervalMs:1e3,callback:this._executeScheduledTaskIfReady,context:this}),this._updateIsBinarySupported(),this._url=function(e){const t=De.get("instance"),{sdkAppId:s,testEnv:o}=t,n=qe(s);return We(o?Fe.TEST[n].DEFAULT:Fe.PRODUCTION[n].INITIAL.replace("*",`${s}`),{isBinary:e})}(this._isBinarySupported),i.subscribeInnerEvent("networkStatusChange",this._handleNetworkStatusChange,this),i.subscribeInnerEvent("activityStatusChange",this._handleActivityStatusChange,this),this.connect()}sendPacket(e,t){var s;const{requestId:o,timeout:n=ft,canResend:i=!0}=t||{};if(he(e))return console.warn(`${vt}.sendPacket: packet is empty `,e),null;this._executeBeforeSendInterceptors(e);const r=JSON.stringify(e);let a=null;if(o){const{resolve:e,reject:t,promise:s}=ge();a=s,this._pendingRequests.set(o,{resolve:e,reject:t,timestamp:Date.now(),uplinkData:r,timeout:n,canResend:i})}const c=this._isBinarySupported?ze(r).buffer:r;return null===(s=this._socketAdapter)||void 0===s||s.send(c),a}connect(){var e;this._socketAdapter=new Re(this._url),this._connectionEstablishedTime=0,this._addEventListeners(),this._connectionStartTime=Date.now();const t=null===(e=this._socketAdapter)||void 0===e?void 0:e.getId(),s=`${vt}.connect isWorkerEnabled: false socketID:${t} url:${this._url}`;this._ssoLog({method:"connect",message:s}),console.log(s)}disconnect(){var e,t;const s=null===(e=this._socketAdapter)||void 0===e?void 0:e.getId(),o=`${vt}.disconnect socketID:${s}`;this._ssoLog({method:"disconnect",message:o}),console.log(o),this._removeEventListeners(),null===(t=this._socketAdapter)||void 0===t||t.disconnect()}getSocketAdapter(){return this._socketAdapter}dispose(){console.log(`${vt}.dispose`),Ye.removeTask(It),Ye.removeTask(St),i.unSubscribeInnerEvent("networkStatusChange",this._handleNetworkStatusChange,this),i.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=Mt,this._url=""}registerBeforeSendInterceptor(e,t){this._beforeSendInterceptors.push(e.bind(t))}_executeBeforeSendInterceptors(e){for(const t of this._beforeSendInterceptors){const{servcmd:s=""}=null==e?void 0:e.head;t(s.includes(".")?s.split(".").pop():"")}}_shouldSkipReconnect(){const e=this._currentConnectState===Ct&&this._isReconnecting;return!this._socketAdapter||e}reconnect(){return a(this,void 0,void 0,(function*(){const e=`${vt} reconnect isReconnecting: ${this._isReconnecting} currentConnectState: ${this._currentConnectState}`;if(this._ssoLog({method:"reconnect",message:e}),console.log(e),!this._shouldSkipReconnect()){this._url=function(e){const t=De.get("instance"),{sdkAppId:s,testEnv:o}=t,n=qe(s);if(o)return We(Fe.TEST[n].DEFAULT,{isBinary:e});const i=Fe.PRODUCTION[n],r=G&&i.ANYCAST;return We({[xe.INITIAL]:()=>(Be=xe.DEFAULT,i.DEFAULT),[xe.DEFAULT]:()=>(Be=xe.BACKUP,i.BACKUP),[xe.BACKUP]:()=>(Be=r?xe.ANYCAST:xe.DEFAULT,r?i.ANYCAST:i.DEFAULT),[xe.ANYCAST]:()=>(Be=xe.DEFAULT,i.ANYCAST="",i.DEFAULT)}[Be](),{isBinary:e})}(this._isBinarySupported);try{this._isReconnecting=!0,this.disconnect(),this.connect()}catch(e){this._isReconnecting=!1,this._handleConnectStateChange({state:yt,reason:Dt}),console.warn(`${vt} reconnect failed: `,e)}}}))}_addEventListeners(){var e,t,s,o,n;null===(e=this._socketAdapter)||void 0===e||e.on("connect",this._onConnect,this),null===(t=this._socketAdapter)||void 0===t||t.on("message",this._onMessage,this),null===(s=this._socketAdapter)||void 0===s||s.on("close",this._onClose,this),null===(o=this._socketAdapter)||void 0===o||o.on("error",this._onError,this),null===(n=this._socketAdapter)||void 0===n||n.on("sendFail",this._onSendFail,this)}_removeEventListeners(){var e,t,s,o,n;null===(e=this._socketAdapter)||void 0===e||e.off("connect",this._onConnect,this),null===(t=this._socketAdapter)||void 0===t||t.off("message",this._onMessage,this),null===(s=this._socketAdapter)||void 0===s||s.off("close",this._onClose,this),null===(o=this._socketAdapter)||void 0===o||o.off("error",this._onError,this),null===(n=this._socketAdapter)||void 0===n||n.off("sendFail",this._onSendFail,this)}_onClose(e){const{socketId:t,event:s}=e||{},o=0!==this._connectionEstablishedTime?Date.now()-this._connectionEstablishedTime:0,n=`${vt} onClose closeSocketID: ${t} currentSocketID: ${this._connectionId} connectionDuration: ${o} code:${null==s?void 0:s.code} reason:${null==s?void 0:s.reason}`;this._ssoLog({method:"onClose",message:n}),console.warn(n),t===this._connectionId&&this._handleConnectStateChange({state:yt,reason:Lt}),this._isReconnecting&&(this._isReconnecting=!1)}_onError(e){const{socketId:t,error:s}=e||{},o=`${vt} onError sourceSocketID: ${t} currentSocketID:${this._connectionId} isReconnecting: ${this._isReconnecting} error: ${JSON.stringify(s)}`;this._ssoLog({method:"onError",message:o}),console.warn(o),t===this._connectionId&&this._handleConnectStateChange({state:yt,reason:Rt}),this._isReconnecting&&(this._isReconnecting=!1)}_onSendFail(e){const{socketId:t,error:s}=e||{},o=`${vt} onSendFail sendFailSocketId: ${t} currentSocketID:${this._connectionId} isReconnecting: ${this._isReconnecting} error: ${s}`;this._ssoLog({method:"onSendFail",message:o}),console.warn(o),t===this._connectionId&&this._handleConnectStateChange({state:yt,reason:Tt}),this._isReconnecting&&(this._isReconnecting=!1)}_onMessage(e){let t,s;this._updateHeartbeatTime();try{t=this._isBinarySupported?this._isCompressedData(e.data)?(e=>{const t=new Uint8Array(e).slice(4);let s;try{s=Ut.inflate(t,{to:"string"})}catch(e){console.error("inflate error",e)}return s})(e.data):function(e){const t=new Uint8Array(e);let s="",o=0;const{length:n}=t;for(;o<n;){let e=t[o],i=0,r=0;if(e<=127?(i=0,r=255&e):e<=223?(i=1,r=31&e):e<=239?(i=2,r=15&e):e<=244&&(i=3,r=7&e),n-o-i>0)for(let s=0;s<i;s+=1)e=t[o+s+1],r=r<<6|63&e;else r=65533,i=n-o;s+=String.fromCodePoint(r),o+=i+1}return s}(e.data):e.data,s=JSON.parse(t)}catch(t){const s=e.data;return this._ssoLog({method:"jsonParseError",message:s}),void console.error(t)}if(!s||!s.head)return;const{seq:o,servcmd:n}=s.head,i=`${o}${n}`;this._pendingRequests.has(i)?this._handleRequestResponse(s):this._handlePushMessage(s)}_handleRequestResponse(e){const{seq:t,servcmd:s}=e.head,{int32_error_code:o,str_error_message:n,ErrorCode:r=o,ErrorInfo:a=n}=(null==e?void 0:e.body)||{},c=`${t}${s}`,{resolve:l,reject:u,timestamp:d,headSeq:h}=this._pendingRequests.get(c);if(this._pendingRequests.delete(c),r&&0!==r)return i.emitInnerEvent("error",{errorCode:r,errorInfo:a}),void u({errorCode:r,errorInfo:a});l(e.body)}_handlePushMessage(e){const{servcmd:t}=e.head,{NeedAck:s,SessionData:o}=e.body;1===s&&this._sendAck(o),i.emitInnerEvent(t,e)}_checkPendingRequestsAndResend(){var e;console.log(`${vt}._checkPendingRequestsAndResend reConnectFlag:${this._isReconnecting} promiseMap.size:${this._pendingRequests.size}`),null===(e=this._pendingRequests)||void 0===e||e.forEach(((e,t)=>{var s;const{uplinkData:o,canResend:n,resolve:i,reject:r,timeout:a}=e;if(n){this._pendingRequests.set(t,{resolve:i,reject:r,timestamp:Date.now(),uplinkData:o,timeout:a,canResend:n});const e=this._isBinarySupported?ze(o).buffer:o;null===(s=this._socketAdapter)||void 0===s||s.send(e)}else this._pendingRequests.delete(t)}))}_onConnect(e){const{socketId:t,event:s={}}=e||{};this._connectionId=t,this._connectionEstablishedTime=Date.now();const o=Date.now()-this._connectionStartTime,n=`${vt} onConnect cost:${o} ms. socketID:${t} res:${JSON.stringify(s)}`;if(this._ssoLog({method:"onConnect",message:n}),console.log(n),this._checkPendingRequestsAndResend(),this._sendHeartbeatIfReady(),this._isReconnecting){const e=`${vt} reconnect success`;this._ssoLog({method:"reconnectSuccess",message:e}),console.log(e),i.emitInnerEvent(lt.RECONNECTED),this._isReconnecting=!1}this._resetReconnectDelay(),this._handleConnectStateChange({state:Et})}_sendAck(e){const t=Xe({servcmd:"openim.ws_msg_push_ack",data:{SessionData:e}});this.sendPacket(t)}_executeScheduledTaskIfReady(){return a(this,void 0,void 0,(function*(){this._clearTimeoutRequest(),this._sendHeartbeatIfReady()}))}_canSendHeartbeat(){var e;return(null===(e=this._socketAdapter)||void 0===e?void 0:e.isConnected())&&Date.now()>=this._nextHeartbeatAt&&!this._isHeartbeatInProgress}_sendHeartbeat(){return a(this,void 0,void 0,(function*(){var e;const t=Xe({servcmd:"heartbeat.alive",data:{}});try{const e=`${t.head.seq}${t.head.servcmd}`;yield this.sendPacket(t,{requestId:e,timeout:3e3})}catch(t){const s=null===(e=De.get("netWorkMonitor"))||void 0===e?void 0:e.isNetWorkOnline,o=`${vt} sendHeartbeat failed. isNetWorkOnline:${s} error: ${t}`;this._ssoLog({method:"sendHeartbeatError",message:o}),console.debug(o),this._handleConnectStateChange({state:yt,reason:Tt})}}))}_sendHeartbeatIfReady(){return a(this,void 0,void 0,(function*(){this._canSendHeartbeat()&&(this._isHeartbeatInProgress=!0,yield this._sendHeartbeat(),this._isHeartbeatInProgress=!1)}))}_updateHeartbeatTime(){this._nextHeartbeatAt=R?Date.now()+5e3:Date.now()+1e4}_handleNetworkStatusChange(e){const t=`${vt} networkStatusChange ${JSON.stringify(e)}`;this._ssoLog({method:"networkStatusChange",message:t}),console.warn(t);const{isNetworkOnline:s,networkType:o}=e;s&&"none"!==o?this._handleConnectStateChange({state:Et,reason:At}):this._handleConnectStateChange({state:yt,reason:At})}isPrivateNetWork(){const e=De.get("instance")||{};return e.proxyServer&&!e.fileDownloadProxy}_handleConnectStateChange(e){const{state:t,reason:s}=e;if(this._currentConnectState!==t){const e=`${vt}._handleConnectStateChange from ${this._currentConnectState} to ${t} reason: ${s}`;this._ssoLog({method:"handleConnectStateChange",message:e}),console.log(e),this._currentConnectState=t,i.emitOuterEvent("netStateChange",{name:"netStateChange",data:{state:t}}),t===yt&&i.emitInnerEvent(lt.SOCKET_DISCONNECTED),t!==yt&&t!==Et||(this._resetReconnectDelay(),Ye.addTask({id:St,intervalMs:this._intendedDelay,callback:this._scheduleReconnectWithBackoff,context:this}))}}_handleActivityStatusChange(e){var t,s;const o=null===(s=null===(t=this._socketAdapter)||void 0===t?void 0:t._ws)||void 0===s?void 0:s.readyState,n=`${vt} activityStatusChange ${JSON.stringify(e)} readyState: ${o}`;this._ssoLog({method:"activityStatusChange",message:n}),console.warn(n),3===o&&this._handleConnectStateChange({state:yt,reason:Ot})}_resetReconnectDelay(){var e;Ye.removeTask(St);const t=null===(e=De.get("activityMonitor"))||void 0===e?void 0:e.isActive;this._intendedDelay=t?Mt:1e3}_scheduleReconnectWithBackoff(){var e;const t=null===(e=De.get("activityMonitor"))||void 0===e?void 0:e.isActive;this._intendedDelay=t?Math.min(5e3,Math.max(Mt,1.5*this._intendedDelay)):Math.min(3e5,Math.max(1e3,1.5*this._intendedDelay));const s=(new Date).toTimeString().slice(0,8),o=`${vt}.scheduleReconnectWithBackoff timeStr: ${s} intendedDelay: ${this._intendedDelay}`;this._ssoLog({method:"scheduleReconnectWithBackoff",message:o}),console.log(o),this.reconnect(),Ye.updateTaskInterval(St,this._intendedDelay)}_ssoLog(e){const{method:t,message:s}=e;mt.createSSOLogData({method:t}).setLogInfo({message:s}).end()}_diagnose(){this.isPrivateNetWork()||(this._lastDiagnoseAt=Date.now(),function(e){a(this,void 0,void 0,(function*(){const t=e.split("/")[2];if(!t.startsWith("ws"))return;const s=`https://${t}/v3/netcheck/getconninfo?${e.slice(e.indexOf("info?")+5)}&reqtime=${Date.now()}`;try{yield de({method:"GET",url:s,data:{}})}catch(e){console.warn("diagnoseBySSO failed. error:",e)}}))}(this._url),function(e){a(this,void 0,void 0,(function*(){const t=`https://boce-cdn.my-imcloud.com/v3/netcheck/getconninfo?${e.slice(e.indexOf("info?")+5)}&reqtime=${Date.now()}`;try{yield de({method:"GET",url:t,data:{}})}catch(e){console.warn("diagnoseByCDN failed. error:",e)}}))}(this._url),this._beforeSendInterceptors=[])}_clearTimeoutRequest(){for(const[e,t]of this._pendingRequests.entries()){const{reject:s,timestamp:o,timeout:n}=t;Date.now()-o>=n&&(this._pendingRequests.delete(e),Date.now()-this._lastDiagnoseAt>=3e4&&this._diagnose(),s({errorCode:ce,errorInfo:"NETWORK_TIMEOUT",data:{requestId:e}}))}}_updateIsBinarySupported(){var e;if(null===(e=De.get("instance"))||void 0===e?void 0:e.devMode)return void(this._isBinarySupported=!1);const t=re();(T||C&&"windows"===t||R)&&(this._isBinarySupported=!1)}_isCompressedData(e){const t=new Uint8Array(e);return 67===t[0]&&79===t[1]&&77===t[2]&&80===t[3]}};const kt={init:function(e){De.set("instance",e),Gt.init()},destroy:function(){Gt.dispose(),De.clear(),Ye.dispose()},notificationCenter:i,channel:Gt,store:De,ssoLog:mt,utils:_e,common:nt,constants:E};var Ft;!function(e){e.SDK_READY="sdkStateReady",e.SDK_NOT_READY="sdkStateNotReady",e.SDK_DESTROY="sdkDestroy",e.MESSAGE_RECEIVED="onMessageReceived",e.ROOM_CUSTOM_DATA_RECEIVED="onRoomCustomDataReceived",e.MESSAGE_MODIFIED="onMessageModified",e.MESSAGE_REVOKED="onMessageRevoked",e.MESSAGE_READ_BY_PEER="onMessageReadByPeer",e.MESSAGE_READ_RECEIPT_RECEIVED="onMessageReadReceiptReceived",e.MESSAGE_EXTENSIONS_UPDATED="onMessageExtensionsUpdated",e.MESSAGE_EXTENSIONS_DELETED="onMessageExtensionsDeleted",e.MESSAGE_REACTIONS_UPDATED="onMessageReactionsUpdated",e.CONVERSATION_LIST_UPDATED="onConversationListUpdated",e.TOTAL_UNREAD_MESSAGE_COUNT_UPDATED="onTotalUnreadMessageCountUpdated",e.CONVERSATION_GROUP_LIST_UPDATED="onConversationGroupListUpdated",e.CONVERSATION_IN_GROUP_UPDATED="onConversationInGroupUpdated",e.GROUP_LIST_UPDATED="onGroupListUpdated",e.GROUP_ATTRIBUTES_UPDATED="groupAttributesUpdated",e.GROUP_COUNTER_UPDATED="onGroupCounterUpdated",e.TOPIC_CREATED="onTopicCreated",e.TOPIC_DELETED="onTopicDeleted",e.TOPIC_UPDATED="onTopicUpdated",e.PROFILE_UPDATED="onProfileUpdated",e.USER_STATUS_UPDATED="onUserStatusUpdated",e.BLACKLIST_UPDATED="blacklistUpdated",e.FRIEND_LIST_UPDATED="onFriendListUpdated",e.FRIEND_GROUP_LIST_UPDATED="onFriendGroupListUpdated",e.FRIEND_APPLICATION_LIST_UPDATED="onFriendApplicationListUpdated",e.MY_FOLLOWERS_LIST_UPDATED="onMyFollowersListUpdated",e.MY_FOLLOWING_LIST_UPDATED="onMyFollowingListUpdated",e.MUTUAL_FOLLOWERS_LIST_UPDATED="onMutualFollowersListUpdated",e.KICKED_OUT="kickedOut",e.ERROR="error",e.NET_STATE_CHANGE="netStateChange",e.ALL_RECEIVE_MESSAGE_OPT_UPDATED="onAllReceiveMessageOptUpdated"}(Ft||(Ft={}));var $t,qt=Ft;!function(e){e.LOGOUT="logout",e.DESTROY="destroy",e.CLOUD_CONFIG_UPDATE="cloud_config_update",e.PROFILE_UPDATE="profile_updated",e.ERROR="error",e.RECONNECTED="reconnected",e.FORCE_OFFLINE="im_open_status.stat_forceoffline",e.COMMERCIAL_CONFIG_PUSH="im_sdk_config_mgr.push_imsdk_purchase_bitsv2",e.OVERLOAD_PUSH="OverLoadPush.notify2",e.NEW_MESSAGE="new_message",e.MESSAGE_PUSH="im_open_push.msg_push",e.MESSAGE_DELETED="message_deleted",e.MESSAGE_REVOKED="message_revoked",e.MESSAGE_MODIFIED="message_modified",e.SOCKET_DISCONNECTED="socket_disconnected",e.CONVERSATION_UPDATED="conversation_updated"}($t||($t={}));var xt,Vt=$t;!function(e){e.NEW_INVITATION_RECEIVED="newInvitationReceived",e.INVITEE_ACCEPTED="ts_invitee_accepted",e.INVITEE_REJECTED="ts_invitee_rejected",e.INVITATION_CANCELLED="ts_invitation_cancelled",e.INVITATION_TIMEOUT="ts_invitation_timeout",e.INVITATION_MODIFIED="ts_invitation_modified"}(xt||(xt={}));var Bt=xt;const jt=Object.assign({},{KICKED_OUT_MULT_ACCOUNT:"multipleAccount",KICKED_OUT_MULT_DEVICE:"multipleDevice",KICKED_OUT_USERSIG_EXPIRED:"userSigExpired",KICKED_OUT_REST_API:"REST_API_Kick"}),Wt={MSG_TEXT:"TIMTextElem",MSG_IMAGE:"TIMImageElem",MSG_AUDIO:"TIMSoundElem",MSG_FILE:"TIMFileElem",MSG_FACE:"TIMFaceElem",MSG_VIDEO:"TIMVideoFileElem",MSG_LOCATION:"TIMLocationElem",MSG_GRP_TIP:"TIMGroupTipElem",MSG_GRP_SYS_NOTICE:"TIMGroupSystemNoticeElem",MSG_CUSTOM:"TIMCustomElem",MSG_MERGER:"TIMRelayElem"};var Kt;!function(e){e.UNSENT="unSend",e.SUCCESS="success",e.FAIL="fail"}(Kt||(Kt={}));const Ht={modify:Vt.MESSAGE_MODIFIED,delete:Vt.MESSAGE_DELETED,revoke:Vt.MESSAGE_REVOKED},Yt=Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},Wt),{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}),zt={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"},Jt=Object.assign({},zt),Zt=Object.assign(Object.assign(Object.assign(Object.assign({},{CONV_C2C:"C2C",CONV_GROUP:"GROUP",CONV_TOPIC:"TOPIC",CONV_SYSTEM:"@TIM#SYSTEM"}),{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"}),Xt=Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},{SNS_TYPE_NO_RELATION:"CheckResult_Type_NoRelation",SNS_TYPE_A_WITH_B:"CheckResult_Type_AWithB",SNS_TYPE_B_WITH_A:"CheckResult_Type_BWithA",SNS_TYPE_BOTH_WAY:"CheckResult_Type_BothWay"}),{ALLOW_TYPE_ALLOW_ANY:"AllowType_Type_AllowAny",ALLOW_TYPE_NEED_CONFIRM:"AllowType_Type_NeedConfirm",ALLOW_TYPE_DENY_ANY:"AllowType_Type_DenyAny"}),{SNS_ADD_TYPE_SINGLE:"Add_Type_Single",SNS_ADD_TYPE_BOTH:"Add_Type_Both"}),{SNS_DELETE_TYPE_SINGLE:"Delete_Type_Single",SNS_DELETE_TYPE_BOTH:"Delete_Type_Both"}),{SNS_APPLICATION_TYPE_BOTH:"Pendency_Type_Both",SNS_APPLICATION_SENT_TO_ME:"Pendency_Type_ComeIn",SNS_APPLICATION_SENT_BY_ME:"Pendency_Type_SendOut",SNS_APPLICATION_AGREE:"Response_Action_Agree",SNS_APPLICATION_AGREE_AND_ADD:"Response_Action_AgreeAndAdd"}),{SNS_CHECK_TYPE_BOTH:"CheckResult_Type_Both",SNS_CHECK_TYPE_SINGLE:"CheckResult_Type_Single"}),{FORBID_TYPE_NONE:"AdminForbid_Type_None",FORBID_TYPE_SEND_OUT:"AdminForbid_Type_SendOut"}),Qt={COMMUNITY:"@TGS#_",TOPIC:"@TOPIC#_"},es=Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},{GRP_WORK:"Private",GRP_PUBLIC:"Public",GRP_MEETING:"ChatRoom",GRP_AVCHATROOM:"AVChatRoom",GRP_COMMUNITY:"Community",GRP_ROOM:"Room",GRP_LIVE:"Live"}),{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:Qt}),ts=Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},jt),Yt),Jt),Zt),Xt),es),{IOS_OFFLINE_PUSH_NO_SOUND:"push.no_sound",IOS_OFFLINE_PUSH_DEFAULT_SOUND:"default"}),{NET_STATE_CONNECTING:"connecting",NET_STATE_DISCONNECTED:"disconnected"}),ss={NO_SDKAPPID:2e3,NO_TINYID:2022,NO_A2KEY:2023,USER_NOT_LOGGED_IN:2024,REPEAT_LOGIN:2025,MSG_SEND_FAIL:2100,MSG_INSTANCE_REQUIRED:2105,MSG_INVALID_CONV_TYPE:2106,MSG_REVOKE_FAIL:2110,MSG_DELETE_FAIL:2111,MSG_UNREAD_ALL_FAIL:2112,READ_RECEIPT_MSG_LIST_EMPTY:2114,CANNOT_DELETE_GRP_SYSTEM_NOTICE:2116,NOT_MY_FRIEND:2700,NETWORK_ERROR:2800,NETWORK_TIMEOUT:2801,NO_NETWORK:2805,UNCAUGHT_ERROR:2903,SDK_IS_NOT_READY:2999,LOGGING_IN:3e3,LOGIN_FAILED:3001,KICKED_OUT_MULT_DEVICE:3002,KICKED_OUT_MULT_ACCOUNT:3003,KICKED_OUT_USERSIG_EXPIRED:3004,LOGGED_OUT:3005,KICKED_OUT_REST_API:3006,NO_USE:3122,OPTIONS_IS_EMPTY:3153,MSG_A2KEY_EXPIRED:20002,ACCOUNT_A2KEY_EXPIRED:70001,HELLO_ANSWER_KICKED_OUT:1002,OPEN_SERVICE_OVERLOAD_ERROR:60022},os={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"},ns={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"},is={[os.SYNC_SERVER_INFO_AFTER_RE_ONLINE]:[{stepId:ns.USER_STATUS_UPDATE},{stepId:ns.GROUP_ATTRIBUTE_CACHE_CLEAR},{stepId:ns.UNREAD_MESSAGE_SYNC},{stepId:ns.CONVERSATION_RECOVER},{stepId:ns.HISTORY_MESSAGE_RECOVER,dependency:ns.CONVERSATION_RECOVER},{stepId:ns.BLACKLIST_RECOVER},{stepId:ns.FRIEND_RECOVER},{stepId:ns.GROUP_REVOKED_NOTICE_RECOVER},{stepId:ns.HANDLE_C2C_REVOKED_MESSAGE_FROM_SYNC_UNREAD,dependency:ns.UNREAD_MESSAGE_SYNC},{stepId:ns.HANDLE_GROUP_TIPS_FROM_SYNC_UNREAD,dependency:ns.UNREAD_MESSAGE_SYNC},{stepId:ns.CONVERSATION_UPDATE_AFTER_UNREAD_SYNC_FINISHED,dependency:[ns.UNREAD_MESSAGE_SYNC,ns.CONVERSATION_RECOVER]},{stepId:ns.EMIT_C2C_MESSAGE_EVENT,dependency:[ns.UNREAD_MESSAGE_SYNC,ns.CONVERSATION_UPDATE_AFTER_UNREAD_SYNC_FINISHED],skipIfDependencyMissing:!1}],[os.SYNC_SERVER_INFO_AFTER_LOGIN]:[{stepId:ns.COMMERCIAL_CONFIG_UPDATE},{stepId:ns.CLOUD_CONFIG_SYNC},{stepId:ns.USER_PROFILE_SYNC},{stepId:ns.UNREAD_MESSAGE_SYNC},{stepId:ns.FRIEND_AND_BLACKLIST_SYNC},{stepId:ns.GROUP_LIST_SYNC},{stepId:ns.CONVERSATION_LIST_SYNC},{stepId:ns.SIGNALING_MESSAGE_RECOVER,dependency:ns.UNREAD_MESSAGE_SYNC},{stepId:ns.CONVERSATION_UPDATE_AFTER_UNREAD_SYNC_FINISHED,dependency:[ns.UNREAD_MESSAGE_SYNC,ns.CONVERSATION_LIST_SYNC]},{stepId:ns.CONVERSATION_UPDATE_AFTER_GROUP_LIST_SYNC_FINISHED,dependency:[ns.GROUP_LIST_SYNC,ns.CONVERSATION_LIST_SYNC]}],[os.RECEIVE_C2C_NEW_MESSAGE]:[{stepId:ns.HANDLE_C2C_NEW_MESSAGE},{stepId:ns.UNREAD_MESSAGE_SYNC},{stepId:ns.CREATE_OR_UPDATE_CONVERSATION_BY_RECEIVE_NEW_MESSAGE,dependency:ns.HANDLE_C2C_NEW_MESSAGE},{stepId:ns.EMIT_C2C_MESSAGE_EVENT,dependency:[ns.HANDLE_C2C_NEW_MESSAGE,ns.CREATE_OR_UPDATE_CONVERSATION_BY_RECEIVE_NEW_MESSAGE],skipIfDependencyMissing:!1},{stepId:ns.CONVERSATION_UPDATE_AFTER_UNREAD_SYNC_FINISHED,dependency:[ns.UNREAD_MESSAGE_SYNC]}],[os.RECEIVE_GROUP_NEW_MESSAGE]:[{stepId:ns.HANDLE_GROUP_NEW_MESSAGE},{stepId:ns.CREATE_OR_UPDATE_CONVERSATION_BY_RECEIVE_NEW_MESSAGE,dependency:ns.HANDLE_GROUP_NEW_MESSAGE},{stepId:ns.UPDATE_GROUP_NEXT_SEQUENCE,dependency:ns.HANDLE_GROUP_NEW_MESSAGE},{stepId:ns.EMIT_GROUP_MESSAGE_EVENT,dependency:[ns.HANDLE_GROUP_NEW_MESSAGE,ns.CREATE_OR_UPDATE_CONVERSATION_BY_RECEIVE_NEW_MESSAGE],skipIfDependencyMissing:!1}]};var rs=Object.freeze({__proto__:null,ERROR_CODE:ss,InnerEvent:Vt,OuterConstant:ts,OuterEvent:qt,SDK_INFO:{VERSION:"1.7.3",APPID:537048168},SignalingEvent:Bt,WORKFLOW_DEFINITIONS:is,WORKFLOW_NAME:os,WORKFLOW_STEP:ns});function as(e){var t;try{const s=De.getStorage("errorMessage");if(!e||!s)return"";const o=(null===(t=JSON.parse(s))||void 0===t?void 0:t.errorMessage)||{},{isIntl:n=!1,code:i,replacement1:r="",replacement2:a=""}=e;if(!i)return"";const c=n?`${i}_en`:`${i}_cn`;let l=o[o[c]?c:i]||"";return l&&(r&&(l=l.replace("$replacement1",r)),a&&(l=l.replace("$replacement2",a))),l}catch(e){return console.warn("Error parsing stored error messages:",e),""}}class cs extends Error{constructor(e){const{functionName:t="Unknown",code:s,message:o="",data:n=""}=e;let i=o;s&&!o&&(i=as(e));const r=s?`${t} failed. error: {"message": ${i}, "code": ${s}}`:`${t} failed. error: {"message": ${i}}`;super(),this.code=s,this.errorCode=s,this.errorMessage=r,this.message=r,this.data=n}}function ls(e,t){var s;if(!e)return;if(!(!0===(null===(s=kt.store.get("login"))||void 0===s?void 0:s.isLoggedIn)))throw new cs({code:ss.USER_NOT_LOGGED_IN,functionName:t})}const us=e=>"function"==typeof e;function ds(e,t,s){const o=s||[];if(!e||!t)return!1;const n=Object.keys(e).filter((e=>!o.includes(e))),i=Object.keys(t).filter((e=>!o.includes(e)));return n.length===i.length&&n.every((o=>!!t.hasOwnProperty(o)&&("object"==typeof e[o]&&null!==e[o]?ds(e[o],t[o],s):e[o]===t[o])))}function hs(e,t,s){if(Array.isArray(e))for(let o=0;o<e.length;o++)ps.call(this,Object.assign(Object.assign({},e[o]),{value:t[o],name:s}));else for(const o in e)ps.call(this,Object.assign(Object.assign({},e[o]),{value:t[0][o],name:s,key:o}))}function ps({required:e,rules:t,range:s,value:o,allowEmpty:n,name:i,key:r,customValidator:a}){if(void 0===o){if(e){throw new cs({functionName:i,message:`[${i}] Missing required params: "${r}"`})}return}let c="";if(!t.some((e=>{return e===(t=o,Object.prototype.toString.call(t).match(/^\[object (.*)\]$/)[1].toLowerCase());var t}))){for(let e=0;e<t.length;e++){let s=t[e];s=s.replace(s[0],s[0].toUpperCase()),c+=`${s}/`}c=c.substring(0,c.length-1);const e=`[${r}] must be type of ${c}, received type: ${function(e){return Reflect.apply(Object.prototype.toString,e,[]).replace(/^\[object\s(\w+)\]$/,"$1").toLowerCase()}(o)}.`;throw new cs({functionName:i,message:e})}if(!1===n){if(Array.isArray(o)&&(0===o.length||"string"==typeof o[0]&&""===o[0].trim())){throw new cs({functionName:i,message:`${r} can not be empty.`})}if("string"==typeof o&&""===o.trim()){throw new cs({functionName:i,message:`${r} can not be empty.`})}}if(a&&"function"==typeof a){const e=a(o);if(!0!==e){throw new cs({functionName:i,message:`[${r}] custom validation failed: ${e||"Invalid value"}`})}}}const gs=[],_s={},ms={};function fs(e,t){ls(_s[e],e),hs(ms[e],t,e),function(e){gs.forEach((t=>{const{interceptor:s,context:o}=t;s.apply(o,[e])}))}(e)}function vs(e,t){gs.push({interceptor:e,context:t})}function Is(e){const{params:t,auth:s}=e;t&&"object"==typeof t&&Object.assign(ms,t),s&&"object"==typeof s&&Object.assign(_s,s)}var Ss=new class{constructor(){this._builtInPlugins=new WeakSet,this._externalPlugins=new WeakSet}installBuiltInPlugin(e){e&&this._installPlugin(e,this._builtInPlugins)}installExternalPlugin(e,t){e&&this._installPlugin(e,this._externalPlugins,t)}clear(){this._builtInPlugins=new WeakSet,this._externalPlugins=new WeakSet}_installPlugin(e,t,s){let o=[];o=Array.isArray(e)?e:[e],o.forEach((e=>{t.has(e)||(e&&us(e.install)?(t.add(e),e.install(_u(),s),us(e.handleLoginSuccess)&&this._isLoggedIn()&&e.handleLoginSuccess()):us(e)?(t.add(e),e(_u(),s),us(e.handleLoginSuccess)&&this._isLoggedIn()&&e.handleLoginSuccess()):console.warn('A plugin must either be a function or an object with an "install" function.'))}))}_isLoggedIn(){var e;return!0===(null===(e=kt.store.get("login"))||void 0===e?void 0:e.isLoggedIn)}};function Es(e){return kt.store.get("commercialConfig").get(e)}const Cs=new Map;var ys=new class{constructor(){this._handlers=new Map,this._activeWorkflows=new Map,this._stepStartTimes=new Map,this._logHandlers={start:(e,t)=>{const s=Date.now();t?(this._stepStartTimes.set(`${e}-${t}`,s),console.log(`[Workflow ${e}] Step ${t} started at ${new Date(s).toISOString()}`)):(this._workflowStartTimes.set(e,s),console.log(`[Workflow ${e}] started at ${new Date(s).toISOString()}`))},success:(e,t)=>{const s=Date.now();if(t){const o=this._stepStartTimes.get(`${e}-${t}`),n=o?s-o:0;this._stepStartTimes.delete(`${e}-${t}`),console.log(`[Workflow ${e}] Step ${t} completed successfully at ${new Date(s).toISOString()} (${n}ms)`)}else{const t=this._workflowStartTimes.get(e),o=t?s-t:0;this._workflowStartTimes.delete(e),console.log(`[Workflow ${e}] completed successfully at ${new Date(s).toISOString()} (${o}ms)`)}},error:(e,t,s)=>{const o=Date.now();if(t){const n=this._stepStartTimes.get(`${e}-${t}`),i=n?o-n:0;this._stepStartTimes.delete(`${e}-${t}`),console.error(`[Workflow ${e}] Step ${t} failed at ${new Date(o).toISOString()} (${i}ms)`,s)}else{const t=this._workflowStartTimes.get(e),n=t?o-t:0;this._workflowStartTimes.delete(e),console.error(`[Workflow ${e}] failed at ${new Date(o).toISOString()} (${n}ms)`,s)}}}}init(){this._initializeWorkflows()}registerWorkflowStep(e,t,s,o){if(!this._handlers.has(e))return void console.debug(`Workflow '${e}' not defined in core`);if(!is[e].find((e=>e.stepId===t)))return void console.debug(`Step '${t}' not defined in workflow '${e}'`);this._handlers.get(e).set(t,o?s.bind(o):s)}executeWorkflow(e,t){return a(this,void 0,void 0,(function*(){if(!this._validateWorkflow(e))return;console.log(`[Workflow ${e}] Started execution at ${(new Date).toISOString()}`);const s=is[e],o={},n={cancelled:!1};this._activeWorkflows.set(e,{cancelToken:n});try{const i=new Map;s.forEach((e=>{i.set(e.stepId,e)}));const r={workflowName:e,pendingSteps:new Set(s.map((e=>e.stepId))),completedSteps:new Set,runningSteps:new Set,stepMap:i,stepResults:o,data:t,cancelToken:n};yield new Promise(((t,s)=>{const o=()=>{if(n.cancelled)return void t();this._getExecutableSteps({pendingSteps:r.pendingSteps,completedSteps:r.completedSteps,stepMap:r.stepMap,workflowName:e}).filter((e=>!r.runningSteps.has(e))).forEach((n=>{r.completedSteps.has(n)||r.runningSteps.has(n)||this._executeWorkflowStep(n,r,{onComplete:()=>{if(0===r.pendingSteps.size)return void t();0===this._getExecutableSteps({pendingSteps:r.pendingSteps,completedSteps:r.completedSteps,stepMap:r.stepMap,workflowName:e}).filter((e=>!r.runningSteps.has(e))).length&&0===r.runningSteps.size&&(console.log(`Workflow ${e} completed with some steps skipped due to dependency failures`),t())},onError:s,onStepComplete:o})}))};o()})),console.log(`[Workflow ${e}] Completed execution at ${(new Date).toISOString()}`)}catch(t){console.error(`[Workflow ${e}] Failed execution at ${(new Date).toISOString()}`,t)}finally{this._activeWorkflows.delete(e)}}))}_executeWorkflowStep(e,t,s){return a(this,void 0,void 0,(function*(){const{workflowName:o,runningSteps:n,stepMap:i,stepResults:r,data:a}=t;n.add(e),this._logWorkflowExecution(o,e,"start");try{const s=i.get(e);let n=null;(null==s?void 0:s.dependency)&&(l(s.dependency)?n=r[s.dependency]:Array.isArray(s.dependency)&&(n={},s.dependency.forEach((e=>{n[e]=r[e]}))));const c=this._handlers.get(o).get(e);if(c){const t=yield Promise.resolve(c({data:a,result:n}));r[e]=t,this._logWorkflowExecution(o,e,"success")}t.completedSteps.add(e)}catch(t){const n=`[Workflow].${o}.${e}`,{errorCode:i,errorInfo:r=`${n} failed`}=t||{},a=new cs({functionName:n,code:i,message:r});kt.ssoLog.createSSOLogData({method:"Workflow"}).setLogInfo({message:`workflowName: ${o}, stepId: ${e}`}).setError(a).end(),this._logWorkflowExecution(o,e,"error",t),s.onError(t)}finally{n.delete(e),t.pendingSteps.delete(e),s.onStepComplete(),s.onComplete()}}))}reset(){this._cancelAllWorkflows()}destroy(){this.reset(),this._handlers.clear()}_initializeWorkflows(){Object.keys(is).forEach((e=>{this._handlers.set(e,new Map)}))}_cancelWorkFlow(e){const t=this._activeWorkflows.get(e);if(!t)return;const{cancelToken:s}=t;s.cancelled=!0,this._activeWorkflows.delete(e)}_cancelAllWorkflows(){Object.keys(is).forEach((e=>{this._cancelWorkFlow(e)}))}_validateWorkflow(e){if(!is[e])return console.debug(`Workflow '${e}' not defined`),!1;return!!this._handlers.get(e)||(console.debug(`No handlers registered for workflow '${e}'`),!1)}_getExecutableSteps(e){const{pendingSteps:t,completedSteps:s,stepMap:o,workflowName:n}=e;return Array.from(t).filter((e=>{const t=o.get(e)||{},{dependency:i,skipIfDependencyMissing:r=!0}=t;if(!i)return!0;if(l(i))return this._isStepRegistered({workflowName:n,stepId:i})?s.has(i):!r;if(d(i)){if(i.filter((e=>!this._isStepRegistered({workflowName:n,stepId:e}))).length>0&&r)return!1;for(const e of i)if(!s.has(e))return!1;return!0}return!1}))}_isStepRegistered(e){var t;const{workflowName:s,stepId:o}=e;return null===(t=this._handlers.get(s))||void 0===t?void 0:t.has(o)}_logWorkflowExecution(e,t,s,o){this._logHandlers[s](e,t)}};function Ms(){var e;return null===(e=kt.store.get("login"))||void 0===e?void 0:e.userId}const As=e=>d(e)||h(e),Os=(e,t,s,o)=>{if(!As(e)||!As(t))return 0;let n=0;const i=Object.keys(t);let r;for(let a=0,l=i.length;a<l;a++)if(r=i[a],!(c(t[r])||s&&s.includes(r)))if(As(e[r])&&As(t[r]))n+=Os(e[r],t[r],s,o);else{if(o&&o.includes(t[r]))continue;e[r]!==t[r]&&(e[r]=t[r],n+=1)}return n},Ts=e=>`${e}`.startsWith(Qt.COMMUNITY)&&`${e}`.includes(Qt.TOPIC),Ds=(e,t)=>{if(c(t))return"";switch(e){case ts.MSG_TEXT:return t.text||"";case ts.MSG_IMAGE:return"[Image]";case ts.MSG_LOCATION:return"[Location]";case ts.MSG_AUDIO:return"[Voice]";case ts.MSG_VIDEO:return"[Video]";case ts.MSG_FILE:return"[File]";case ts.MSG_CUSTOM:return"[Custom Messages]";case ts.MSG_GRP_TIP:return"[Group Notification]";case ts.MSG_GRP_SYS_NOTICE:return"[Group System Message]";case ts.MSG_FACE:return"[Animated Sticker]";case ts.MSG_MERGER:return"[Chat Record]";default:return""}},Rs=[{cmd:"ws_get_user_status",interval:5,count:20},{cmd:"ws_status_subscribe",interval:5,count:20},{cmd:"ws_status_unsubscribe",interval:5,count:20},{cmd:"get_group_self_member_info",interval:5,count:20},{cmd:"modify_group_base_info",interval:1,count:8},{cmd:"get_members",interval:3,count:1},{cmd:"get_pendency",interval:1,count:15},{cmd:"set_group_attr",interval:5,count:10},{cmd:"modify_group_attr",interval:5,count:10},{cmd:"delete_group_attr",interval:5,count:10},{cmd:"clear_group_attr",interval:5,count:10},{cmd:"get_group_attr",interval:5,count:20},{cmd:"update_group_counter",interval:5,count:20},{cmd:"get_group_counter",interval:5,count:20},{cmd:"get_topic",interval:1,count:10},{cmd:"read_all_unread_msg",interval:1,count:1},{cmd:"query",interval:5,count:20}],Ls="im_sdk_config_mgr.fetch_config",Ns="im_sdk_config_mgr.push_configv2",bs="cloud-config",ws=2996;var Ps=new class{constructor(){this._core=null,this._expirationTime=0,this._version=0,this._isFetching=!1,this._cmdFrequencyLimitMap=new Map,this._methodCallFrequencyMap=new Map}install(e){this._core=e;const{notificationCenter:t,InnerEvent:s,helper:o,constants:{WORKFLOW_NAME:n,WORKFLOW_STEP:i},channel:r}=e;t.subscribeInnerEvent(Ns,this._handlePushedConfig,this),o.registerWorkflowStep(n.SYNC_SERVER_INFO_AFTER_LOGIN,i.CLOUD_CONFIG_SYNC,this._handleLoginSuccess,this),t.subscribeInnerEvent(s.LOGOUT,this._reset,this),t.subscribeInnerEvent(s.DESTROY,this._dispose,this),o.registerExperimentalAPI("getServerConfig",this),this._updateCmdFreqLimitMap(Rs),r.registerBeforeSendInterceptor(this.checkMethodCallOverLimit,this)}getServerConfig(e){var t;const s={code:0,data:""};return e?(s.data=(null===(t=this._core.store.get("cloudConfig"))||void 0===t?void 0:t[e])||"",s):s}checkMethodCallOverLimit(e){if(!this._cmdFrequencyLimitMap.has(e))return;if(!this._methodCallFrequencyMap.has(e))return void this._methodCallFrequencyMap.set(e,{startTime:Date.now(),methodCallCounter:1});const{count:t,interval:s}=this._cmdFrequencyLimitMap.get(e);let{startTime:o,methodCallCounter:n}=this._methodCallFrequencyMap.get(e);if(Date.now()-o>1e3*s)this._methodCallFrequencyMap.set(e,{startTime:Date.now(),methodCallCounter:1});else if(n+=1,this._methodCallFrequencyMap.set(e,{startTime:o,methodCallCounter:n}),n>t)throw new this._core.helper.ChatError({code:ws,replacement1:e})}_fetchCloudConfig(){return a(this,void 0,void 0,(function*(){try{const{sdkAppId:e}=this._core.store.get("instance")||{},t=this._core.helper.generateProtocolData({servcmd:Ls,data:{uint32_sdkappid:e,uint64_version:this._version}}),s=`${t.head.seq}${Ls}`;return yield this._core.channel.sendPacket(t,{requestId:s})}catch(e){throw console.warn("fetch cloudControl fail: ",e),e}}))}_handlePushedConfig(e){this._updateCloudConfig(e)}_handleLoginSuccess(){return a(this,void 0,void 0,(function*(){try{if(this._canFetch()){const e=yield this._fetchCloudConfig();this._updateCloudConfig(e)}this._core.helper.taskScheduler.addTask({id:bs,intervalMs:1e3,callback:this._fetchCloudConfigIfReady,context:this})}catch(e){console.warn(e)}}))}_fetchCloudConfigIfReady(){return a(this,void 0,void 0,(function*(){if(this._canFetch())try{const e=yield this._fetchCloudConfig();this._updateCloudConfig(e)}catch(e){console.warn(e)}}))}_updateCloudConfig(e){const t=this._parseCloudConfig(e);t&&(this._core.store.set("cloudConfig",t),this._parseCmdFreqLimit(),this._core.notificationCenter.emitInnerEvent(this._core.InnerEvent.CLOUD_CONFIG_UPDATE,t))}_canFetch(){const{isLoggedIn:e}=this._core.store.get("login")||{};return e&&!this._isFetching&&Date.now()>=this._expirationTime}_parseCloudConfig(e){const{int32_error_code:t,str_error_message:s,str_json_config:o,uint32_expired_time:n,uint32_sdkappid:i,uint64_version:r}=e;let a=null;if(0===t){if(this._version!==r)try{a=JSON.parse(o),this._version=r}catch(e){}this._expirationTime=Date.now()+1e3*n}else this._expirationTime=void 0===t?Date.now()+36e5:Date.now()+12e4;return a}_parseCmdFreqLimit(){var e;let t=null===(e=this.getServerConfig("cmd_frequency_limit"))||void 0===e?void 0:e.data;const{isEmpty:s}=this._core.utils;if(!s(t))try{t=JSON.parse(t),this._updateCmdFreqLimitMap(t)}catch(e){console.warn(e)}}_updateCmdFreqLimitMap(e){e.forEach((e=>{this._cmdFrequencyLimitMap.set(e.cmd,{interval:e.interval,count:e.count})}))}_reset(){this._core.helper.taskScheduler.removeTask(bs),this._core.store.clear("cloudConfig"),this._updateCmdFreqLimitMap(Rs),this._methodCallFrequencyMap.clear(),this._expirationTime=0,this._version=0,this._isFetching=!1}_dispose(){const{notificationCenter:e,InnerEvent:t}=this._core;e.unSubscribeInnerEvent(Ns,this._handlePushedConfig,this),e.unSubscribeInnerEvent(t.LOGOUT,this._reset,this),e.unSubscribeInnerEvent(t.DESTROY,this._dispose,this),this._reset()}};class Us{constructor(e=0,t=0){this.high=e,this.low=t}equal(e){return null!==e&&(this.low===e.low&&this.high===e.high)}toString(){const e=Number(this.high).toString(16);let t=Number(this.low).toString(16);if(t.length<8){let e=8-t.length;for(;e;)t=`0${t}`,e--}return e+t}}const Gs={SEARCH_GRP_SNS:new Us(0,Math.pow(2,1)).toString(),AV_HISTORY_MSG:new Us(0,Math.pow(2,2)).toString(),GRP_COMMUNITY:new Us(0,Math.pow(2,3)).toString(),MSG_TO_SPECIFIED_GRP_MBR:new Us(0,Math.pow(2,4)).toString(),AV_MBR_LIST:new Us(0,Math.pow(2,6)).toString(),USER_STATUS:new Us(0,Math.pow(2,7)).toString(),CONV_MARK:new Us(0,Math.pow(2,9)).toString(),CONV_GROUP:new Us(0,Math.pow(2,10)).toString(),AV_BAN_MBR:new Us(0,Math.pow(2,11)).toString(),MSG_EXT:new Us(0,Math.pow(2,13)).toString(),GRP_COUNTER:new Us(0,Math.pow(2,15)).toString(),PLUGIN_TRANSLATE:new Us(Math.pow(2,6)).toString(),PLUGIN_VOICE_TO_TEXT:new Us(Math.pow(2,7)).toString(),PLUGIN_CS:new Us(Math.pow(2,8)).toString(),PLUGIN_PUSH:new Us(Math.pow(2,9)).toString(),PLUGIN_BOT:new Us(Math.pow(2,10)).toString(),MSG_REACTION:new Us(Math.pow(2,16)).toString(),FOLLOW:new Us(Math.pow(2,20)).toString()},ks="CommercialConfig",Fs="commercial-config";var $s=new class{constructor(){this._core=null,this._expirationTime=0,this._isFetching=!1,this._featureMap=new Map,this._methodKeyMap=new Map}install(e){this._core=e;const{helper:t,notificationCenter:s,constants:{WORKFLOW_NAME:o,WORKFLOW_STEP:n,InnerEvent:i}}=e;s.subscribeInnerEvent(i.COMMERCIAL_CONFIG_PUSH,this._handlePushedConfig,this),s.subscribeInnerEvent(i.LOGOUT,this._handleLogout,this),s.subscribeInnerEvent(i.DESTROY,this._dispose,this),t.registerWorkflowStep(o.SYNC_SERVER_INFO_AFTER_LOGIN,n.COMMERCIAL_CONFIG_UPDATE,this._syncCommercialConfig,this),e.helper.registerExperimentalAPI("isCommercialAbilityEnabled",this)}isCommercialAbilityEnabled(e){return a(this,void 0,void 0,(function*(){const t=parseInt(e,10).toString(2),{length:s}=t;let o,n=!0;for(let e=s-1,i=0;e>=0;e--,i++)if("1"===t.charAt(e)&&(o=i<32?new Us(0,2**i).toString():new Us(2**(i-32),0).toString(),!this._featureMap.get(o))){n=!1;break}return console.log(`${ks}.isFeatureEnabled decimalNumber:${e} key:${o} ret:${n}`),{code:0,data:{enabled:n}}}))}_fetchAndParseCommercialConfig(){return a(this,void 0,void 0,(function*(){var e;try{this._isFetching=!0;const t=this._core.helper.generateProtocolData({servcmd:"im_sdk_config_mgr.fetch_imsdk_purchase_bitsv2",data:{uint32_sdkappid:null===(e=this._core.store.get("instance"))||void 0===e?void 0:e.sdkAppId}}),s=yield this._core.channel.sendPacket(t);(null==s?void 0:s.body)&&(this._parseCommercialConfig(s.body),this._core.store.set("commercialConfig",this._methodKeyMap))}catch(e){console.warn("fetch commercial fail: ",e)}finally{this._isFetching=!1}}))}_syncCommercialConfig(e){return a(this,void 0,void 0,(function*(){const{purchaseBits:t}=(null==e?void 0:e.data)||{};t&&(this._parsePurchaseBits(t),this._core.store.set("commercialConfig",this._methodKeyMap)),this._canFetch()&&(yield this._fetchAndParseCommercialConfig()),this._core.helper.taskScheduler.addTask({id:Fs,intervalMs:1e3,callback:this._fetchCommercialConfigIfReady,context:this})}))}_canFetch(){var e;const t=null===(e=this._core.store.get("login"))||void 0===e?void 0:e.isLoggedIn,s=Date.now()>=this._expirationTime;return t&&!this._isFetching&&s}_handlePushedConfig(e){(null==e?void 0:e.body)&&(this._parseCommercialConfig(e.body),this._core.store.set("commercialConfig",this._methodKeyMap))}_fetchCommercialConfigIfReady(){return a(this,void 0,void 0,(function*(){this._canFetch()&&(yield this._fetchAndParseCommercialConfig())}))}_parseCommercialConfig(e){if("object"!=typeof e)return;const{int32_error_code:t,str_error_message:s,str_purchase_bits:o,uint32_expired_time:n}=e;0===t?(this._parsePurchaseBits(o),this._expirationTime=Date.now()+1e3*n):void 0===t?(console.log(`${ks}._parseCommercialConfig failed. Invalid message format:`,e),this._expirationTime=Date.now()+36e5):(console.error(`${ks}._parseCommercialConfig errorCode:${t} errorMessage:${s}`),this._expirationTime=Date.now()+12e4)}_isValidPurchaseBits(e){return e&&"string"==typeof e&&e.length>=1&&e.length<=64&&/[01]{1,64}/.test(e)}_parsePurchaseBits(e){if(this._isValidPurchaseBits(e)){this._featureMap.clear(),this._methodKeyMap.clear();let t=null;for(let s=e.length-1,o=0;s>=0;s--,o++)if(t=o<32?new Us(0,2**o).toString():new Us(2**(o-32),0).toString(),"1"===e[s]){this._featureMap.set(t,!0);const e=this._getKeyByValue(Gs,t);e&&this._methodKeyMap.set(e,!0)}else{this._featureMap.set(t,!1);const e=this._getKeyByValue(Gs,t);e&&this._methodKeyMap.set(e,!1)}}else console.warn(`${ks}.parsePurchaseBits invalid purchases:${e}`)}_getKeyByValue(e,t){const s=Object.entries(e).find((([e,s])=>s===t));return s?s[0]:void 0}_handleLogout(){this._reset()}_dispose(){this._reset(),this._core.notificationCenter.unSubscribeInnerEvent(this._core.InnerEvent.COMMERCIAL_CONFIG_PUSH,this._handlePushedConfig,this),this._core.notificationCenter.unSubscribeInnerEvent(this._core.InnerEvent.LOGOUT,this._reset,this),this._core.notificationCenter.unSubscribeInnerEvent(this._core.InnerEvent.DESTROY,this._dispose,this)}_reset(){this._core.helper.taskScheduler.removeTask(Fs),this._core.store.set("commercialConfig",{}),this._expirationTime=0,this._isFetching=!1,this._featureMap.clear()}};var qs=new class{constructor(){this._core=null,this._serverOverloadInfoMap=new Map}install(e){this._core=e;const{notificationCenter:t,InnerEvent:s,channel:o}=this._core;t.subscribeInnerEvent(s.OVERLOAD_PUSH,this._handleOverLoadPush,this),t.subscribeInnerEvent(s.LOGOUT,this._reset,this),t.subscribeInnerEvent(s.DESTROY,this._dispose,this),o.registerBeforeSendInterceptor(this.checkServerOverload,this)}checkServerOverload(e){if(!this._serverOverloadInfoMap.has(e))return;const{overloadStartTimestamp:t,delaySeconds:s}=this._serverOverloadInfoMap.get(e);if(Date.now()-t<=1e3*s)throw new this._core.helper.ChatError({functionName:e,message:"service is busy, please try again later"});this._serverOverloadInfoMap.delete(e)}_handleOverLoadPush(e){const{OverLoadServCmd:t,DelaySecs:s}=e;this._serverOverloadInfoMap.set(t,{overloadStartTimestamp:Date.now(),delaySeconds:s})}_reset(){this._serverOverloadInfoMap.clear()}_dispose(){this._reset();const{notificationCenter:e,InnerEvent:t}=this._core;e.unSubscribeInnerEvent(t.OVERLOAD_PUSH,this._handleOverLoadPush,this),e.unSubscribeInnerEvent(t.LOGOUT,this._reset,this),e.unSubscribeInnerEvent(t.DESTROY,this._dispose,this)}};var xs=new class{constructor(){this._core=null}install(e){return a(this,void 0,void 0,(function*(){if(this._core=e,this._canFetch()){const e=yield this._fetchErrorMessage();if(!e)return;const t=this._parseResponse(e);this._saveErrorMessage(t)}}))}_canFetch(){const e=this._core.store.getStorage("errorMessage");return!e||this._isExpired(e)}_saveErrorMessage(e){this._core.store.setStorage("errorMessage",{errorMessage:e,errorMessageSavedTime:(new Date).getTime()})}_fetchErrorMessage(){return a(this,void 0,void 0,(function*(){try{return yield this._core.helper.httpRequest({method:"GET",url:"https://web.sdk.qcloud.com/im/download/error-message/v3/0.0.6/tim-error-message.txt"})}catch(e){console.error(e)}}))}_isExpired(e){if(!e)return!0;const{errorMessageSavedTime:t}=e;return t&&(new Date).getTime()-t>=6048e5}_parseResponse(e){if("string"==typeof e){const t=e.split(";\n"),s={},o=new RegExp(/'/g);for(let e=0;e<t.length;e++){const n=t[e].indexOf(":"),i=t[e].slice(0,n);let r=t[e].slice(n+1);if(!i.startsWith("//")){if(""===r)continue;r=r.replace(o,""),s[i]=r}}return s}}};function Vs(e,t){return a(this,void 0,void 0,(function*(){const{cookie:s,syncFlag:o,syncTriggerEvent:n}=e,i="openim.getmsg",r=t.helper.generateProtocolData({servcmd:i,data:{Cookie:s,SyncFlag:o,IsOnlineSync:n,NeedAbstract:1,NeedSignaling:1,NeedCachedMsg:1}}),a=`${r.head.seq}${i}`;try{const e=yield t.channel.sendPacket(r,{requestId:a});if(!e)return null;const{C2CPairUnreadCount:s,C2CRemainingUnreadCount:o,EventArray:n}=e,{unreadMessageList:i,revokedMessageList:c}=function(e,t){const s=[],o=[];return null==e||e.forEach((e=>{var n,i,r;const a=function(e,t){const{From_Account:s,From_AccountHeadurl:o,From_AccountNick:n,IsNeedReadReceipt:i,MsgBody:r,MsgClientTime:a,MsgRandom:c,MsgSeq:l,MsgTimeStamp:u,SendMsgControl:d,SupportMessageExtension:h,To_Account:p,TinyId:g,MsgCheckResult:_,CloudCustomData:m,IsPeerRead:f,MsgFlagBits:v,MsgVersion:I,EventArray:S}=e;return{from:s,avatar:o,nick:n,needReadReceipt:1===i,readReceiptSentByPeer:f,clientTime:a,messageFlagBits:v,random:c,sequence:l,time:u,messageControlInfo:d,isSupportExtension:h,to:p,tinyID:g,checkResult:_,cloudCustomData:m,messageVersion:I,eventArray:S,elements:t.message.messageHelper.parseServerPushMessageElement(r)}}(e,t);if(null===(r=null===(i=null===(n=null==e?void 0:e.EventArray)||void 0===n?void 0:n[0])||void 0===i?void 0:i.hasOwnProperty)||void 0===r?void 0:r.call(i,"C2cNotifyMsgArray"))o.push(...function(e){var t;const s=[];return null===(t=e.EventArray)||void 0===t||t.forEach((e=>{var t,o;const{C2cNotifyMsgArray:n}=e,i=null===(o=null===(t=null==n?void 0:n[0])||void 0===t?void 0:t.WithdrawC2cMsgNotify)||void 0===o?void 0:o.C2cWithdrawInfoArray;Array.isArray(i)&&s.push(...i)})),s}(e));else{const e=t.message.messageFactory.createMessage(Object.assign(Object.assign({},a),{conversationType:"C2C",flow:"in"})),{elements:o}=a;e.setElement(o),s.push(e)}})),{unreadMessageList:s,revokedMessageList:o}}(e.MsgList,t);return{syncFlag:null==e?void 0:e.SyncFlag,unreadMessageList:i,revokedMessageList:c,unreadCountList:s,overflowUnreadCountList:o,cookie:null==e?void 0:e.Cookie,groupTipList:n}}catch(e){console.warn(e)}}))}var Bs,js;!function(e){e[e.START_SYNC=0]="START_SYNC",e[e.SYNCING=1]="SYNCING",e[e.SYNC_COMPLETE=2]="SYNC_COMPLETE"}(Bs||(Bs={})),function(e){e[e.LOGIN_SUCCESS=0]="LOGIN_SUCCESS",e[e.NEW_MESSAGE_RECEIVED=1]="NEW_MESSAGE_RECEIVED"}(js||(js={}));var Ws=new class{constructor(){this._unreadDBMessageMap=new Map,this._cookie=""}install(e){this._core=e;const{constants:t}=e;e.helper.registerWorkflowStep(t.WORKFLOW_NAME.SYNC_SERVER_INFO_AFTER_RE_ONLINE,t.WORKFLOW_STEP.UNREAD_MESSAGE_SYNC,this._syncUnreadDBMessageAfterReOnline,this),e.helper.registerWorkflowStep(t.WORKFLOW_NAME.RECEIVE_C2C_NEW_MESSAGE,t.WORKFLOW_STEP.UNREAD_MESSAGE_SYNC,this._syncUnreadDBMessageAfterNewMessageReceived,this),e.helper.registerWorkflowStep(t.WORKFLOW_NAME.SYNC_SERVER_INFO_AFTER_LOGIN,t.WORKFLOW_STEP.UNREAD_MESSAGE_SYNC,this._syncUnreadDBMessageAfterLogin,this),e.notificationCenter.subscribeInnerEvent(e.InnerEvent.LOGOUT,this._reset,this),e.notificationCenter.subscribeInnerEvent(e.InnerEvent.DESTROY,this._dispose,this)}_syncUnreadMessage(e){return a(this,void 0,void 0,(function*(){const{isAfterReOnline:t=!1,isAfterNewMessageReceived:s=!1,isAfterLogin:o=!1}=e||{};let n=Bs.START_SYNC;const i=[],r=[],a=[],c=[];for(;this._canContinueSync({cookie:this._cookie,syncFlag:n});){const e=yield this._fetchUnreadDBMessage({cookie:this._cookie,syncFlag:n,syncTriggerEvent:s?js.NEW_MESSAGE_RECEIVED:js.LOGIN_SUCCESS});if(!e)break;const{unreadMessageList:o=[],revokedMessageList:l=[],overflowUnreadCountList:u,unreadCountList:d,groupTipList:h}=e;if(this._cookie=(null==e?void 0:e.cookie)||"",n=null==e?void 0:e.syncFlag,this._parseAndSaveUnreadMessageList(o),a.push(...l),this._updateConversationUnreadOptions({unreadCountList:d,overflowUnreadCountList:u,conversationUpdateFieldList:i}),Array.isArray(h)&&r.push(...h),t){const{messages:e}=this._handleNewMessageList(o);c.push(...e)}}return t?{conversationUpdateFieldList:i,revokedMessageList:a,unreadMessageMap:this._unreadDBMessageMap,groupTipList:r,messages:c}:{conversationUpdateFieldList:i,isInstantMessage:!o,isUnreadC2CMessage:!0,revokedMessageList:a,unreadMessageMap:this._unreadDBMessageMap,groupTipList:r}}))}_syncUnreadDBMessageAfterLogin(){return a(this,void 0,void 0,(function*(){return this._syncUnreadMessage({isAfterLogin:!0})}))}_syncUnreadDBMessageAfterNewMessageReceived(e){return a(this,void 0,void 0,(function*(){if(1===e.data.Flag)return this._syncUnreadMessage({isAfterNewMessageReceived:!0})}))}_updateConversationUnreadOptions(e){const{unreadCountList:t,overflowUnreadCountList:s,conversationUpdateFieldList:o}=e,{constants:{OuterConstant:{CONV_C2C:n,CONV_SYSTEM:i}}}=this._core;null==t||t.forEach((e=>{const{From_Account:t,UnreadCount:s}=e;if(t!==i){const e=o.find((({conversationID:e})=>e===`${n}${t}`));e?e.unreadCount=s:o.push({conversationID:`${n}${t}`,unreadCount:s,type:n})}})),null==s||s.forEach((e=>{const{From_Account:t,LastMsgTime:s}=e;if(t!==i){o.find((({conversationID:e})=>e===`${n}${t}`))||o.push({conversationID:`${n}${t}`,type:n,lastMsgTime:s})}}))}_syncUnreadDBMessageAfterReOnline(){return a(this,void 0,void 0,(function*(){return this._syncUnreadMessage({isAfterReOnline:!0})}))}_updateMessageProfile(e){var t;const{messageDataHandler:s}=this._core.message||{},o=null===(t=this._core.store.get("login"))||void 0===t?void 0:t.userId,{from:n,nick:i,avatar:r,conversationID:a=""}=e;if(n!==o){const t=s.getLatestMsgSentByPeer(a);if(t){const{nick:o,avatar:n}=t;i&&r?i===o&&r===n||s.updateNickAndAvatarOfSentMessage({conversationID:a,latestNick:i,latestAvatar:r,isSentByMe:!1}):(e.nick=o,e.avatar=n)}}else{const e=s.getLatestMsgSentByMe(a);!e||i===e.nick&&r===e.avatar||s.updateNickAndAvatarOfSentMessage({conversationID:a,latestNick:i,latestAvatar:r,isSentByMe:!0})}}_handleNewMessageList(e){const{messageDataHandler:t}=this._core.message||{},s=new Map,o=[];return e.forEach((e=>{this._updateMessageProfile(e);let n=1===e.isModified;if(t.isMessageSentByCurrentInstance(e)?e.isModified=n:n=!1,e.isOnlineMessage())e._onlineOnlyFlag=!0,t.isMessageSentByCurrentInstance(e)||o.push(e);else if(!t.isInMessageList(e)){if(t.storeConversationMessage(e)){const{conversationID:t,conversationType:o,conversationSubType:n,flow:i,_isExcludedFromUnreadCount:r,_isExcludedFromLastMessage:a}=e,c=a?"":e;s.has(t)?(s.get(t).lastMessage=c,"in"===i&&(r||s.get(t).unreadCount++)):s.set(t,{conversationID:t,type:o,subType:n,unreadCount:r||"in"!==i?0:1,lastMessage:c})}t.isMessageSentByCurrentInstance(e)&&!n||o.push(e)}})),{messages:o,conversationOptions:s}}_fetchUnreadDBMessage(e){return a(this,void 0,void 0,(function*(){try{const t="unread-message-synchronizer._fetchUnreadDBMessage";console.log(`${t} options:`,e);const s=yield Vs(e,this._core);if(!s)return null;const{syncFlag:o,unreadMessageList:n,revokedMessageList:i,cookie:r,unreadCountList:a,overflowUnreadCountList:c,groupTipList:l}=s;return this._parseAndSaveUnreadMessageList(n),{syncFlag:o,cookie:r,unreadMessageList:n,revokedMessageList:i,unreadCountList:a,overflowUnreadCountList:c,groupTipList:l}}catch(e){console.log(e)}}))}_canContinueSync({cookie:e,syncFlag:t}){var s;return t===Bs.START_SYNC||t===Bs.SYNCING&&!(null===(s=this._core)||void 0===s?void 0:s.helper.isEmpty(e))}_parseAndSaveUnreadMessageList(e){e.forEach((e=>{const{ID:t}=e;this._unreadDBMessageMap.set(t,e)}))}_reset(){this._cookie="",this._unreadDBMessageMap.clear()}_dispose(){var e,t;null===(e=this._core)||void 0===e||e.notificationCenter.unSubscribeInnerEvent(this._core.InnerEvent.LOGOUT,this._reset,this),null===(t=this._core)||void 0===t||t.notificationCenter.unSubscribeInnerEvent(this._core.InnerEvent.DESTROY,this._dispose,this),this._reset()}};var Ks=new class{init(e){var t;this._core=e,this._visibilityChangeHandler=this._handleVisibilityChange.bind(this),e.notificationCenter.subscribeInnerEvent(e.InnerEvent.DESTROY,this._dispose,this),document.addEventListener("visibilitychange",this._visibilityChangeHandler),null===(t=this._core)||void 0===t||t.store.set("activityMonitor",{isActive:!0})}_handleVisibilityChange(){var e,t;const s="visible"===document.visibilityState;null===(e=this._core)||void 0===e||e.store.set("activityMonitor",{isActive:s}),null===(t=this._core)||void 0===t||t.notificationCenter.emitInnerEvent("activityStatusChange",{isActive:s})}_reset(){var e;null===(e=this._core)||void 0===e||e.store.clear("activityMonitor")}_dispose(){document.removeEventListener("visibilitychange",this._visibilityChangeHandler);const{notificationCenter:e,InnerEvent:t}=this._core;e.unSubscribeInnerEvent(t.DESTROY,this._dispose,this),this._reset()}};var Hs=new class{init(e){var t;this._core=e,this._bindAppActivityEvent(),e.notificationCenter.subscribeInnerEvent(e.InnerEvent.DESTROY,this._dispose,this),null===(t=this._core)||void 0===t||t.store.set("activityMonitor",{isActive:!0})}_bindAppActivityEvent(){var e;const{MINI_APP_NAMESPACE:t}=(null===(e=this._core)||void 0===e?void 0:e.utils)||{};t.onAppShow((()=>{var e,t;null===(e=this._core)||void 0===e||e.store.set("activityMonitor",{isActive:!0}),null===(t=this._core)||void 0===t||t.notificationCenter.emitInnerEvent("activityStatusChange",{isActive:!0})})),t.onAppHide((()=>{var e,t;null===(e=this._core)||void 0===e||e.store.set("activityMonitor",{isActive:!1}),null===(t=this._core)||void 0===t||t.notificationCenter.emitInnerEvent("activityStatusChange",{isActive:!1})}))}_reset(){var e;null===(e=this._core)||void 0===e||e.store.clear("activityMonitor")}_dispose(){const{notificationCenter:e,InnerEvent:t}=this._core;e.unSubscribeInnerEvent(t.DESTROY,this._dispose,this),this._reset()}};var Ys=new class{init(e){const{IN_WX_MINI_APP:t,IN_WX_MINI_PLUGIN:s}=e.helper;s||(t?Hs.init(e):Ks.init(e))}};const zs="none",Js="online";var Zs=new class{init(e){this._core=e,this._activateNetworkMonitoring(),e.notificationCenter.subscribeInnerEvent(e.InnerEvent.DESTROY,this._dispose,this)}_activateNetworkMonitoring(){return a(this,void 0,void 0,(function*(){navigator.onLine?this._onOnline():this._onOffline(),this._onOnlineCallback=this._onOnline.bind(this),this._onOfflineCallback=this._onOffline.bind(this),window.addEventListener("online",this._onOnlineCallback),window.addEventListener("offline",this._onOfflineCallback)}))}_deactivateNetworkMonitoring(){null!==this._onOnlineCallback&&(window.removeEventListener("online",this._onOnlineCallback),this._onOnlineCallback=null),null!==this._onOfflineCallback&&(window.removeEventListener("offline",this._onOfflineCallback),this._onOfflineCallback=null)}_onNetworkStatusChange(e){var t,s;const{isConnected:o,networkType:n}=e;null===(t=this._core)||void 0===t||t.store.set("netWorkMonitor",{isNetworkOnline:o,networkType:n}),null===(s=this._core)||void 0===s||s.notificationCenter.emitInnerEvent("networkStatusChange",{isNetworkOnline:o,networkType:n})}_onOnline(){this._onNetworkStatusChange({isConnected:!0,networkType:Js})}_onOffline(){this._onNetworkStatusChange({isConnected:!1,networkType:zs})}_reset(){var e;this._deactivateNetworkMonitoring(),null===(e=this._core)||void 0===e||e.store.clear("netWorkMonitor")}_dispose(){var e,t;null===(e=this._core)||void 0===e||e.notificationCenter.unSubscribeInnerEvent(null===(t=this._core)||void 0===t?void 0:t.InnerEvent.DESTROY,this._dispose,this),this._reset()}};var Xs=new class{init(e){this._core=e,this._activateNetworkMonitoring(),e.notificationCenter.subscribeInnerEvent(e.InnerEvent.DESTROY,this._dispose,this)}_activateNetworkMonitoring(){return a(this,void 0,void 0,(function*(){try{this._mpNetworkStatusCallback=this._onNetworkStatusChange.bind(this),wx.onNetworkStatusChange(this._onNetworkStatusChange.bind(this))}catch(e){console.error(e)}}))}_deactivateNetworkMonitoring(){null!==this._mpNetworkStatusCallback&&(wx.offNetworkStatusChange&&wx.offNetworkStatusChange(this._mpNetworkStatusCallback),this._mpNetworkStatusCallback=null)}_onNetworkStatusChange(e){var t,s;const{isConnected:o,networkType:n}=e;null===(t=this._core)||void 0===t||t.store.set("netWorkMonitor",{isNetworkOnline:o,networkType:n}),null===(s=this._core)||void 0===s||s.notificationCenter.emitInnerEvent("networkStatusChange",{isNetworkOnline:o,networkType:n})}_reset(){var e;this._deactivateNetworkMonitoring(),null===(e=this._core)||void 0===e||e.store.clear("netWorkMonitor")}_dispose(){var e,t;null===(e=this._core)||void 0===e||e.notificationCenter.unSubscribeInnerEvent(null===(t=this._core)||void 0===t?void 0:t.InnerEvent.DESTROY,this._dispose,this),this._reset()}};var Qs=new class{init(e){const{IN_WX_MINI_APP:t}=e.helper;t?Xs.init(e):Zs.init(e)}};var eo=new class{install(e){Ys.init(e),Qs.init(e)}};const to=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.*"]),so="tui_room_svr.*";var oo=new class{constructor(){this._transferredCommands=to}install(e){this._core=e;const{notificationCenter:t,InnerEvent:s,helper:o}=e;t.subscribeInnerEvent(s.CLOUD_CONFIG_UPDATE,this._onCloudConfigUpdate,this),t.subscribeInnerEvent(s.LOGOUT,this._reset,this),t.subscribeInnerEvent(s.DESTROY,this._dispose,this),t.subscribeInnerEvent("im_open_push.msg_push",t.InnerEventSubType.BUSINESS_COMMAND,this._onServerPushBusinessCommand,this),o.registerExperimentalAPI("sendTRTCCustomData",this,"transferBusinessCommand"),o.registerExperimentalAPI("sendRoomCustomData",this,"transferBusinessCommand")}transferBusinessCommand(e){return a(this,void 0,void 0,(function*(){const t="transferBusinessCommand";try{const{serviceCommand:s=so}=e||{};if(!this._isValidTransferredCommand(s))throw new this._core.helper.ChatError({code:2995,functionName:t});const o=yield function(e,t){return a(this,void 0,void 0,(function*(){const{helper:s,channel:o}=t,{serviceCommand:n=so,data:i}=e||{};let r={};try{r="string"==typeof i?JSON.parse(i):i}catch(e){console.warn(e)}const a=s.generateProtocolData({servcmd:n,data:r}),c=`${a.head.seq}${n}`;return o.sendPacket(a,{requestId:c})}))}(e,this._core);return{code:0,data:o||{}}}catch(e){throw console.warn(e),new this._core.helper.ChatError({code:null==e?void 0:e.errorCode,message:null==e?void 0:e.errorInfo,data:{},functionName:t})}}))}_onCloudConfigUpdate(e={}){try{if("string"!=typeof e.rtc_cmd)return;const t=JSON.parse(e.rtc_cmd);Array.isArray(t)&&(this._transferredCommands=new Set([...this._transferredCommands,...t]))}catch(e){console.log(e)}}_isValidTransferredCommand(e=""){const t=`${null==e?void 0:e.split(".")[0]}.*`;return this._transferredCommands.has(t)}_onServerPushBusinessCommand(e){const{OuterEvent:t,notificationCenter:s}=this._core,{MsgContent:o}=e||{},{ROOM_CUSTOM_DATA_RECEIVED:n}=t;s.emitOuterEvent(n,{name:n,data:o})}_reset(){this._transferredCommands=to}_dispose(){const{notificationCenter:e,InnerEvent:t}=this._core;this._reset(),e.unSubscribeInnerEvent(t.CLOUD_CONFIG_UPDATE,this._onCloudConfigUpdate,this),e.unSubscribeInnerEvent(t.LOGOUT,this._reset,this),e.unSubscribeInnerEvent(t.DESTROY,this._dispose,this),e.unSubscribeInnerEvent("im_open_push.msg_push",e.InnerEventSubType.BUSINESS_COMMAND,this._onServerPushBusinessCommand,this)}};const no=1,io=2,ro=3,ao=4,co=5,lo="TIMCustomElem",uo="C2C",ho="GROUP",po="invite",go="accept",_o="cancel",mo="reject",fo="modifyInvitation",vo="signaling",Io=8010,So="signaling-timeout";function Eo(e){return e.filter((e=>{if(e.type===lo){const{cloudCustomData:t="",payload:{data:s=""}={}}=e,o=t.match(/"type":"tsignaling"/),n=s.match(/inviteID/),i=s.match(/actionType/);return o||n&&i}return!1}))}function Co(e){const{data:t}=e.payload;try{return JSON.parse(t)}catch(e){return console.error(e),null}}function yo(e,t){return e.toString(16).padStart(t,"0")}function Mo(e){if(e<0||e>53)throw new Error("Number of digits must be between 0 and 53");if(e<=30)return Math.floor(Math.random()*(1<<e));const t=e-30;return Math.floor(Math.random()*(1<<t))*(1<<30)+Math.floor(Math.random()*(1<<30))}var Ao=new class{constructor(){this._onlineSignalingMap=new Map,this._isSignalingListening=!1}init(e){this._core=e,e.notificationCenter.subscribeInnerEvent(e.InnerEvent.DESTROY,this._dispose,this),e.notificationCenter.subscribeInnerEvent(e.InnerEvent.LOGOUT,this._reset,this)}getOnlineSignalingMap(){return this._onlineSignalingMap}hasSignaling(e){return this._onlineSignalingMap.has(e)}getSignaling(e){return this._onlineSignalingMap.get(e)}saveSignaling(e,t){return this._onlineSignalingMap.set(e,t)}removeSignaling(e){return this._onlineSignalingMap.delete(e)}isInvitationValid(e){const t=`${vo}.isInvitationValid`,{inviteID:s,groupID:o,inviter:n}=e,i=n===this._core.common.getCurrentUserID();if(!this._onlineSignalingMap.has(s))return!1;const{inviteeList:r}=this._onlineSignalingMap.get(s);if(console.log(`${t} inviteID:${s} inviteeList:${r} groupID:${o}`),o){if(i)return r.length>0;const e=this._core.common.getCurrentUserID();return r.includes(e)}return!0}updateSignaling(e){const t=`${vo}.updateSignaling`,{inviteID:s,inviter:o,inviteeList:n,groupID:i}=e;if(console.log(`${t} inviteID:${s} inviter:${o} groupID:${i}`),i&&this.hasSignaling(s)){const e=n[0],{inviteeList:o}=this._onlineSignalingMap.get(s);o.includes(e)&&(o.splice(o.indexOf(e),1),console.log(`${t} remove ${e}. localInviteeList.length:${o.length}`)),0===o.length&&this.removeSignaling(s)}else this.removeSignaling(s)}setSignalingListenStatus(e){this._isSignalingListening=e}getSignalingListenStatus(){return this._isSignalingListening}_dispose(){var e,t;this._reset(),null===(e=this._core)||void 0===e||e.notificationCenter.unSubscribeInnerEvent(this._core.InnerEvent.DESTROY,this._dispose,this),null===(t=this._core)||void 0===t||t.notificationCenter.unSubscribeInnerEvent(this._core.InnerEvent.LOGOUT,this._reset,this),this._isSignalingListening=!1}_reset(){this._onlineSignalingMap.clear()}};var Oo=new class{init(e){this._core=e}createInviteSignaling(e){const t=this._generateInviteID(),s=this._createInviteSignalingData(Object.assign(Object.assign({},e),{inviteID:t})),{groupID:o,inviteeList:n}=s,i=o||n[0];return{signaling:this._createSignaling(s,i),signalingData:s,signalingExtensionOptions:this._createSignalingExtensionOptions(e)}}createAcceptSignaling(e){const t=this._createAcceptSignalingData(e),{groupID:s,inviter:o}=t,n=s||o;return{signaling:this._createSignaling(t,n),signalingData:t,signalingExtensionOptions:this._createSignalingExtensionOptions(e)}}createCancelSignaling(e){const t=this._createCancelSignalingData(e),{groupID:s,inviteeList:o}=t,n=s||o[0];return{signaling:this._createSignaling(t,n),signalingData:t,signalingExtensionOptions:this._createSignalingExtensionOptions(e)}}createRejectSignaling(e){const t=this._createRejectSignalingData(e),{groupID:s,inviter:o}=t,n=s||o;return{signaling:this._createSignaling(t,n),signalingData:t,signalingExtensionOptions:this._createSignalingExtensionOptions(e)}}createTimeoutSignaling(e){const{isInviter:t=!1}=e,s=this._createTimeoutSignalingData(e),{groupID:o,inviteeList:n,inviter:i}=s,r=o||(t?n[0]:i);return{signaling:this._createSignaling(s,r),signalingData:s,signalingExtensionOptions:this._createSignalingExtensionOptions(s)}}_createSignalingExtensionOptions(e){var t,s;const{data:o="",onlineUserOnly:n,inviteID:i="",offlinePushInfo:r,actionType:a}=e,c=(null===(s=null===(t=Ao.getSignaling(i))||void 0===t?void 0:t.signaling)||void 0===s?void 0:s._onlineOnlyFlag)||!1;return{onlineUserOnly:n||c,offlinePushInfo:r,messageControlInfo:this._createMessageControlInfo(o,a)}}_createMessageControlInfo(e,t){const s=t===co&&!!e.match(/excludeTimeoutSignalingFromHistoryMessage/),o=!!e.match(/excludeFromHistoryMessage/)||!!e.match(/excludeOriginalSignalingFromHistoryMessage/);return{excludedFromContentModeration:!0,excludedFromUnreadCount:s||o,excludedFromLastMessage:s||o}}_createInviteSignalingData(e){const t=`${vo}._createInviteSignalingData`,{userID:s,timeout:o=0,groupID:n="",inviteeList:i=[]}=e,r=this._core.common.getCurrentUserID(),a=Object.assign(Object.assign({},this._generateBaseSignalData(e)),{actionType:no,inviter:r,inviteeList:n?i:[s],timeout:o});return console.log(`${t} signalingData:`,a),a}_createAcceptSignalingData(e){const t=`${vo}._createAcceptSignalingData`,{inviteID:s}=e,o=this._core.common.getCurrentUserID(),{inviter:n,groupID:i}=Ao.getSignaling(s),r=Object.assign(Object.assign({},this._generateBaseSignalData(e)),{actionType:ro,groupID:i,inviter:n,inviteeList:[o]});return console.log(`${t} signalingData:`,r),r}_createCancelSignalingData(e){const t=`${vo}._createCancelSignalingData`,{inviteID:s}=e,o=this._core.common.getCurrentUserID(),{inviteeList:n,groupID:i}=Ao.getSignaling(s),r=Object.assign(Object.assign({},this._generateBaseSignalData(e)),{actionType:io,groupID:i,inviter:o,inviteeList:n});return console.log(`${t} signalingData:`,r),r}_createRejectSignalingData(e){const t=`${vo}._createRejectSignalingData`,{inviteID:s}=e,o=this._core.common.getCurrentUserID(),{inviter:n,groupID:i}=Ao.getSignaling(s),r=Object.assign(Object.assign({},this._generateBaseSignalData(e)),{actionType:ao,groupID:i,inviter:n,inviteeList:[o]});return console.log(`${t} signalingData:`,r),r}_createTimeoutSignalingData(e){const t=`${vo}._createTimeoutSignalingData`,{isInviter:s=!1,inviteID:o}=e,{inviteeList:n,inviter:i}=Ao.getSignaling(o),r=this._core.common.getCurrentUserID(),a=Object.assign(Object.assign({},this._generateBaseSignalData(e)),{actionType:co,inviter:i,inviteeList:s?n:[r]});return console.log(`${t} signalingData:`,a),a}_createSignaling(e,t){var s,o,n;const{groupID:i=""}=e,r={to:t,conversationType:i?ho:uo,priority:"High",payload:{data:JSON.stringify(e)}};return null===(n=null===(o=null===(s=this._core)||void 0===s?void 0:s.message)||void 0===o?void 0:o.messageFactory)||void 0===n?void 0:n.createCustomMessage(r)}_generateInviteID(){return[yo(Mo(32),8),yo(Mo(16),4),yo(16384|Mo(12),4),yo(32768|Mo(14),4),yo(Mo(48),12)].join("-")}_generateBaseSignalData(e){const{data:t="",inviteID:s="",groupID:o=""}=e;return{businessID:1,timeout:0,data:t,inviteID:s,groupID:o}}};var To=new class{constructor(){this._isProcessingSignaling=!1}init(e){this._core=e,e.helper.registerApi({apiName:"invite",context:this}),e.helper.registerApi({apiName:"accept",context:this}),e.helper.registerApi({apiName:"cancel",context:this}),e.helper.registerApi({apiName:"reject",context:this}),e.helper.registerApi({apiName:"modifyInvitation",context:this}),e.helper.registerApi({apiName:"getSignalingInfo",context:this}),e.helper.registerApi({apiName:"addSignalingListener",context:this}),e.helper.registerApi({apiName:"removeSignalingListener",context:this}),e.notificationCenter.subscribeInnerEvent(e.InnerEvent.DESTROY,this._dispose,this),e.notificationCenter.subscribeInnerEvent(e.InnerEvent.LOGOUT,this._reset,this)}invite(e){return a(this,void 0,void 0,(function*(){var t;console.log(`${vo}.invite params:${JSON.stringify(e)}`);try{this._validateBeforeInvite(e);const{signaling:s,signalingData:o,signalingExtensionOptions:n}=Oo.createInviteSignaling(e),i=yield this._sendSignaling(s,n);if(0===(null==i?void 0:i.code)){const{inviteID:e,timeout:n}=o;return Ao.saveSignaling(e,Object.assign(Object.assign({},o),{signaling:s})),n>0&&(null===(t=this._core)||void 0===t||t.helper.taskScheduler.addOnceTask({id:`${So}-${e}`,intervalMs:1e3*(n+5),callback:this.handleInvitationExpiryTimer.bind(this,e)})),Object.assign(Object.assign({},i),{inviteID:e})}return i}catch(e){throw console.error(`${vo}.invite error:${e}`),e}}))}accept(e){return a(this,void 0,void 0,(function*(){console.log(`${vo}.accept params:${JSON.stringify(e)}`);try{const{inviteID:t}=e;this._validateBeforeAccept(t),this._isProcessingSignaling=!0;const{signaling:s,signalingData:o,signalingExtensionOptions:n}=Oo.createAcceptSignaling(e),i=yield this._sendSignaling(s,n);return 0===(null==i?void 0:i.code)?(Ao.updateSignaling(o),Object.assign(Object.assign({},i),{inviteID:t})):i}catch(e){throw console.error(`${vo}.accept error:${e}`),e}finally{this._isProcessingSignaling=!1}}))}cancel(e){return a(this,void 0,void 0,(function*(){console.log(`${vo}.cancel params:${JSON.stringify(e)}`);try{const{inviteID:t}=e;this._validateBeforeCancel(t),this._isProcessingSignaling=!0;const{signaling:s,signalingExtensionOptions:o}=Oo.createCancelSignaling(e),n=yield this._sendSignaling(s,o);return 0===(null==n?void 0:n.code)?(Ao.removeSignaling(t),Object.assign(Object.assign({},n),{inviteID:t})):n}catch(e){throw console.error(`${vo}.cancel error:${e}`),e}finally{this._isProcessingSignaling=!1}}))}reject(e){return a(this,void 0,void 0,(function*(){console.log(`${vo}.reject params:${JSON.stringify(e)}`);try{const{inviteID:t}=e;this._validateBeforeReject(t),this._isProcessingSignaling=!0;const{signaling:s,signalingExtensionOptions:o}=Oo.createRejectSignaling(e),n=yield this._sendSignaling(s,o);return 0===(null==n?void 0:n.code)?(Ao.removeSignaling(t),Object.assign(Object.assign({},n),{inviteID:t})):n}catch(e){throw console.error(`${vo}.reject error:${e}`),e}finally{this._isProcessingSignaling=!1}}))}modifyInvitation(e){return a(this,void 0,void 0,(function*(){var t,s;console.log(`${vo}.modifyInvitation params:${JSON.stringify(e)}`);const{inviteID:o,data:n}=e;let i="";try{this._validateBeforeModifyInvitation(o);const e=Ao.getSignaling(o),{signaling:a}=e,c=r(e,["signaling"]);i=a.payload.data,c.data=n,a.payload.data=JSON.stringify(c);const l=yield null===(s=null===(t=this._core)||void 0===t?void 0:t.message.messageAction)||void 0===s?void 0:s.modifyMessage(a);return Ao.hasSignaling(o)&&Ao.saveSignaling(o,Object.assign(Object.assign({},c),{signaling:a})),l}catch(e){if(i){const{signaling:e}=Ao.getSignaling(o);e.payload.data=i}throw e}}))}getSignalingInfo(e){if(0===Eo([e]).length)return;const t=Co(e),s={businessID:t.businessID||1,inviteID:t.inviteID,groupID:t.groupID||"",inviter:t.inviter||"",inviteeList:t.inviteeList||[],data:t.data||"",actionType:t.actionType||no,timeout:t.timeout||0};return console.log(`${vo} getSignalingInfo `,s),s}addSignalingListener(e,t,s){var o,n;e===(null===(o=this._core)||void 0===o?void 0:o.SignalingEvent.NEW_INVITATION_RECEIVED)&&Ao.setSignalingListenStatus(!0),null===(n=this._core)||void 0===n||n.notificationCenter.subscribeOuterEvent(e,t,s)}removeSignalingListener(e,t,s){var o,n;e===(null===(o=this._core)||void 0===o?void 0:o.SignalingEvent.NEW_INVITATION_RECEIVED)&&Ao.setSignalingListenStatus(!1),null===(n=this._core)||void 0===n||n.notificationCenter.unSubscribeOuterEvent(e,t,s)}handleInvitationExpiryTimer(e){const t=Ao.getOnlineSignalingMap(),s=this._core.common.getCurrentUserID();if(!t.has(e))return;const o=t.get(e).inviter===s;this._sendTimeoutNotice({inviteID:e,isInviter:o})}_sendSignaling(e,t){return a(this,void 0,void 0,(function*(){var s,o,n;return null===(n=null===(o=null===(s=this._core)||void 0===s?void 0:s.message)||void 0===o?void 0:o.messageSender)||void 0===n?void 0:n.sendMessage(e,t)}))}_sendTimeoutNotice(e){return a(this,void 0,void 0,(function*(){var t,s,o;console.log(`${vo}._sendTimeoutNotice params:${JSON.stringify(e)}`);const{isInviter:n,inviteID:i}=e,{signaling:r,signalingData:a,signalingExtensionOptions:c}=Oo.createTimeoutSignaling(e),l=yield this._sendSignaling(r,c);if(0===(null==l?void 0:l.code)){const{data:e,groupID:c,inviteeList:l,inviter:u}=a;null===(t=this._core)||void 0===t||t.notificationCenter.emitOuterEvent(null===(s=this._core)||void 0===s?void 0:s.SignalingEvent.INVITATION_TIMEOUT,{name:null===(o=this._core)||void 0===o?void 0:o.SignalingEvent.INVITATION_TIMEOUT,data:{data:e,groupID:c,inviteID:i,inviteeList:l,inviter:u,isSelfTimeout:!0,message:r}}),n?Ao.removeSignaling(i):Ao.updateSignaling(a)}}))}_validateInviteId(e,t){if(!Ao.hasSignaling(t))throw new this._core.helper.ChatError({functionName:e,code:Io})}_validateProcessStatus(e){if(this._isProcessingSignaling)throw new this._core.helper.ChatError({functionName:e,message:"processing other signaling operations"})}_validateBeforeInvite(e){const t=po,{userID:s}=e,o=this._core.common.getCurrentUserID();if(s===o)throw new this._core.helper.ChatError({functionName:t,message:`cannot invite yourself, currentUserId:${o}, inviteeId:${s}`})}_validateBeforeAccept(e){const t=go;this._validateInviteId(t,e),this._validateProcessStatus(t);const s=this._core.common.getCurrentUserID(),{inviteeList:o}=Ao.getSignaling(e);if(!o.includes(s)){const o=`userID:${s} not in inviteeList. inviteID:${e}`;throw new this._core.helper.ChatError({functionName:t,message:o})}}_validateBeforeCancel(e){const t=_o;this._validateInviteId(t,e),this._validateProcessStatus(t);const s=this._core.common.getCurrentUserID(),{inviter:o}=Ao.getSignaling(e);if(o!==s){const e=`unmatched inviter:${o} and my userID:${s}`;throw new this._core.helper.ChatError({functionName:t,message:e})}}_validateBeforeReject(e){const t=mo;this._validateInviteId(t,e),this._validateProcessStatus(t);const s=this._core.common.getCurrentUserID(),{inviteeList:o}=Ao.getSignaling(e);if(!o.includes(s)){const o=`userID:${s} not in inviteeList. inviteID:${e}`;throw new this._core.helper.ChatError({functionName:t,message:o})}}_validateBeforeModifyInvitation(e){const t=fo;this._validateInviteId(t,e)}_dispose(){var e,t;this._reset(),null===(e=this._core)||void 0===e||e.notificationCenter.unSubscribeInnerEvent(this._core.InnerEvent.DESTROY,this._dispose,this),null===(t=this._core)||void 0===t||t.notificationCenter.unSubscribeInnerEvent(this._core.InnerEvent.LOGOUT,this._reset,this)}_reset(){this._isProcessingSignaling=!1}};var Do=new class{constructor(){this._actionProcessor=new Map([[no,this._onNewInvitationReceived.bind(this)],[ao,this._onInviteeRejected.bind(this)],[ro,this._onInviteeAccepted.bind(this)],[io,this._onInvitationCancelled.bind(this)],[co,this._onInvitationTimeout.bind(this)]])}init(e){this._core=e,e.notificationCenter.subscribeOuterEvent(e.OuterEvent.MESSAGE_RECEIVED,this._handleMessageReceived,this),e.notificationCenter.subscribeOuterEvent(e.OuterEvent.MESSAGE_MODIFIED,this._handleMessageModified,this),e.notificationCenter.subscribeInnerEvent(e.InnerEvent.DESTROY,this._dispose,this)}handleActionSignaling(e){e.forEach((e=>{const t=Co(e);if(t){const s=this._actionProcessor.get(t.actionType);null==s||s(t,e)}}))}_handleMessageReceived(e){if(!Ao.getSignalingListenStatus())return;const t=Eo(e.data);0!==t.length&&this.handleActionSignaling(t)}_handleMessageModified(e){if(!Ao.getSignalingListenStatus())return;const t=Eo(e.data);t.length>0&&t.forEach((e=>{const t=Co(e);t&&this._onInvitationModified(t,e)}))}_onNewInvitationReceived(e,t){var s,o;const n=`${vo}._onNewInvitationReceived`,{inviteID:i,inviteeList:r,groupID:a}=e,c=this._core.common.getCurrentUserID();console.log(`${n} signalingData:${JSON.stringify(e)}}`);if(a&&!r.includes(c))return;let{timeout:l}=e;const u=Date.now()/1e3-t.time;l>0&&u>0&&l>u&&(l-=u);const d=Ao.getSignaling(i);d!==e&&(d||Ao.saveSignaling(i,Object.assign(Object.assign({},e),{signaling:t})),l>0&&(null===(s=this._core)||void 0===s||s.helper.taskScheduler.addOnceTask({id:`${So}-${i}`,intervalMs:1e3*l,callback:To.handleInvitationExpiryTimer.bind(To,i)})),this._emitEvent({name:null===(o=this._core)||void 0===o?void 0:o.SignalingEvent.NEW_INVITATION_RECEIVED,data:Object.assign(Object.assign({},this._generateBaseEmitData(e)),{inviteeList:r})}))}_onInviteeRejected(e){var t;const s=`${vo}._onInviteeRejected`,{inviteID:o,inviter:n,groupID:i,inviteeList:r}=e,a=Ao.hasSignaling(o);console.log(`${s} inviteID:${o} hasInviteID:${a} inviter:${n} groupID:${i}`),a&&(Ao.updateSignaling(e),this._emitEvent({name:null===(t=this._core)||void 0===t?void 0:t.SignalingEvent.INVITEE_REJECTED,data:Object.assign(Object.assign({},this._generateBaseEmitData(e)),{invitee:r[0]})}))}_onInviteeAccepted(e){var t;const s=`${vo}._onInviteeAccepted`,{inviteID:o,inviter:n,groupID:i,inviteeList:r}=e,a=Ao.hasSignaling(o);console.log(`${s} inviteID:${o} hasInviteID:${a} inviter:${n} groupID:${i}`),a&&(Ao.updateSignaling(e),this._emitEvent({name:null===(t=this._core)||void 0===t?void 0:t.SignalingEvent.INVITEE_ACCEPTED,data:Object.assign(Object.assign({},this._generateBaseEmitData(e)),{invitee:r[0]})}))}_onInvitationCancelled(e){var t;const s=`${vo}._onInvitationCancelled`,{inviteID:o,inviter:n,groupID:i}=e,r=Ao.hasSignaling(o);console.log(`${s} inviteID:${o} hasInviteID:${r} inviter:${n} groupID:${i}`),r&&(Ao.removeSignaling(o),this._emitEvent({name:null===(t=this._core)||void 0===t?void 0:t.SignalingEvent.INVITATION_CANCELLED,data:this._generateBaseEmitData(e)}))}_onInvitationTimeout(e){var t;const s=`${vo}._onInvitationTimeout`,{inviteID:o,inviteeList:n}=e,i=Ao.hasSignaling(o);console.log(`${s} inviteID:${o} hasInviteID:${i} data:${e.data}`),i&&(Ao.updateSignaling(e),this._emitEvent({name:null===(t=this._core)||void 0===t?void 0:t.SignalingEvent.INVITATION_TIMEOUT,data:Object.assign(Object.assign({},this._generateBaseEmitData(e)),{inviteeList:n,isSelfTimeout:!1})}))}_onInvitationModified(e,t){var s;const o=`${vo}._onInvitationModified`,{inviteID:n,data:i}=e,r=Ao.hasSignaling(n);console.log(`${o} inviteID:${n} data:${i}`),r&&(Ao.saveSignaling(n,Object.assign(Object.assign({},e),{signaling:t})),this._emitEvent({name:null===(s=this._core)||void 0===s?void 0:s.SignalingEvent.INVITATION_MODIFIED,data:{inviteID:n,data:i}}))}_emitEvent(e){var t;null===(t=this._core)||void 0===t||t.notificationCenter.emitOuterEvent(e.name,e)}_generateBaseEmitData(e){const{inviteID:t,inviter:s,groupID:o,data:n}=e;return{inviteID:t,inviter:s,groupID:o,data:n||""}}_dispose(){var e,t,s;null===(e=this._core)||void 0===e||e.notificationCenter.unSubscribeOuterEvent(this._core.OuterEvent.MESSAGE_RECEIVED,this._handleMessageReceived,this),null===(t=this._core)||void 0===t||t.notificationCenter.unSubscribeOuterEvent(this._core.OuterEvent.MESSAGE_MODIFIED,this._handleMessageModified,this),null===(s=this._core)||void 0===s||s.notificationCenter.unSubscribeOuterEvent(this._core.InnerEvent.DESTROY,this._dispose,this)}};var Ro=new class{constructor(){this._offlineSignalingMap=new Map}init(e){this._core=e;const{notificationCenter:t,helper:s,constants:{InnerEvent:o,WORKFLOW_STEP:n,WORKFLOW_NAME:i}}=e;t.subscribeInnerEvent(o.DESTROY,this._dispose,this),t.subscribeInnerEvent(o.LOGOUT,this._reset,this),s.registerWorkflowStep(i.SYNC_SERVER_INFO_AFTER_LOGIN,n.SIGNALING_MESSAGE_RECOVER,this._handleC2COfflineMessage,this)}_handleC2COfflineMessage(e){const{result:{unreadMessageMap:t}={}}=e||{};if(!(0!==(null==t?void 0:t.size)&&Ao.getSignalingListenStatus()))return;const s=Eo([...t.values()]);if(0!==s.length&&(s.forEach((e=>{this._handleC2CActionType(e)})),this._offlineSignalingMap.size>0)){const e=this._sortOfflineSignalingByTime();Do.handleActionSignaling(e)}}_handleC2CActionType(e){const t=Co(e);if(!t)return;const{actionType:s}=t;s===no?this._saveValidOfflineInvite(t,e):this._removeOfflineInvite(t)}_saveValidOfflineInvite(e,t){const{inviteID:s,inviteeList:o=[],timeout:n=0}=e,i=this._core.common.getCurrentUserID();if(!o.includes(i))return;const r=Date.now()/1e3-t.time;n>0&&r>n&&0!==n||this._offlineSignalingMap.set(s,Object.assign(Object.assign({},e),{signalingList:[t]}))}_removeOfflineInvite(e){const{inviteID:t=""}=e;this._offlineSignalingMap.has(t)&&this._offlineSignalingMap.delete(t)}_sortOfflineSignalingByTime(){let e=[];return this._offlineSignalingMap.forEach((t=>{e=[...e,...t.signalingList]})),e.sort(((e,t)=>e.time-t.time))}_dispose(){var e,t;this._reset(),null===(e=this._core)||void 0===e||e.notificationCenter.unSubscribeInnerEvent(this._core.InnerEvent.LOGOUT,this._reset,this),null===(t=this._core)||void 0===t||t.notificationCenter.unSubscribeInnerEvent(this._core.InnerEvent.DESTROY,this._dispose,this)}_reset(){this._offlineSignalingMap.clear()}};const Lo={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}}},No={invite:!0,cancel:!0,accept:!0,reject:!0,modifyInvitation:!0};var bo=new class{install(e){To.init(e),Do.init(e),Oo.init(e),Ao.init(e),Ro.init(e),e.helper.registerValidateConfig({auth:No,params:Lo})}};const wo=new class{init(e){this.core=e}};var Po,Uo,Go;!function(e){e.MSG_TEXT="TIMTextElem",e.MSG_CUSTOM="TIMCustomElem",e.MSG_LOCATION="TIMLocationElem",e.MSG_FACE="TIMFaceElem"}(Po||(Po={})),function(e){e[e.DATA_HAS_EXPIRED=0]="DATA_HAS_EXPIRED",e[e.HAS_MORE_DATA=1]="HAS_MORE_DATA",e[e.NO_MORE_DATA=2]="NO_MORE_DATA"}(Uo||(Uo={})),function(e){e[e.FORWARD=0]="FORWARD",e[e.BACKWARD=1]="BACKWARD"}(Go||(Go={}));const ko="MSG_REACTION",Fo=0,$o=1,qo={ZH_CN:"zh (cmn-Hans-CN)",EN_US:"en-US",YUE_HK:"yue-Hant-HK",JA_JP:"ja-JP",ZH_PY:"zh-PY"},xo="16k_zh",Vo="16k_en",Bo="16k_yue",jo="16k_ja",Wo="16k_zh-PY",Ko={[qo.ZH_CN]:xo,[qo.EN_US]:Vo,[qo.YUE_HK]:Bo,[qo.JA_JP]:jo,[qo.ZH_PY]:Wo},Ho=/\.(wav|pcm|ogg-opus|speex|silk|mp3|m4a|aac|amr)/,Yo={READ:0,UNREAD:1};const zo=2116,Jo="C2C",Zo="GROUP",Xo=20,Qo=1,en=300;function tn(e){return a(this,void 0,void 0,(function*(){var t;const{appStore:s}=wo.core,{messageList:o,conversationID:n}=e,i=s.conversationStore.getConversationMap();let r=null===(t=i.get(n))||void 0===t?void 0:t.peerReadTime;if(!r){const e=n.replace(Jo,""),t=yield function(e){return a(this,void 0,void 0,(function*(){const t={To_Account:e};return wo.core.common.buildAndSendPacket({servcmd:"openim.get_peer_read_time",data:t})}))}([e]);if(t){const{ReadTime:e}=t;r=null==e?void 0:e[0],i.has(n)&&(i.get(n).peerReadTime=r)}}o.forEach((e=>{e.time<=r&&!e.isPeerRead&&"out"===e.flow&&(e.isPeerRead=!0)}))}))}function sn(e){return a(this,void 0,void 0,(function*(){var t;const{message:s,user:o,appStore:n,constants:{OuterConstant:i}}=wo.core,r=n.conversationStore.getConversationMap();if(r.has(e)){const n=null===(t=r.get(e))||void 0===t?void 0:t.userProfile;if(n&&e.startsWith(i.CONV_C2C)){const{avatar:t,nick:s}=n;wo.core.message.messageDataHandler.updateNickAndAvatarOfSentMessage({conversationID:e,latestAvatar:t,latestNick:s,isSentByMe:!1})}const{data:a}=(yield o.userProfile.getMyProfile())||{};if(a){const{avatar:t,nick:o}=a;s.messageDataHandler.updateNickAndAvatarOfSentMessage({conversationID:e,latestAvatar:t,latestNick:o,isSentByMe:!0})}}}))}function on(e){let t;const{message:s}=wo.core,{conversationID:o,messageID:n}=e;if(t=s.messageDataHandler.getLocalMessageList(o).find((e=>e.ID===n)),!t){t=s.messageDataHandler.getSparseMessageList(o).find((e=>e.ID===n))}return t}function nn(e){return e.map((e=>{const{from:t,to:s,cloudCustomData:o,avatar:n,nick:i,ID:r,clientSequence:a,clientTime:c,messageRandom:l,messageSequence:u,time:d}=e;return{ClientSeq:a,CloudCustomData:o,From_Account:t,From_AccountHeadurl:n,From_AccountNick:i,Id:r,MsgBody:JSON.parse(JSON.stringify(e.transformElementsToServerFormat())),MsgClientTime:c,MsgRandom:l,Random:l,MsgSeq:u,MsgTimeStamp:d,ReceiverId:s,SenderId:t,To_Account:s}}))}function rn(e){var t;const{From_Account:s,From_AccountHeadurl:o,From_AccountNick:n,GroupId:i,MsgClientTime:r,ClientSeq:a,To_Account:c,MsgTimeStamp:l,TinyId:u,MsgRandom:d,MsgSeq:h}=e;return{from:s,avatar:o,nick:n,clientTime:r,time:l,tinyID:u,random:d,sequence:h,to:c,groupID:i,clientSequence:a,_elements:null===(t=e.MsgBody)||void 0===t?void 0:t.map((e=>{const{MsgType:t}=e;return wo.core.message.messageFactory.getElementClass(t).parseServerPushElement(e)}))}}var an=new class{constructor(){this._reactionsMap=new Map}init(e){this._core=e;const{helper:t,notificationCenter:s,InnerEvent:{MESSAGE_PUSH:o},InnerEventSubType:{MESSAGE_REACTION_UPDATED:n,MESSAGE_REACTION_UPDATED_SYNC:i}}=e;t.registerApi({apiName:"addMessageReaction",context:this}),t.registerApi({apiName:"removeMessageReaction",context:this}),t.registerApi({apiName:"getMessageReactions",context:this}),t.registerApi({apiName:"getAllUserListOfMessageReaction",context:this}),s.subscribeInnerEvent(o,n,this._handleReactionUpdated,this),s.subscribeInnerEvent(o,i,this._handleReactionSync,this)}addMessageReaction(e,t){return a(this,void 0,void 0,(function*(){const{OuterConstant:s,ssoLog:o,helper:n}=this._core;this._validateMessageReactionBusinessCapability();const i=o.createSSOLogData({method:"addMessageReaction"}),{conversationID:r,ID:c,conversationType:l,from:u,to:d,clientSequence:h,random:p,time:g,sequence:_}=e;try{return this._recordMessageReactedByMe(c,t),l===s.CONV_C2C?yield function(e,t){return a(this,void 0,void 0,(function*(){var s;const{from:o,to:n,clientSequence:i,random:r,time:a,reactionID:c}=e,l={From_Account:o,To_Account:n,MsgKey:`${i}_${r}_${a}`,Reaction:c,Add_Account:[null===(s=t.store.get("login"))||void 0===s?void 0:s.userId]};return wo.core.common.buildAndSendPacket({servcmd:"openim_msg_ext_http_svc.reaction_add",data:l})}))}({from:u,to:d,clientSequence:h,random:p,time:g,reactionID:t},this._core):l===s.CONV_GROUP&&(yield function(e,t){return a(this,void 0,void 0,(function*(){var s;const{to:o,reactionID:n,sequence:i}=e,r={GroupId:o,MsgSeq:i,Reaction:n,Add_Account:[null===(s=t.store.get("login"))||void 0===s?void 0:s.userId]};return wo.core.common.buildAndSendPacket({servcmd:"openim_msg_ext_http_svc.group_reaction_add",data:r})}))}({to:d,reactionID:t,sequence:_},this._core)),i.setLogInfo({message:`conversationID:${r} messageID:${c} reactionID:${t}`}).end(),{code:0}}catch(e){this._removeMyReactionRecord(c,t);const{errorCode:s}=e||{},o=new n.ChatError({functionName:"addMessageReaction",code:s});i.setError(o).end(),console.error("addMessageReaction error: ",e)}}))}removeMessageReaction(e,t){return a(this,void 0,void 0,(function*(){const{OuterConstant:s,ssoLog:o,helper:n}=this._core;this._validateMessageReactionBusinessCapability();const i=o.createSSOLogData({method:"removeMessageReaction"});try{const{conversationID:o,ID:n,conversationType:r,from:c,to:l,clientSequence:u,random:d,time:h,sequence:p}=e;return this._removeMyReactionRecord(n,t),r===s.CONV_C2C?yield function(e,t){return a(this,void 0,void 0,(function*(){var s;const{from:o,to:n,clientSequence:i,random:r,time:a,reactionID:c}=e,l={From_Account:o,To_Account:n,MsgKey:`${i}_${r}_${a}`,Reaction:c,Del_Account:[null===(s=t.store.get("login"))||void 0===s?void 0:s.userId]};return wo.core.common.buildAndSendPacket({servcmd:"openim_msg_ext_http_svc.reaction_del",data:l})}))}({from:c,to:l,clientSequence:u,random:d,time:h,reactionID:t},this._core):r===s.CONV_GROUP&&(yield function(e,t){return a(this,void 0,void 0,(function*(){var s;const{common:{isTopic:o},constants:{OuterConstant:{GROUP_ID_PREFIX:n}}}=wo.core,{to:i,reactionID:r,sequence:a}=e,c=null===(s=t.store.get("login"))||void 0===s?void 0:s.userId;let l,u=i;o(i)&&(l=i,u=l.split(n.TOPIC)[0]);const d={TopicId:l,GroupId:u,MsgSeq:a,Reaction:r,Del_Account:[c]};return wo.core.common.buildAndSendPacket({servcmd:"openim_msg_ext_http_svc.group_reaction_del",data:d},t)}))}({to:l,reactionID:t,sequence:p},this._core)),i.setLogInfo({message:`conversationID:${o} messageID:${n} reactionID:${t}`}).end(),{code:0}}catch(e){const{errorCode:t}=e||{},s=new n.ChatError({functionName:"removeMessageReaction",code:t});i.setError(s).end(),console.error("removeMessageReaction error: ",e)}}))}getAllUserListOfMessageReaction(e){return a(this,void 0,void 0,(function*(){this._validateMessageReactionBusinessCapability();const{message:t,reactionID:s,nextSeq:o=0}=e,n=e.count>100?100:e.count,{conversationID:i}=t,{ssoLog:r,helper:c,constants:l}=this._core;try{let e=null;if(e=i.startsWith(l.OuterConstant.CONV_C2C)?yield function(e){return a(this,void 0,void 0,(function*(){const{message:t,nextSeq:s,reactionID:o,count:n}=e,{from:i,to:r,clientSequence:a,random:c,time:l}=t,u={Reaction:o,NextSeq:s,Count:n,From_Account:i,To_Account:r,MsgKey:`${a}_${c}_${l}`};return wo.core.common.buildAndSendPacket({servcmd:"openim_msg_ext_http_svc.reaction_iterate",data:u})}))}({message:t,reactionID:s,nextSeq:o,count:n}):yield function(e){return a(this,void 0,void 0,(function*(){const{common:{isTopic:t},constants:{OuterConstant:{GROUP_ID_PREFIX:s}}}=wo.core,{message:o,nextSeq:n,reactionID:i,count:r}=e,{sequence:a}=o;let c,l=o.to;t(o.to)&&(c=o.to,l=c.split(s.TOPIC)[0]);const u={Reaction:i,NextSeq:n,TopicId:c,GroupId:l,Count:r,MsgSeq:a};return wo.core.common.buildAndSendPacket({servcmd:"openim_msg_ext_http_svc.group_reaction_iterate",data:u})}))}({message:t,reactionID:s,nextSeq:o,count:n}),e){const{Reaction_Account:t,NextSeq:s}=e,n=yield this._getUserProfileList(t);return{code:0,data:{nextSeq:s,isCompleted:0===o,userList:n}}}}catch(e){const{errorCode:t}=e||{},s=new c.ChatError({functionName:"getAllUserListOfMessageReaction",code:t});r.createSSOLogData({method:"removeMessageReaction"}).setError(s).end(),console.error("getAllUserListOfMessageReaction error: ",e)}}))}getMessageReactions(e){return a(this,void 0,void 0,(function*(){const{constants:t}=this._core;this._validateMessageReactionBusinessCapability();const{messageList:s,maxUserCountPerReaction:o=10}=e,n=s[0];let i=null;const r=new Map,{from:c,to:l,conversationType:u}=n,d=this._generateMessageKeyList(s,r);u===t.OuterConstant.CONV_C2C?i=yield function(e){return a(this,void 0,void 0,(function*(){const{from:t,to:s,messageKeyList:o,maxUserCountPerReaction:n}=e,i={From_Account:t,To_Account:s,MsgKeyList:o,Count:n};return wo.core.common.buildAndSendPacket({servcmd:"openim_msg_ext_http_svc.reaction_multi_stat",data:i})}))}({from:c,to:l,messageKeyList:d,maxUserCountPerReaction:o}):u===t.OuterConstant.CONV_GROUP&&(i=yield function(e){return a(this,void 0,void 0,(function*(){const{common:{isTopic:t},constants:{OuterConstant:{GROUP_ID_PREFIX:s}}}=wo.core;let o,{groupId:n,messageSequenceList:i,maxUserCountPerReaction:r}=e;t(n)&&(o=n,n=n.split(s.TOPIC)[0]);const a={GroupId:n,TopicId:o,MsgSeqList:i,Count:r};return wo.core.common.buildAndSendPacket({servcmd:"openim_msg_ext_http_svc.group_reaction_multi_stat",data:a})}))}({groupId:l,messageSequenceList:d,maxUserCountPerReaction:o}));const{Results:h=[]}=i||{},p=this._extractUserIDsFromReactionResults(h),g=yield this._getUserProfileMap(p);return{code:0,data:{resultList:h.map((e=>{const{ReactionList:t,MsgSeq:s,MsgKey:o}=e;return{messageID:this._generateMessageID({messageSequence:s,messageKey:o,messageIDMap:r}),reactionList:t.map((e=>{const{Reaction:t,Count:s,Reaction_Account:o,ReactedByMe:n}=e;return{reactionID:t,totalUserCount:s,partialUserList:this._generatePartialUserInfo({userIDList:o,userProfileMap:g}),reactedByMyself:1===n}}))}}))}}}))}dispose(){this._reactionsMap.clear()}_extractUserIDsFromReactionResults(e){const t=[];return null==e||e.forEach((e=>{const{ReactionList:s=[]}=e;s.forEach((e=>{e.Reaction_Account&&t.push(...e.Reaction_Account)}))})),t}_getUserProfileList(e){return a(this,void 0,void 0,(function*(){var t;try{const s=yield null===(t=this._core.user.userProfile)||void 0===t?void 0:t.getUserProfile({userIDList:e});return s?s.data:[]}catch(e){return[]}}))}_getUserProfileMap(e){return a(this,void 0,void 0,(function*(){const t=new Map;return(yield this._getUserProfileList(e)).forEach((e=>{const{nick:s,avatar:o,userID:n}=e;t.set(n,{nick:s,avatar:o,userID:n})})),t}))}_recordMessageReactedByMe(e,t){const s=`${e}-${t}`;this._reactionsMap.has(s)?this._reactionsMap.get(s).reactedByMe=!0:this._reactionsMap.set(s,{reactedByMe:!0})}_removeMyReactionRecord(e,t){const s=`${e}-${t}`;this._reactionsMap.has(s)&&(this._reactionsMap.get(s).reactedByMe=!1)}_recordMessageReactionInfo(e){const{messageID:t,reactionID:s,reactionInfo:o}=e,n=`${t}-${s}`,i=this._reactionsMap.get(n)||{};this._reactionsMap.set(n,Object.assign(Object.assign({},i),o))}_validateMessageReactionBusinessCapability(){const{helper:e,constants:t}=this._core;if(!e.checkBusinessCapabilityBits(ko))throw new e.ChatError({functionName:"addMessageReaction",code:t.ERROR_CODE.NO_USE,replacement1:"addMessageReaction"})}_handleReactionUpdated(e){const{MsgReactionNotifyList:t}=e,{notificationCenter:s,constants:o}=this._core;t.forEach((e=>a(this,void 0,void 0,(function*(){const{C2CMsgInfo:t,GroupMsgInfo:n,MsgReactionSummary:i}=e,{TinyId:r,MsgClientTime:a,MsgRandom:c}=Object.assign(Object.assign({},t),n),l=`${r}-${a}-${c}`,u=this._extractUserIDsFromReactionResults([{ReactionList:i}]),d=yield this._getUserProfileMap(u),h=i.map((e=>{var t;const{Reaction:s,Reaction_Account:o}=e,n=this._generatePartialUserInfo({userIDList:o,userProfileMap:d}),i=o?e.Count:0,r=(null===(t=this._reactionsMap.get(`${l}-${s}`))||void 0===t?void 0:t.reactedByMe)||!1;return this._recordMessageReactionInfo({messageID:l,reactionID:s,reactionInfo:{reactionID:s,totalUserCount:i,partialUserList:n}}),{reactionID:s,totalUserCount:i,partialUserList:n,reactedByMyself:r}}));s.emitOuterEvent(o.OuterEvent.MESSAGE_REACTIONS_UPDATED,{name:o.OuterEvent.MESSAGE_REACTIONS_UPDATED,data:{messageID:l,reactionList:h}})}))))}_handleReactionSync(e){var t;const{notificationCenter:s,constants:o}=this._core,{C2CMsgInfo:n={},GroupMsgInfo:i={},Reaction:r,OperateType:a}=e.MsgReactionNotify,{TinyId:c="",MsgClientTime:l=0,MsgRandom:u=0}=Object.assign(Object.assign({},n),i),d=`${c}-${l}-${u}`,h=`${d}-${r}`;if(1===a?this._recordMessageReactedByMe(d,r):this._removeMyReactionRecord(d,r),null===(t=this._reactionsMap.get(h))||void 0===t?void 0:t.reactionID){const e=this._reactionsMap.get(h);e.reactedByMyself=1===a,s.emitOuterEvent(o.OuterEvent.MESSAGE_REACTIONS_UPDATED,{name:o.OuterEvent.MESSAGE_REACTIONS_UPDATED,data:{messageID:d,reactionList:[e]}})}}_generatePartialUserInfo({userIDList:e,userProfileMap:t}){const s=[];return null==e||e.forEach((e=>{t.has(e)&&s.push(t.get(e))})),s}_generateMessageID(e){const{messageSequence:t,messageKey:s,messageIDMap:o}=e;return s?o.get(s):o.get(t)}_generateMessageKeyList(e,t){const{constants:s}=this._core,o=e[0],{conversationType:n}=o;let i=[];return n===s.OuterConstant.CONV_C2C?i=e.map((e=>{const{clientSequence:s,random:o,time:n,ID:i}=e,r=`${s}_${o}_${n}`;return t.set(r,i),r})):n===s.OuterConstant.CONV_GROUP&&(i=e.map((e=>{const{ID:s,sequence:o}=e;return t.set(o,s),o}))),i}};var cn=new class{init(e){this._core=e;const{helper:t,InnerEvent:{MESSAGE_PUSH:s},InnerEventSubType:{C2C_MESSAGE_READ_RECEIPT:o,GROUP_MESSAGE_READ_RECEIPT:n},notificationCenter:i}=e;t.registerApi({apiName:"sendMessageReadReceipt",context:this}),t.registerApi({apiName:"getMessageReadReceiptList",context:this}),t.registerApi({apiName:"getGroupMessageReadMemberList",context:this}),i.subscribeInnerEvent(s,o,this._handleC2CMessageReadReceipt,this),i.subscribeInnerEvent(s,n,this._handleGroupMessageReadReceipt,this)}sendMessageReadReceipt(e){return a(this,void 0,void 0,(function*(){const{common:t,constants:s}=this._core,o=this._filterValidMessageSendByOther(e);if(0===o.length)throw new t.ChatError({code:s.ERROR_CODE.READ_RECEIPT_MSG_LIST_EMPTY});try{const{conversationType:e}=o[0];return e===s.OuterConstant.CONV_C2C?yield function(e){return a(this,void 0,void 0,(function*(){const{common:t,constants:s}=wo.core,o=e[0].conversationID.replace(s.OuterConstant.CONV_C2C,""),n=e.map((e=>{const{from:t,to:s,sequence:o,random:n,time:i,clientTime:r}=e;return{From_Account:t,To_Account:s,MsgSeq:o,MsgRandom:n,MsgTime:i,MsgClientTime:r}})),i={Peer_Account:o,C2CMsgInfo:n};return t.buildAndSendPacket({servcmd:"openim.c2c_msg_read_receipt",data:i})}))}(o):yield function(e){return a(this,void 0,void 0,(function*(){const{common:t,constants:s}=wo.core,o={GroupId:e[0].conversationID.replace(s.OuterConstant.CONV_GROUP,""),MsgSeqList:e.map((e=>({MsgSeq:e.sequence})))};return t.buildAndSendPacket({servcmd:"group_open_http_svc.group_msg_receipt",data:o})}))}(o),{code:0,data:{}}}catch(e){const{errorCode:s,errorInfo:o}=e;throw new t.ChatError({code:s,message:o})}}))}getMessageReadReceiptList(e){return a(this,void 0,void 0,(function*(){const{common:t,constants:s}=this._core;try{const{conversationType:t}=e[0];if(t===s.OuterConstant.CONV_GROUP){const t=this._filterValidMessageSendByMe(e);if((null==t?void 0:t.length)>0){const s=yield function(e){return a(this,void 0,void 0,(function*(){const{common:t,constants:s}=wo.core,o={GroupId:e[0].conversationID.replace(s.OuterConstant.CONV_GROUP,""),MsgSeqList:e.map((e=>({MsgSeq:e.sequence})))};return t.buildAndSendPacket({servcmd:"group_open_http_svc.get_group_msg_receipt",data:o})}))}(t),{GroupMsgReceiptList:o}=s||{};this._updateGroupMessagesReadReceiptInfo({messageList:e,readReceiptList:o})}}return{code:0,data:{messageList:e}}}catch(e){const{errorCode:s,errorInfo:o}=e;throw new t.ChatError({code:s,message:o})}}))}getGroupMessageReadMemberList(e){return a(this,void 0,void 0,(function*(){const{constants:t,common:s}=this._core,{message:o,filter:n=Yo.READ,cursor:i=""}=e,{conversationID:r,sequence:c,ID:l}=o,u=r.replace(t.OuterConstant.CONV_GROUP,""),d=e.count>=100?100:e.count;try{const e=yield function(e){return a(this,void 0,void 0,(function*(){const{sequence:t,groupID:s,filter:o,cursor:n,count:i}=e,r={MsgSeq:t,GroupId:s,Filter:o,Cursor:n,Num:i};return wo.core.common.buildAndSendPacket({servcmd:"group_open_http_svc.get_group_msg_receipt_detail",data:r})}))}({groupID:u,sequence:c,filter:n,cursor:i,count:d});if(e){const{Cursor:t,IsFinish:s,UnreadList:o,ReadList:i}=e,r={cursor:t,isCompleted:1===s,messageID:l,unreadUserIDList:[],readUserIDList:[]};return n===Yo.READ?r.readUserIDList=i.map((e=>e.Read_Account)):n===Yo.UNREAD&&(r.unreadUserIDList=o.map((e=>e.Unread_Account))),{code:0,data:r}}}catch(e){const{errorCode:t,errorInfo:o}=e;throw new s.ChatError({code:t,message:o})}}))}_handleC2CMessageReadReceipt(e){const t=[],{constants:s,helper:o}=this._core,{C2cMsgInfo:n,PeerReadTime:i,Peer_Account:r}=e;if(o.isEmpty(n))return;const a=`${s.OuterConstant.CONV_C2C}${r}`;null==n||n.forEach((e=>{const{TinyId:s,MsgClientTime:o,MsgRandom:n}=e,c=`${s}-${o}-${n}`,l=on({conversationID:a,messageID:c});l&&!l.readReceiptInfo.isPeerRead&&(l.readReceiptInfo.isPeerRead=!0,l.readReceiptInfo.timestamp=i,t.push({userID:r,messageID:c,isPeerRead:!0,timestamp:i}))})),this._emitReadReceiptEventIfNeed(t)}_updateGroupMessagesReadReceiptInfo(e){const{messageList:t,readReceiptList:s}=e,o=new Map;t.forEach((e=>{o.set(e.sequence,e)})),null==s||s.forEach((e=>{if(0===e.Code){const{MsgSeq:t,ReadNum:s,UnreadNum:n}=e,i=o.get(t);i&&(i.readReceiptInfo.readCount=s,i.readReceiptInfo.unreadCount=n)}}))}_handleGroupMessageReadReceipt(e){const t=[],{constants:s}=this._core,{GroupTips:o}=e;o.forEach((e=>{const{MsgBody:{GroupMsgReceiptList:o},GroupInfo:{GroupId:n}}=e,i=`${s.OuterConstant.CONV_GROUP}${n}`;null==o||o.forEach((e=>{const{TinyId:s,MsgClientTime:o,MsgRandom:r,ReadNum:a,UnreadNum:c}=e,l=`${s}-${o}-${r}`,u=on({conversationID:i,messageID:l}),d={groupID:n,messageID:l,readCount:0,unreadCount:0};u&&("number"==typeof a&&(u.readReceiptInfo.readCount=a,d.readCount=a),"number"==typeof c&&(u.readReceiptInfo.unreadCount=c,d.unreadCount=c),t.push(d))}))})),this._emitReadReceiptEventIfNeed(t)}_emitReadReceiptEventIfNeed(e){const{notificationCenter:t,OuterEvent:s}=this._core;e.length>0&&t.emitOuterEvent(s.MESSAGE_READ_RECEIPT_RECEIVED,{name:s.MESSAGE_READ_RECEIPT_RECEIVED,data:e})}_filterValidMessageSendByOther(e){return this._filterNeedReadReceiptMessages(e).filter((e=>{const{from:t}=e;return t!==this._core.common.getCurrentUserID()}))}_filterValidMessageSendByMe(e){const{OuterConstant:t}=this._core.constants;return this._filterNeedReadReceiptMessages(e).filter((e=>{const{from:s,status:o}=e;return s===this._core.common.getCurrentUserID()&&o===t.MessageStatus.SUCCESS}))}_filterNeedReadReceiptMessages(e){return e.filter((e=>!0===e.needReadReceipt))}dispose(){const{InnerEvent:{MESSAGE_PUSH:e},InnerEventSubType:{C2C_MESSAGE_READ_RECEIPT:t,GROUP_MESSAGE_READ_RECEIPT:s},notificationCenter:o}=this._core;o.unSubscribeInnerEvent(e,t,this._handleC2CMessageReadReceipt,this),o.unSubscribeInnerEvent(e,s,this._handleGroupMessageReadReceipt,this)}};const ln=Object.assign(Object.assign({deleteMessage:[{required:!0,rules:["array"],allowEmpty:!1}],revokeMessage:[{required:!0,rules:["object"],allowEmpty:!1}],resendMessage:[{key:"message",required:!0,rules:["object"],allowEmpty:!1},{key:"options",required:!1,rules:["object"],allowEmpty:!1}],getMessageList:{conversationID:{required:!0,rules:["string"],allowEmpty:!1},nextReqMessageID:{required:!1,rules:["string"],allowEmpty:!0},count:{required:!1,rules:["number"],allowEmpty:!0}},getMessageListHopping:{conversationID:{required:!0,rules:["string"],allowEmpty:!1},sequence:{required:!1,rules:["number"],allowEmpty:!0},direction:{required:!1,rules:["number"],allowEmpty:!0},count:{required:!1,rules:["number"],allowEmpty:!0}},createTextAtMessage:{to:{required:!0,rules:["string"],allowEmpty:!1},conversationType:{required:!0,rules:["string"],allowEmpty:!1,customValidator:e=>"GROUP"===e||"conversationType should be GROUP."},payload:{required:!0,rules:["object"],allowEmpty:!1,customValidator:e=>{const t=function(e){var t;if("string"!=typeof(null==e?void 0:e.text)||"string"==typeof e.text&&0===(null===(t=null==e?void 0:e.text)||void 0===t?void 0:t.length))return"payload.text is invalid.";return!0}(e);return!0!==t?t:!((null==e?void 0:e.atUserList)&&!Array.isArray(e.atUserList))||"atUserList should be an array or undefind."}}},findMessage:[{required:!0,rules:["string"],allowEmpty:!1}],translateText:{sourceTextList:{required:!0,rules:["array"],allowEmpty:!1},sourceLanguage:{required:!0,rules:["string"],allowEmpty:!1},targetLanguage:{required:!0,rules:["string"],allowEmpty:!1}},createForwardMessage:{to:{required:!0,rules:["string"],allowEmpty:!1},conversationType:{required:!0,rules:["string"],allowEmpty:!1,customValidator:e=>!(!e.startsWith("C2C")&&!e.startsWith("GROUP"))||"conversationType is invalid."},payload:{required:!0,rules:["object"],allowEmpty:!1}},createLocationMessage:{to:{required:!0,rules:["string"],allowEmpty:!1},conversationType:{required:!0,rules:["string"],allowEmpty:!1},payload:{required:!0,rules:["object"],allowEmpty:!1,customValidator:e=>{const{utils:{isString:t,isNumber:s}}=wo.core;return t(null==e?void 0:e.description)?s(null==e?void 0:e.longitude)?!!s(null==e?void 0:e.latitude)||"payload.latitude must be a number.":"payload.longitude must be a number.":"payload.description must be a string."}}}},{addMessageReaction:[{key:"message",required:!0,rules:["object"],allowEmpty:!1},{key:"reactionID",required:!0,rules:["string"],allowEmpty:!1}],removeMessageReaction:[{key:"message",required:!0,rules:["object"],allowEmpty:!1},{key:"reactionID",required:!0,rules:["string"],allowEmpty:!1}],getMessageReactions:{messageList:{required:!0,rules:["array"],allowEmpty:!1},maxUserCountPerReaction:{required:!1,rules:["number"],allowEmpty:!0,customValidator:e=>"number"!=typeof e?"maxUserCountPerReaction is invalid.":!(e<0||e>10)||"maxUserCountPerReaction should between [0, 10]."}},getAllUserListOfMessageReaction:{message:{required:!0,rules:["object"],allowEmpty:!1,customValidator:e=>"success"===e.status||"message is invalid."},reactionID:{required:!0,rules:["string"],allowEmpty:!1},nextSeq:{required:!1,rules:["number"],allowEmpty:!0},count:{required:!1,rules:["number"],allowEmpty:!0}}}),{sendMessageReadReceipt:[{required:!0,rules:["array"],allowEmpty:!1}],getMessageReadReceiptList:[{required:!0,rules:["array"],allowEmpty:!1}],getGroupMessageReadMemberList:{message:{required:!0,rules:["object"],allowEmpty:!1},filter:{required:!1,rules:["number"],allowEmpty:!0},count:{required:!1,rules:["number"],allowEmpty:!0},cursor:{required:!1,rules:["string"],allowEmpty:!0}}}),un=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});class dn{constructor(e){this._core=e}deleteMessage(e){return a(this,void 0,void 0,(function*(){const{to:t,messageIdentifiers:s}=e,o="openim.delete_c2c_msg_ramble",n={From_Account:this._core.common.getCurrentUserID(),To_Account:t,MsgKeyList:s},i=this._core.helper.generateProtocolData({servcmd:o,data:n}),r=`${i.head.seq}${o}`;return this._core.channel.sendPacket(i,{requestId:r})}))}revokeMessage(e){return a(this,void 0,void 0,(function*(){const{to:t,from:s,sequence:o,time:n,random:i}=e,r="openim.msgwithdraw",a={MsgInfo:{From_Account:s,To_Account:t,MsgSeq:o,MsgRandom:i,MsgTimeStamp:n}},c=this._core.helper.generateProtocolData({servcmd:r,data:a}),l=`${c.head.seq}${r}`;return this._core.channel.sendPacket(c,{requestId:l})}))}}class hn{constructor(e){this._core=e}deleteMessage(e){return a(this,void 0,void 0,(function*(){const{to:t,messageIdentifiers:s}=e,o="group_open_http_svc.delete_group_ramble_msg_by_seq",n={GroupId:t,Deleter_Account:this._core.common.getCurrentUserID(),Seqs:s},i=this._core.helper.generateProtocolData({servcmd:o,data:n}),r=`${i.head.seq}${o}`;return this._core.channel.sendPacket(i,{requestId:r})}))}revokeMessage(e){return a(this,void 0,void 0,(function*(){const{to:t,sequence:s}=e,o="group_open_http_svc.group_msg_recall",n={GroupId:t,MsgSeqList:[{MsgSeq:s}]},i=this._core.helper.generateProtocolData({servcmd:o,data:n}),r=`${i.head.seq}${o}`;return this._core.channel.sendPacket(i,{requestId:r})}))}}class pn{constructor(e){this._core=e}generateRevokeMessage(e){const{conversationID:t,sequence:s,random:o,tinyID:n,clientTime:i,revokeReason:r,revoker:a}=e;let c={};const{messageDataHandler:l}=this._core.message;return c=l.revokeMessage({conversationID:t,sequence:s,random:o,revoker:a}),c||(c={conversationID:t,sequence:s},n&&i&&o&&(c.ID=`${n}-${i}-${o}`)),c=Object.assign(Object.assign({},c),{revoker:a,revokeReason:r,revokerInfo:{userID:a,nick:"",avatar:""}}),c}updateRevokerInfo(e){return a(this,void 0,void 0,(function*(){const t=e.map((e=>e.revoker));try{const s=yield this._fetchUserInfos(t);s&&e.forEach((e=>{const{revoker:t}=e;s[t]&&(e.revokerInfo.nick=s[t].nick||"",e.revokerInfo.avatar=s[t].avatar||"",e.revokerInfo.userID=t)}))}catch(e){console.debug(e)}}))}filterValidMessages(e){return e.filter((e=>{const t=!this._core.helper.isEmpty(null==e?void 0:e.getElements()),s=1===(null==e?void 0:e.isPlaceMessage);if(!t){this._core.ssoLog.createSSOLogData({method:"emptyMessageBody"}).setLogInfo({message:`from:${e.from} to:${e.to} sequence:${e.sequence}`}).end()}return t&&!s}))}_fetchUserInfos(e){return a(this,void 0,void 0,(function*(){var t,s;const o=yield null===(t=this._core.user.userProfile)||void 0===t?void 0:t.getUserProfile({userIDList:e});return(null==o?void 0:o.data)?null===(s=o.data)||void 0===s?void 0:s.reduce(((e,{userID:t,nick:s,avatar:o})=>(e[t]={nick:s||"",avatar:o||""},e)),{}):null}))}}var gn=new class{constructor(){this._core=null,this._c2cMessageAction=null,this._groupMessageAction=null}init(e){this._core=e,this._groupMessageAction=new hn(e),this._c2cMessageAction=new dn(e),this._messageHelper=new pn(e);const{helper:t}=e;t.registerApi({apiName:"deleteMessage",context:this}),t.registerApi({apiName:"revokeMessage",context:this}),t.registerApi({apiName:"resendMessage",context:this}),t.registerApi({apiName:"findMessage",context:this})}deleteMessage(e){return a(this,void 0,void 0,(function*(){let t=[],s=[];const{conversationID:o,conversationType:n}=e[0],i=o.replace(n,"");if("@TIM#SYSTEM"===n)throw new this._core.helper.ChatError({code:zo});if(e.forEach((e=>{const{conversationID:i,conversationType:r,status:a,_onlineOnlyFlag:c,sequence:l,random:u,time:d}=e||{};if("success"===a&&i===o&&r===n){if(!c){const e="C2C"===r?`${l}_${u}_${d}`:String(l);t.push(e)}s.push(e)}})),0===t.length)return this._handleDeleteMessageSuccess(s),{code:0,data:{messageList:s}};t.length>30&&(t=t.slice(0,30),s=s.slice(0,30));try{return"C2C"===n?yield this._c2cMessageAction.deleteMessage({to:i,messageIdentifiers:t}):yield this._groupMessageAction.deleteMessage({to:i,messageIdentifiers:t}),this._handleDeleteMessageSuccess(s),{code:0,data:{messageList:s}}}catch(e){const{errorCode:t}=e;throw new this._core.helper.ChatError({functionName:"deleteMessage",code:t})}}))}revokeMessage(e){return a(this,void 0,void 0,(function*(){var t;const s=this._core.ssoLog.createSSOLogData({method:"revokeMessage"}),{conversationType:o,isRevoked:n}=e;let i=null;if("@TIM#SYSTEM"===o)throw new this._core.helper.ChatError({message:"system message cannot be revoked"});if(n)throw new this._core.helper.ChatError({message:"message has been revoked"});s.setLogInfo({message:`type:${e.type} from:${e.from} to:${e.to}`});try{if(i="C2C"===o?yield this._c2cMessageAction.revokeMessage(e):yield this._groupMessageAction.revokeMessage(e),i){const{RecallRetList:o}=i,n=(null===(t=null==o?void 0:o[0])||void 0===t?void 0:t.RetCode)||0;if(0!==n)throw new this._core.helper.ChatError({code:n});return s.end(),yield this._handleRevokeMessageSuccess(e),{code:0,data:{message:e}}}}catch(e){const{errorCode:t}=e,s=new this._core.helper.ChatError({functionName:"revokeMessage",code:t});throw this._core.ssoLog.getSSOLogData("revokeMessage").setError(s).end(),s}}))}resendMessage(e,t){return a(this,void 0,void 0,(function*(){var s,o;return e.isResend=!0,e.status="unSend",null===(o=null===(s=this._core)||void 0===s?void 0:s.apiMap)||void 0===o?void 0:o.sendMessage(e,t)}))}findMessage(e){return this._core.message.messageDataHandler.findMessage(e)}_handleDeleteMessageSuccess(e){0!==e.length&&(e.forEach((e=>{e.isDeleted=!0;const t=this._core.message.messageDataHandler.getLocalMessageList(e.conversationID);null==t||t.forEach((t=>{t.ID===e.ID&&(t.isDeleted=!0)}))})),this._core.notificationCenter.emitInnerEvent(this._core.InnerEvent.MESSAGE_DELETED,e[0].conversationID))}_handleRevokeMessageSuccess(e){return a(this,void 0,void 0,(function*(){var t;const s=null===(t=this._core.store.get("login"))||void 0===t?void 0:t.userId,{conversationID:o,sequence:n,random:i}=e;this._core.message.messageDataHandler.revokeMessage({conversationID:o,sequence:n,random:i,revoker:s}),yield this._messageHelper.updateRevokerInfo([e])}))}};class _n{static parseServerPushElement(e){const{MsgContent:t={}}=e,{Index:s,Data:o}=t;return new _n({index:s,data:o})}constructor(e){this.type=Po.MSG_FACE;const{index:t,data:s}=e;this.content={index:t,data:s}}validateBeforeSend(){var e,t;return"number"==typeof(null===(e=this.content)||void 0===e?void 0:e.index)&&"string"==typeof(null===(t=this.content)||void 0===t?void 0:t.data)?{isValid:!0}:{isValid:!1,error:{message:"content is invalid"}}}transformToServerFormat(e){const{isMergerMessage:t=!1}=e||{},s=t?this.payload:this.content,{index:o,data:n}=s;return{MsgType:this.type,MsgContent:{Index:o,Data:n}}}}class mn{static parseServerPushElement(e){const{MsgContent:t={}}=e,{Desc:s,Longitude:o,Latitude:n}=t;return new mn({description:s,longitude:o,latitude:n})}constructor(e){this.type=Po.MSG_LOCATION;const{description:t,longitude:s,latitude:o}=e;this.content={description:t,longitude:s,latitude:o}}validateBeforeSend(){return{isValid:!0}}transformToServerFormat(e){const{isMergerMessage:t=!1}=e||{},s=t?this.payload:this.content,{description:o,longitude:n,latitude:i}=s;return{MsgType:this.type,MsgContent:{Desc:o,Longitude:n,Latitude:i}}}}var fn=new class{init(e){this._core=e,e.message.messageFactory.registerElementClass(Po.MSG_FACE,_n),e.message.messageFactory.registerElementClass(Po.MSG_LOCATION,mn),e.helper.registerApi({apiName:"createFaceMessage",context:this}),e.helper.registerApi({apiName:"createTextAtMessage",context:this}),e.helper.registerApi({apiName:"createForwardMessage",context:this}),e.helper.registerApi({apiName:"createLocationMessage",context:this})}createFaceMessage(e){if(!e)return null;const{index:t,data:s}=(null==e?void 0:e.payload)||{},o=new _n({index:t,data:s}),n=this._core.common.getCurrentUserID(),i=this._core.message.messageFactory.createMessage(Object.assign(Object.assign({},e),{from:n}));return i.setElement(o),i}createTextAtMessage(e){const{atUserList:t}=(null==e?void 0:e.payload)||{},s=this._core.apiMap.createTextMessage(e),{OuterConstant:o}=this._core;if(!s)return null;if(Array.isArray(t)){const e=[],n=[];t.forEach((t=>{t!==o.MSG_AT_ALL?(e.push({GroupAtAllFlag:Fo,GroupAt_Account:t}),n.push(t)):(e.push({GroupAtAllFlag:$o}),n.push(o.MSG_AT_ALL))})),s._groupAtInfoList=e,s.atUserList=n}return s}createForwardMessage(e){const{helper:t,OuterConstant:s}=this._core,{to:o,conversationType:n,priority:i,payload:r,needReadReceipt:a,receiverList:c,cloudCustomData:l="",isSupportExtension:u=!1}=e;if(!Array.isArray(r._elements))throw new t.ChatError({functionName:"createForwardMessage",code:2454});if(r.type===s.MSG_GRP_TIP)throw new t.ChatError({functionName:"createForwardMessage",code:2453});const d=this._core.common.getCurrentUserID(),h=this._core.message.messageFactory.createMessage({to:o,from:d,conversationType:n,isPlaceMessage:0,priority:i,payload:r,needReadReceipt:a,isSupportExtension:u,cloudCustomData:l,receiverList:c});return h.setRelayFlag(!0),h.setElement(r._elements[0]),h}createLocationMessage(e){if(!e)return null;const{description:t,longitude:s,latitude:o}=(null==e?void 0:e.payload)||{},n=new mn({description:t,longitude:s,latitude:o}),i=this._core.common.getCurrentUserID(),r=this._core.message.messageFactory.createMessage(Object.assign(Object.assign({},e),{from:i}));return r.setElement(n),r}};let vn=class{init(e){this._messageHelper=new pn(e),this._core=e;const{notificationCenter:t,InnerEvent:{MESSAGE_PUSH:s},InnerEventSubType:{C2C_REVOKED_MESSAGE:o},helper:{registerWorkflowStep:n},constants:{WORKFLOW_NAME:i,WORKFLOW_STEP:r}}=e;t.subscribeInnerEvent(s,o,this._handleC2CNotifyMessage,this),n(i.SYNC_SERVER_INFO_AFTER_RE_ONLINE,r.HANDLE_C2C_REVOKED_MESSAGE_FROM_SYNC_UNREAD,this._handleC2CRevokeMessagesFromUnreadMessageSync,this)}_handleC2CNotifyMessage(e){const{C2cNotifyMsgArray:t}=e;null==t||t.forEach((e=>{Object.keys(e).includes("WithdrawC2cMsgNotify")&&this._handleC2CRevokeMessage(e)}))}_handleC2CRevokeMessage(e){return a(this,void 0,void 0,(function*(){try{const{WithdrawC2cMsgNotify:{C2cWithdrawInfoArray:t}}=e;yield this._parseAndEmitC2CRevokedMessages(t)}catch(e){console.debug(e)}}))}_parseAndEmitC2CRevokedMessages(e){return a(this,void 0,void 0,(function*(){const t=[],{notificationCenter:s,OuterEvent:o,common:{getCurrentUserID:n}}=this._core;e.forEach((e=>{const{MsgRand:s,MsgSeq:o,To_Account:i,From_Account:r,RevokerInfo:{Revoker_Account:a,Revoke_Reason:c,Reason:l=c}}=e,u=n()===r?`C2C${i}`:`C2C${r}`,d=this._messageHelper.generateRevokeMessage({conversationID:u,sequence:o,random:s,revoker:a,revokeReason:l});t.push(d)})),t.length>0&&(yield this._messageHelper.updateRevokerInfo(t),s.emitOuterEvent(o.MESSAGE_REVOKED,{name:o.MESSAGE_REVOKED,data:t}))}))}_handleC2CRevokeMessagesFromUnreadMessageSync(e){return a(this,void 0,void 0,(function*(){const{revokedMessageList:t}=e.result;yield this._parseAndEmitC2CRevokedMessages(t)}))}dispose(){const{notificationCenter:e,InnerEvent:{MESSAGE_PUSH:t},InnerEventSubType:{C2C_REVOKED_MESSAGE:s}}=this._core;e.unSubscribeInnerEvent(t,s,this._handleC2CNotifyMessage,this)}},In=class{init(e){this._messageHelper=new pn(e),this._core=e;const{notificationCenter:t,InnerEvent:{MESSAGE_PUSH:s},InnerEventSubType:{GROUP_MESSAGE_REVOKED:o}}=e;t.subscribeInnerEvent(s,o,this._handleGroupNotifyMessage,this)}_handleGroupNotifyMessage(e){const{GroupTips:t}=e;null==t||t.forEach((e=>{var t;Array.isArray(null===(t=null==e?void 0:e.MsgBody)||void 0===t?void 0:t.GroupWithdrawInfoArray)&&this._handleGroupRevokeMessage(e)}))}_handleGroupRevokeMessage(e){return a(this,void 0,void 0,(function*(){try{const{RevokerInfo:t,MsgBody:{GroupWithdrawInfoArray:s}}=e,o=[],{notificationCenter:n,OuterEvent:i,InnerEvent:r}=this._core;s.forEach((e=>{const{Random:s,MsgSeq:n,GroupId:i,MsgClientTime:r,TinyId:a,TopicId:c,RevokerInfo:{Revoker_Account:l=(null==t?void 0:t.Revoker_Account)||"",Reason:u=(null==t?void 0:t.Reason)||""}}=e,d=c?`GROUP${c}`:`GROUP${i}`,h=this._messageHelper.generateRevokeMessage({conversationID:d,sequence:n,random:s,tinyID:a,clientTime:r,revoker:l,revokeReason:u});o.push(h)})),0!==o.length&&(yield this._messageHelper.updateRevokerInfo(o),n.emitOuterEvent(i.MESSAGE_REVOKED,{name:i.MESSAGE_REVOKED,data:o}))}catch(e){console.debug(e)}}))}dispose(){const{notificationCenter:e,InnerEvent:{MESSAGE_PUSH:t},InnerEventSubType:{GROUP_MESSAGE_REVOKED:s}}=this._core;e.unSubscribeInnerEvent(t,s,this._handleGroupNotifyMessage,this)}};var Sn=new class{constructor(){this._c2cMessageReceiver=new vn,this._groupMessageReceiver=new In}init(e){this._c2cMessageReceiver.init(e),this._groupMessageReceiver.init(e)}dispose(){this._c2cMessageReceiver.dispose(),this._groupMessageReceiver.dispose()}};class En{constructor(e){this._lastMessageSequenceMapOnDisconnect=new Map,this._core=e,this._messageHelper=new pn(e)}getRoamingMessagesByAnchor(e){return a(this,void 0,void 0,(function*(){try{const t=this._core.ssoLog.createSSOLogData({method:"getRoamingMessagesByAnchor"}),{conversationID:s,count:o,direction:n,sequence:i}=e,r=s.replace(Zo,"");let a=i;if(n===Go.BACKWARD){if("number"!=typeof i)return{messageList:[],hasNoMoreHistoryMessage:!1,nextReqMessageIDFromServer:""};a=i+o-1}const c={GroupId:r,ReqMsgNumber:o,WithRecalledMsg:1,Version:1};a&&(c.ReqMsgSeq=a);const l="group_open_http_svc.group_msg_get",u=this._core.helper.generateProtocolData({servcmd:l,data:c}),d=`${u.head.seq}${l}`,h=yield this._core.channel.sendPacket(u,{requestId:d});if(h){const{RspMsgList:e=[],NextReqMsgSeq:s=0,IsFinished:o,InvisibleMsgSeq:c}=h;t.setLogInfo({message:`groupID:${r} sequence:${i} reqSeq:${a} direction:${n}\n complete:${o} nextSequence:${s} remoteMsgCount:${e.length} invisibleSequenceList:${c}`}).end();const l=[];for(let t=0;t<e.length;t++){const s=e[t],o=this._parseMessage(s);l.push(o)}l.reverse();const u=[Uo.NO_MORE_DATA,Uo.DATA_HAS_EXPIRED].includes(o);return{messageList:this._messageHelper.filterValidMessages(l),invisibleSequenceList:c,nextReqMessageIDFromServer:s,hasNoMoreHistoryMessage:u}}}catch(e){const t=new this._core.helper.ChatError({code:null==e?void 0:e.code});this._core.ssoLog.getSSOLogData("getRoamingMessagesByAnchor").setError(t).end()}}))}recoverHistoryMessage(e){return a(this,void 0,void 0,(function*(){const{message:{messageReceiver:t,messageDataHandler:s},notificationCenter:o,OuterEvent:n,constants:{OuterConstant:i}}=this._core,r=[];null==e||e.forEach((e=>a(this,void 0,void 0,(function*(){const{conversationID:a,lastMessage:c}=e;let l=this._getLocalLastMessageSequence(a);const u=c.lastSequence;if(this._shouldRecoverHistory({localLastMessageSequence:l,serverLastMessageSequence:u})){const e=u-l;let i=!1;const r=Math.ceil(e/20);for(let e=0;e<r;e++)try{const e=u-l,r=Math.min(20,e),c=yield this.getRoamingMessagesByAnchor({conversationID:a,sequence:l+r,direction:Go.FORWARD,count:r}),{nextReqMessageIDFromServer:d,hasNoMoreHistoryMessage:h,messageList:p}=c;i=h&&d<0,l=p[p.length-1].sequence;const g=[];if(Array.isArray(p)&&(p.forEach((e=>{t.groupMessageReceiver.updateMessageProfile(e);s.storeConversationMessage(e)&&g.push(e)})),g.length>0&&o.emitOuterEvent(n.MESSAGE_RECEIVED,{name:n.MESSAGE_RECEIVED,data:g})),i)break}catch(e){console.debug(e);break}}else r.push(a.replace(i.CONV_GROUP,""))})))),this._recoverGroupRevokeNotice(r)}))}updateLastMessageSequenceMapOnDisconnect(){const e=this._core.message.messageDataHandler.getContinuousMessagesByConversation();for(const[t,s]of e){if(t.startsWith("C2C"))continue;const e=Array.from(s.values());if((null==e?void 0:e.length)>0){const s=e[e.length-1].sequence;this._lastMessageSequenceMapOnDisconnect.set(t,s)}}}_shouldRecoverHistory(e){const{localLastMessageSequence:t,serverLastMessageSequence:s}=e;if("number"!=typeof t||"number"!=typeof s)return!1;const o=s-t;return 0!==s&&t&&(o>=Qo&&o<en)}_getLocalLastMessageSequence(e){if(this._lastMessageSequenceMapOnDisconnect.has(e))return this._lastMessageSequenceMapOnDisconnect.get(e);const t=this._core.message.messageDataHandler.getLocalMessageList(e),s=t[t.length-1];return null==s?void 0:s.sequence}_parseMessage(e){const{constants:{OuterConstant:t}}=this._core,s=Zo;4===e.Event&&(e.MsgBody.MsgType=t.MSG_GRP_TIP);const o=this._core.message.messageHelper.parseServerGroupMessage(e),n=this._core.message.messageFactory.createMessage(Object.assign(Object.assign({},o),{conversationType:s,flow:"in"}));return n.setElement(o.elements),n}_recoverGroupRevokeNotice(e){const t=this._filterValidGroupIDList(e);if(0===t.length)return;const s=Math.min(Math.ceil(t.length/10),5);Promise.all(Array.from({length:s},((e,s)=>{const o=10*s,n=Math.min(o+10,t.length);return this._fetchGroupRevokeNotice(t.slice(o,n))}))).catch((e=>console.error(e)))}_fetchGroupRevokeNotice(e){return a(this,void 0,void 0,(function*(){var t;try{const s=yield function(e){return a(this,void 0,void 0,(function*(){const{appStore:t,constants:{OuterConstant:s},common:o}=wo.core,n=t.groupStore.getGroupMap(),i=e.map((e=>{const t=n.get(e);return{NotifyType:1,Limit:20,Type:o.isCommunity({type:t.type,groupID:e})?s.GRP_COMMUNITY:void 0,GroupId:e,BeginTime:(null==t?void 0:t._lastRevokedTime)||0,EndTime:1e3*wo.core.common.timeManager.getServerTimeMs()}}))||[],r={NotifyReqList:i};return o.buildAndSendPacket({servcmd:"group_open_http_svc.batch_get_group_notify",data:r})}))}(e);if(s){const e=[];null===(t=null==s?void 0:s.NotifyRspList)||void 0===t||t.forEach((t=>{const{GroupId:s,NotifyMsgList:o}=t,n=this._parseServerRevokeMessageList({groupID:s,serverRevokeMessageList:o});e.push(...n)})),0!==e.length&&(yield this._emitMessageRevokedEvent(e))}}catch(e){console.error(e)}}))}_parseServerRevokeMessageList(e){const{serverRevokeMessageList:t,groupID:s}=e,o=[];return null==t||t.forEach((e=>{const{ClientTime:t,MsgSeq:n,Random:i,RevokerInfo:{Revoker_Account:r="",Reason:a=""}}=e,c=`GROUP${s}`,l=this._messageHelper.generateRevokeMessage({conversationID:c,sequence:n,random:i,clientTime:t,revoker:r,revokeReason:a});o.push(l)})),o}_filterValidGroupIDList(e){const{constants:{OuterConstant:t}}=this._core,s=this._core.appStore.groupStore.getGroupMap();return(null==e?void 0:e.filter((e=>{if(!s.has(e))return!1;const o=s.get(e);return(null==o?void 0:o.type)!==t.GRP_AVCHATROOM&&!(null==o?void 0:o.isSupportTopic)})))||[]}_emitMessageRevokedEvent(e){return a(this,void 0,void 0,(function*(){const{notificationCenter:t,OuterEvent:s}=this._core;yield this._messageHelper.updateRevokerInfo(e),t.emitOuterEvent(s.MESSAGE_REVOKED,{name:s.MESSAGE_REVOKED,data:e})}))}}class Cn{constructor(e){this._historyMessageListFetchAnchors=new Map,this._core=e,this._messageHelper=new pn(e)}getRoamingMessagesByAnchor(e){return a(this,void 0,void 0,(function*(){var t;try{const{conversationID:s,count:o,messageID:n,time:i,direction:r}=e;let c=i,l="";if(!i){const e=n?this._core.message.messageDataHandler.findMessage(n):null;if(c=(null==e?void 0:e.time)||0,n&&this._historyMessageListFetchAnchors.has(s)){const e=this._historyMessageListFetchAnchors.get(s);c=e.lastMessageTime,l=e.messageKey}}const u=s.replace(Jo,""),d=yield function(e){return a(this,void 0,void 0,(function*(){const{peerAccount:t,count:s,lastMessageTime:o,messageKey:n,direction:i}=e,r={Peer_Account:t,MaxCnt:s,WithRecalledMsg:1,LastMsgTime:o,MsgKey:n,GetDirection:i};return wo.core.common.buildAndSendPacket({servcmd:"openim.getroammsg",data:r})}))}({count:o,lastMessageTime:c,messageKey:l,peerAccount:u,direction:r});if(d){const{MsgList:e=[],Complete:o,MsgKey:n,LastMsgTime:i}=d;this._historyMessageListFetchAnchors.set(s,{messageKey:n,lastMessageTime:i});const r=[];for(let t=0;t<e.length;t++){const s=e[t],o=this._parseMessage(s);r.push(o)}const a=this._messageHelper.filterValidMessages(r);return{messageList:a,nextReqMessageIDFromServer:null===(t=a[0])||void 0===t?void 0:t.ID,lastMessageTime:i,hasNoMoreHistoryMessage:1===o}}}catch(e){throw new this._core.helper.ChatError({code:null==e?void 0:e.code})}}))}_parseMessage(e){const t=Jo,s=this._core.message.messageHelper.parseServerPushMessage(e),o=this._core.message.messageFactory.createMessage(Object.assign(Object.assign({},s),{conversationType:t,flow:"in"}));return o.setElement(s.elements),o}}var yn=new class{constructor(){this._clearedConversations=new Set,this._fetchedCompleteConversations=new Set}init(e){this._core=e,this._groupMessageHistory=new En(e),this._c2cMessageHistory=new Cn(e),this._messageHelper=new pn(e);const{InnerEvent:t,notificationCenter:s,constants:o}=e;e.helper.registerApi({apiName:"getMessageList",context:this}),e.helper.registerApi({apiName:"getMessageListHopping",context:this}),e.helper.registerWorkflowStep(o.WORKFLOW_NAME.SYNC_SERVER_INFO_AFTER_RE_ONLINE,o.WORKFLOW_STEP.HISTORY_MESSAGE_RECOVER,this._recoverHistoryMessage,this),s.subscribeInnerEvent(t.SOCKET_DISCONNECTED,this._handleSocketDisconnected,this)}getMessageList(e){return a(this,void 0,void 0,(function*(){try{const t=this._core.ssoLog.createSSOLogData({method:"getMessageList"});let{conversationID:s,nextReqMessageID:o}=e;const n=Xo;if("@TIM#SYSTEM"===s)return{code:0,data:{messageList:[],isCompleted:!1,nextMessageSeq:""}};const i=this._getAvailableLocalMessagesCount({conversationID:s,nextReqMessageID:o});if(this._needFetchHistoryMessageList({conversationID:s,availableLocalMessagesCount:i,targetCount:n})){let e=null;if(s.startsWith(Zo)?e=yield this._groupMessageHistory.getRoamingMessagesByAnchor({conversationID:s,sequence:Number(o),count:n,direction:Go.FORWARD}):s.startsWith(Jo)&&(e=yield this._c2cMessageHistory.getRoamingMessagesByAnchor({conversationID:s,messageID:o,count:n,direction:Go.FORWARD})),e){const{nextReqMessageIDFromServer:n,hasNoMoreHistoryMessage:r,messageList:a}=e,c=this._core.message.messageDataHandler.prependLocalMessageList({messageList:a,conversationID:s});!function(e){const{appStore:t,message:s,OuterConstant:o}=wo.core,n=t.conversationStore.getConversation(e),i=s.messageDataHandler.getLocalMessageList(e);if(!n||0===i.length||e===o.CONV_SYSTEM)return;const r=[];for(let e=0;e<i.length;e++)"in"!==i[e].flow?"out"!==i[e].flow||i[e].isRead||i[e].setIsRead(!0):r.push(i[e]);let a=0;if(n.type===o.CONV_C2C){const e=r.slice(-n.unreadCount).filter((e=>e.isRevoked)).length;a=r.length-n.unreadCount-e}else a=r.length-n.unreadCount;for(let e=0;e<a&&!r[e].isRead;e++)r[e].setIsRead(!0)}(s),yield sn(s),s.startsWith(Jo)&&(yield tn({messageList:a,conversationID:s}));const l=this._core.message.messageDataHandler.getLocalMessageList(s).slice(0,c.length+i),u=l.filter((e=>e.isRevoked));yield this._messageHelper.updateRevokerInfo(u);const d={nextReqMessageID:r?"":String(n),messageList:l,isCompleted:r},h=l.map((e=>e.sequence));return t.setLogInfo({message:`conversationID: ${s} nextReqMessageID: ${o} \n availableLocalMessagesCount: ${i} sequenceList: ${JSON.stringify(h)} `}).end(),{code:0,data:d}}return{code:0,data:{messageList:[],isCompleted:!1,nextMessageSeq:""}}}t.setLogInfo({message:`conversationID: ${s} nextReqMessageID: ${o} availableLocalMessagesCount: ${i}}`}).end();return{code:0,data:yield this._getMessageListFromMemory({conversationID:s,nextReqMessageID:o,count:n})}}catch(e){const t=new this._core.helper.ChatError({code:null==e?void 0:e.code});this._core.ssoLog.getSSOLogData("getMessageList").setError(t).end(),console.debug(t)}}))}getMessageListHopping(e){return a(this,void 0,void 0,(function*(){var t,s;const{conversationID:o,sequence:n,time:i,direction:r=Go.FORWARD}=e,{isEmpty:a}=this._core.helper;if(![Go.BACKWARD,Go.FORWARD].includes(r))throw new this._core.helper.ChatError({message:"direction must be 0 or 1"});let{count:c=Xo}=e;c=c>Xo?Xo:c;let l=null;if(o.startsWith(Zo)){if(l=yield this._groupMessageHistory.getRoamingMessagesByAnchor({conversationID:o,sequence:n,count:c,direction:r}),l){const{nextReqMessageIDFromServer:e,hasNoMoreHistoryMessage:o,messageList:i,invisibleSequenceList:c}=l;if(this._core.message.messageDataHandler.storeSparseMessageList(i),r===Go.FORWARD){const t=o&&e<1;return{code:0,data:{messageList:i,isCompleted:t,nextMessageSeq:t?"":e}}}if(r===Go.BACKWARD){if(a(i)&&a(c))return{code:0,data:{messageList:[],isCompleted:!0,nextMessageSeq:""}};const e=(null===(t=null==i?void 0:i[i.length-1])||void 0===t?void 0:t.sequence)||0,o=(null===(s=null==c?void 0:c[c.length-1])||void 0===s?void 0:s.sequence)||0;return{code:0,data:{messageList:i.filter((e=>e.sequence>=n)),isCompleted:!1,nextMessageSeq:Math.max(e,o)+1}}}return{code:0,data:l}}}else if(o.startsWith(Jo)&&(l=yield this._c2cMessageHistory.getRoamingMessagesByAnchor({conversationID:o,count:c+1,time:i,direction:r}),l)){const{messageList:e,lastMessageTime:t,hasNoMoreHistoryMessage:s}=l;return s||(r===Go.FORWARD?e.shift():e.pop()),this._core.message.messageDataHandler.storeSparseMessageList(e),{code:0,data:{messageList:e,isCompleted:s,nextMessageTime:s?"":t}}}}))}_getAvailableLocalMessagesCount({conversationID:e,nextReqMessageID:t}){const s=this._core.message.messageDataHandler.getLocalMessageList(e),{length:o}=s;if(!t)return o;let n=-1;return(null==e?void 0:e.startsWith(Jo))?n=s.findIndex((e=>e.ID===t)):(null==e?void 0:e.startsWith(Zo))&&(n=s.findIndex((e=>t.includes("-")?e.ID===t:String(e.sequence)===t))),-1===n?0:n}_needFetchHistoryMessageList({conversationID:e,availableLocalMessagesCount:t,targetCount:s}){return!!this._clearedConversations.has(e)||t<=s&&!this._fetchedCompleteConversations.has(e)}_getMessageListFromMemory(e){return a(this,arguments,void 0,(function*({conversationID:e,nextReqMessageID:t,count:s}){const o=this._core.message.messageDataHandler.getLocalMessageList(e),n=o.length;let i=n,r={isCompleted:!1,nextReqMessageID:"",messageList:[]},a=0,c=n;return t?t&&(c=o.findIndex((s=>e.startsWith(Jo)?s.ID===t:String(s.sequence)===t)),a=c>s?c-s:0,i=c):a=n>s?n-s:0,r.nextReqMessageID=0===a?"":this._generateNextReqMessageID({conversationID:e,targetIndex:a}),r.messageList=o.slice(a,c),r.isCompleted=i<=s,e.startsWith(Jo)&&(yield sn(e),yield tn({messageList:r.messageList,conversationID:e})),r}))}_generateNextReqMessageID({conversationID:e,targetIndex:t}){const s=this._core.message.messageDataHandler.getLocalMessageList(e);return e.startsWith("C2C")?s[t].ID:String(s[t].sequence)}_recoverHistoryMessage(){const{appStore:e,constants:{OuterConstant:{GRP_AVCHATROOM:t}}}=this._core,s=e.conversationStore.getConversationMap()||{};if(s instanceof Map){const e=[...s.values()].filter((e=>e.type===Zo&&e.groupProfile.type!==t));this._groupMessageHistory.recoverHistoryMessage(e)}}_handleSocketDisconnected(){this._groupMessageHistory.updateLastMessageSequenceMapOnDisconnect()}dispose(){const{notificationCenter:e,InnerEvent:t}=this._core;e.unSubscribeInnerEvent(t.SOCKET_DISCONNECTED,this._handleSocketDisconnected,this)}};var Mn=new class{constructor(){this._core=null}init(e){this._core=e;const{helper:t}=e;t.registerApi({apiName:"translateText",context:this})}translateText(e){return a(this,void 0,void 0,(function*(){try{const{sourceLanguage:t,sourceTextList:s,targetLanguage:o}=e,n=yield function(e,t){return a(this,void 0,void 0,(function*(){var s,o;const{sourceTextList:n,sourceLanguage:i,targetLanguage:r}=e,{store:a,helper:c,channel:l}=t,u="im_open_translate.ws_batch_trans_text",d={SourceText:n,Source:i,Target:r,FromAccount:null===(s=a.get("login"))||void 0===s?void 0:s.tinyID,SDKAppID:null===(o=a.get("instance"))||void 0===o?void 0:o.sdkAppId},h=c.generateProtocolData({servcmd:u,data:d}),p=`${h.head.seq}${u}`,g=yield l.sendPacket(h,{requestId:p});if(g){const{CmdErrorCode:e,TargetText:t}=g;return{cmdErrorCode:e,translatedTextList:t}}}))}({sourceLanguage:t,sourceTextList:s,targetLanguage:o},this._core);if(n){const{cmdErrorCode:{ErrorCode:e,ErrorInfo:t},translatedTextList:s}=n;if(0===e)return{code:0,data:{translatedTextList:s}};throw{errorCode:e,errorInfo:t,message:t}}}catch(e){const{errorCode:t,errorInfo:s}=e||{};throw new this._core.helper.ChatError({functionName:"translateText",code:t,message:s})}}))}};var An=new class{init(e){this._core=e,e.common.registerApi({apiName:"convertVoiceToText",context:this})}convertVoiceToText(e){return a(this,void 0,void 0,(function*(){var t,s;const{message:o,language:n=qo.ZH_PY}=e;let{url:i}=o.payload||{};const r=null===(t=this._core.store.get("login"))||void 0===t?void 0:t.userID;o.from===r&&"out"===o.flow&&(i=o.payload.remoteAudioUrl),this._validateVoiceFormat(i);const a=(null===(s=Ho.exec(i))||void 0===s?void 0:s[1])||"mp3",c=Ko[n]||Wo;try{const e=yield function(e){var t;const{store:s,common:o}=wo.core,{url:n,format:i,serverLanguageType:r}=e,a={BytesUrl:n,BytesEngServiceType:r,BytesVoiceFormat:i,Uint32Sdkappid:null===(t=s.get("instance"))||void 0===t?void 0:t.sdkAppId,Uint64SourceType:0};return o.buildAndSendPacket({servcmd:"im_open_speech.ws_sentence_recognition",data:a})}({url:i,format:a,serverLanguageType:c});if(e){const{CmdErrorCode:t,BytesResult:s}=e;if(0===t.ErrorCode)return{code:0,data:{result:s}};throw{code:t.ErrorCode,message:t.ErrorInfo}}}catch(e){const{code:t,message:s}=e||{},o=new this._core.common.ChatError({functionName:"convertVoiceToText",code:t,message:s});console.error(o),this._core.ssoLog.createSSOLogData({method:"convertVoiceToText"}).setError(o).end()}}))}_validateVoiceFormat(e){if(!Ho.test(e))throw new this._core.common.ChatError({code:2119})}};class On{constructor(e){const{constants:t,common:s,utils:o}=wo.core,{CONV_C2C:n,CONV_GROUP:i}=t.OuterConstant,{ID:r,tinyID:a,from:c,to:l,clientTime:u=s.timeManager.getServerTimeSeconds()||0,random:d,sequence:h,cloudCustomData:p="",nick:g="",avatar:_="",clientSequence:m,conversationType:f,groupID:v,_elements:I,time:S}=e;this.ID=r||`${a}-${u}-${d}`,this.messageRandom=d,this.from=c,this.messageSender=c,this.time=S,this.messageSequence=h,this.clientSequence=m||h,this.clientTime=u,this.cloudCustomData=p,this.messageReceiver=l,this.avatar=_,this.nick=g;const E=o.deepCopyWithMethods(I);E.forEach((e=>{e.payload=e.content,delete e.content})),this.messageBody=E,r?f.startsWith(n)?this.receiverUserID=l:f.startsWith(i)&&(this.receiverGroupID=l):v?(this.receiverGroupID=v,this.messageReceiver=v):l&&(this.receiverUserID=l,this.messageReceiver=l)}transformElementsToServerFormat(){return this.messageBody?Array.isArray(this.messageBody)?this.messageBody.map((e=>e.transformToServerFormat({isMergerMessage:!0}))):this.messageBody.transformToServerFormat({isMergerMessage:!0}):null}}class Tn{static parseServerPushElement(e){const{MsgContent:t}=e,{MsgList:s=[],CompatibleText:o,AbstractList:n,Title:i,PbMsgKey:r,JsonMsgKey:a}=t||{},c=s.map((e=>rn(e)));return new Tn({messageList:c,title:i,abstractList:n,compatibleText:o,pbDownloadKey:r,downloadKey:a})}constructor(e){this.type=wo.core.constants.OuterConstant.MSG_MERGER;const{messageList:t,title:s,abstractList:o,compatibleText:n,pbDownloadKey:i="",downloadKey:r="",version:a=0,layersOverLimit:c=!1}=e,l=[];t.forEach((e=>{if(e){const t=new On(e);l.push(t)}})),this.content={messageList:l,title:s,abstractList:o,compatibleText:n,version:a,downloadKey:r,pbDownloadKey:i,layersOverLimit:c}}validateBeforeSend(){const{isEmpty:e}=wo.core.helper;return e(this.content.messageList)?{isValid:!1,error:{message:"content is invalid"}}:{isValid:!0}}transformToServerFormat(e){const{isMergerMessage:t=!1}=e||{},s=t?this.payload:this.content,{abstractList:o,compatibleText:n,downloadKey:i,layersOverLimit:r,pbDownloadKey:a,title:c,version:l,messageList:u}=s;return{MsgType:this.type,MsgContent:{AbstractList:o,CompatibleText:n,JsonMsgKey:i,LayersOverLimit:r,PbMsgKey:a,Title:c,Version:l,MsgList:nn(u)}}}}var Dn=new class{init(e){this._core=e;const{message:t,helper:s,constants:{OuterConstant:o}}=e;t.messageFactory.registerElementClass(o.MSG_MERGER,Tn),s.registerApi({apiName:"createMergerMessage",context:this}),s.registerApi({apiName:"sendMessage",context:this,matcher:e=>e[0].type===o.MSG_MERGER}),s.registerApi({apiName:"downloadMergerMessage",context:this})}createMergerMessage(e){const{common:t}=this._core;if(!e)return null;const s=new Tn(e.payload),o=t.getCurrentUserID(),n=this._core.message.messageFactory.createMessage(Object.assign(Object.assign({},e),{from:o}));return n.setRelayFlag(!0),n.setElement(s),n}sendMessage(e,t){return a(this,void 0,void 0,(function*(){var s,o,n;try{const i=function(e){let t="utf-8";wo.core.helper.IN_BROWSER&&document&&(t=document.charset.toLowerCase());let s,o=0,n=0;if(n=e.length,"utf-8"===t||"utf8"===t)for(let t=0;t<n;t++)s=e.codePointAt(t),s<=127?o+=1:s<=2047?o+=2:s<=65535?o+=3:(o+=4,t++);else if("utf-16"===t||"utf16"===t)for(let t=0;t<n;t++)s=e.codePointAt(t),s<=65535?o+=2:(o+=4,t++);else o=e.replace(/[^\x00-\xff]/g,"aa").length;return o}(JSON.stringify(e));let r=e,c=null;if(i>11264){r=this._core.utils.deepCopyWithMethods(e);try{const{JsonMsgKey:e,PbMsgKey:t}=yield function(e){return a(this,void 0,void 0,(function*(){const{payload:{messageList:t}}=e,s={MsgList:nn(t)};return wo.core.common.buildAndSendPacket({servcmd:"im_long_msg.save_relay_json_msg",data:s})}))}(r),{payload:s}=r;c=new Tn(Object.assign(Object.assign({},s),{messageList:[],downloadKey:e,pbDownloadKey:t})),r.setElement(c)}catch(e){console.error(e)}}const{data:{message:l}}=yield null===(n=null===(o=null===(s=this._core)||void 0===s?void 0:s.message)||void 0===o?void 0:o.messageSender)||void 0===n?void 0:n.sendMessage(r,t);return c&&l.setElement(e._elements),{code:0,data:{message:l}}}catch(e){throw console.error(e),e}}))}downloadMergerMessage(e){return a(this,void 0,void 0,(function*(){try{const t=e.payload,{downloadKey:s,pbDownload:o,type:n,messageList:i}=t,c=r(t,["downloadKey","pbDownload","type","messageList"]),l=yield function(e){return a(this,void 0,void 0,(function*(){return wo.core.common.buildAndSendPacket({servcmd:"im_long_msg.get_relay_json_msg",data:{JsonMsgKey:e}})}))}(s),{MsgList:u}=l||{},d=null==u?void 0:u.map((e=>{const t=rn(e);return new On(t)}));return"function"==typeof e.isOnlineMessage?e.setElement({type:e.type,content:Object.assign({messageList:d},c)}):(e.payload.messageList=d,e.payload.downloadKey="",e.payload.pbDownloadKey=""),e}catch(e){console.error(e)}}))}};var Rn=new class{install(e){this._core=e,wo.init(e),gn.init(e),fn.init(e),Sn.init(e),yn.init(e),an.init(e),Mn.init(e),An.init(e),cn.init(e),Dn.init(e),e.helper.registerValidateConfig({auth:un,params:ln}),e.notificationCenter.subscribeInnerEvent(e.InnerEvent.DESTROY,this.dispose,this)}dispose(){const{notificationCenter:e,InnerEvent:t}=this._core;e.unSubscribeInnerEvent(t.DESTROY,this.dispose,this),Sn.dispose(),yn.dispose(),cn.dispose()}};var Ln=new class{constructor(){this._name="WebRequest"}init(e){this._core=e}request(e,t){return a(this,void 0,void 0,(function*(){var s;const{isEmpty:o}=null===(s=this._core)||void 0===s?void 0:s.utils,{downloadUrl:n="",method:i="PUT",url:r,qs:a,headers:c={},resources:l,dataType:u="text",uploadByIP:d,uploadIP:h}=e;let p=r;if(a){const e=this._queryString(a);e&&(p+=`${p.includes("?")?"&":"?"}${e}`)}const g=new XMLHttpRequest;g.open(i.toUpperCase(),p,!0),g.responseType=u;const _=Object.assign({},c);if(d&&h&&(_.host=h),!o(_))for(const e in _)_.hasOwnProperty(e)&&!["content-length","user-agent","origin","host"].includes(e.toLowerCase())&&g.setRequestHeader(e,_[e]);return g.onload=()=>{const s=this._getResponseBody(g,n,d&&h),o=this._buildResponse(g,s);if(200===g.status)t(null,o);else{if(h&&!p.includes(h))return e.url=this._domainName2IP(p,h),e.uploadByIP=!0,this.request(e,t);t({code:g.status,message:JSON.stringify(g.responseText)},o)}},g.onerror=()=>{const e=this._getResponseBody(g,n,d&&h),s=this._buildResponse(g,e),o={code:g.status,message:0===g.status?"CORS blocked or network error":JSON.stringify(g.responseText)};t(o,s)},e.onProgress&&g.upload&&(g.upload.onprogress=t=>{const{total:s,loaded:o}=t,n=Math.min(Math.floor(100*o/s),100);e.onProgress({total:s,loaded:o,percent:n/100})}),g.send(l),g}))}_buildResponse(e,t){const s={};return e.getAllResponseHeaders().trim().split("\n").forEach((e=>{if(e){const[t,o]=e.split(":").map((e=>e.trim()));s[t.toLowerCase()]=o}})),{statusCode:e.status,statusMessage:e.statusText,headers:s,data:t}}_getResponseBody(e,t,s){return 200===e.status&&t?{location:t,uploadIP:s}:{response:e.responseText,uploadIP:s}}_queryString(e,t="&",s="="){var o;const{isEmpty:n,isPlainObject:i}=null===(o=this._core)||void 0===o?void 0:o.utils;return n(e)?"":i(e)?Object.keys(e).map((o=>{const n=encodeURIComponent(o)+s;return Array.isArray(e[o])?e[o].map((e=>n+encodeURIComponent(e))).join(t):n+encodeURIComponent(e[o])})).filter(Boolean).join(t):void 0}_domainName2IP(e,t){return e.replace(/^http(s)?:\/\/(.*?)\//,`https://${t}/`)}};const Nn=["unknown","image","video","audio","log"];var bn=new class{init(e){this._core=e}request(e,t){var s;const{MINI_APP_NAMESPACE:o,IN_ALIPAY_MINI_APP:n,IN_UNI_IOS_APP:i}=null===(s=this._core)||void 0===s?void 0:s.utils,{resources:a="",headers:c={},url:l,downloadUrl:u=""}=e;let d=l,h=null;const p=u?u.match(/^(https?:\/\/[^/]+\/)([^/]*\/?)(.*)$/):null;if(!p)return void console.warn("message Invalid download URL format");const g=decodeURIComponent(p[3]),_=g.includes("?")?g.split("?")[0]:g||"",m={key:e.fileKey||_,success_action_status:200,"Content-Type":""},f={};if(i){const[e,t]=l.split("?sign=");t&&(d=`${e}?sign=${encodeURIComponent(t)}`,f.sign=decodeURIComponent(t),f.signature=decodeURIComponent(t))}let v={url:d,header:c,name:"file",filePath:a,formData:Object.assign(Object.assign({},m),f),timeout:e.timeout||3e5};if(n){const t=r(v,["name"]);v=Object.assign(Object.assign({},t),{fileName:"file",fileType:e.fileType?Nn[e.fileType]:"image"})}return h=o.uploadFile(Object.assign(Object.assign({},v),{success:e=>{this._handleResponse({response:e,downloadUrl:u,callback:t})},fail:e=>{this._handleResponse({response:e,downloadUrl:u,callback:t})}})),h.onProgressUpdate&&h.onProgressUpdate((t=>{e.onProgress&&e.onProgress({total:t.totalBytesExpectedToSend||0,loaded:t.totalBytesSent||0,percent:t.progress?Math.floor(t.progress)/100:0})})),h}_handleResponse(e){const{downloadUrl:t,response:s,callback:o}=e,n={};if(s.header)for(const e in s.header)s.header.hasOwnProperty(e)&&(n[e.toLowerCase()]=s.header[e]);const i=+s.statusCode;200===i?o(null,{statusCode:i,headers:n,data:Object.assign(Object.assign({},s.data),{location:t})}):o({code:i,message:JSON.stringify(s.data)},{statusCode:i,headers:n,data:void 0})}};function wn(e){return"file"===function(e){return Object.prototype.toString.call(e).match(/^\[object (.*)\]$/)[1].toLowerCase()}(e)}function Pn(e){const t=e||99999999;return Math.round(Math.random()*t)}function Un(e,t=!0,s=!0){const o=Date.now();return t?s?o-e+" ms":`${Math.round((o-e)/1e3)} s`:s?o-e:Math.round((o-e)/1e3)}function Gn(e){return`${Array.from({length:8},(()=>Math.floor(65536*(1+Math.random())).toString(16).substring(1))).join("")}-${e}`}function kn(e,t){return Math.round(Number(e)*10**t)/10**t}function Fn(e){const t=1024,s=1048576;return e<t?`${e}B`:e<s?`${Math.floor(e/t)}KB`:`${Math.floor(e/s)}MB`}function $n(e){if(e<=1048576){return`${kn(e/1024,1)}KB/s`}return`${kn(e/1048576,1)}MB/s`}const qn="TIMImageElem",xn="TIMSoundElem",Vn="TIMFileElem",Bn="TIMVideoFileElem",jn="RichMediaMessagePlugin",Wn=["rich.my-imcloud.com","imrich.qcloud.com"],Kn=1,Hn=2,Yn=3;var zn;!function(e){e.UNSENT="unSend",e.SUCCESS="success",e.FAIL="fail"}(zn||(zn={}));var Jn=new class{init(e){this._core=e}addAuthToUrl(e=""){if(this._isMiniProgramTempFile(e))return e;const t=function(e){return e?e.startsWith("https://")?e:e.startsWith("http://")?e.replace("http://","https://"):e:""}(e);return this.processResourceUrl(t)}removeAuthToUrl(e){return function(e,t){const[s,o]=e.split("?");if(!o)return s;const n=o.split("&").reduce(((e,s)=>{const[o,n]=s.split("=");return o&&o!==t&&(e[o]=n||""),e}),{}),i=Object.keys(n).map((e=>`${e}${n[e]?`=${n[e]}`:""}`)).join("&");return i?`${s}?${i}`:s}(e,"authKey")}_isMiniProgramTempFile(e){return!!this.getPlatformFlags().IN_MINI_APP&&Object.values(TEMP_FILE_PATTERNS).some((t=>t.test(e)))}extractFileFromInput(e){return wn(e)?e:function(e){if("object"!=typeof e||null===e)return!1;const t=Object.getPrototypeOf(e);if(null===t)return!0;let s=t;for(;null!==Object.getPrototypeOf(s);)s=Object.getPrototypeOf(s);return t===s}(e)&&"undefined"!=typeof uni?Array.isArray(e.tempFiles)&&e.tempFiles.length>0?e.tempFiles[0]:null:e instanceof HTMLInputElement&&e.files&&e.files.length>0?e.files[0]:null}probeImageWidthHeight(e){return a(this,void 0,void 0,(function*(){var t;const{IN_MINI_APP:s,IN_BROWSER:o}=(null===(t=this._core)||void 0===t?void 0:t.utils)||{};return this._shouldSkipProbing()?{width:0,height:0}:o?this._probeImageDimensionsWeb(e):s?this._probeImageDimensionsMiniApp(e):void 0}))}isSimpleCos(){var e;const t=(null===(e=this._core)||void 0===e?void 0:e.store.get("cloudConfig"))||{},{simple_cos:s}=t;return"0"!==s}getFileDNList(){var e;let t=Wn;const s=(null===(e=this._core)||void 0===e?void 0:e.store.get("cloudConfig"))||{},{file_dn_list:o}=s;if(void 0===o)return t;try{JSON.parse(o).forEach((e=>{t.includes(e)||t.push(e)}))}catch(e){console.warn(e),t=Wn}return t}getPlatform(){var e;return null===(e=this._core)||void 0===e?void 0:e.utils.platform}generateUUID(e,t){var s;let o=`${this.getSDKAppID()}-${this.getCurrentUserID()}-${null===(s=this._core)||void 0===s?void 0:s.utils.randomString()}`;if(t)return`${o}.${t}`;const n=e.name||e.value||e.url||e.tempFilePath,i=n&&n.slice(n.lastIndexOf(".")+1);return i&&(o=`${o}.${i}`),o}processResourceUrl(e){if(!e)return"";let t=e;const s=this.getFileDownloadProxy(),o=this.getAuthKey(),n=this.getFileDNList();s&&(e.startsWith("http://")?t=e.replace(/^http:\/\/[^/]+/,s):e.startsWith("https://")&&(t=e.replace(/^https:\/\/[^/]+/,s)));const i=o&&-1===t.indexOf("authKey=")&&function(e,t){let s=!1;if(e){const o=e.match(/:\/\/([0-9]?\.)?(.[^/:]+)/),n=o&&o[2]||"";if(n.includes("rich-dev"))return!0;for(let e=0;e<t.length;e++)if(n.endsWith(t[e])){s=!0;break}}return s}(t,n);return i&&(t=t.indexOf("?")>-1?`${t}&authKey=${o}`:`${t}?authKey=${o}`),t}getCurrentUserID(){var e,t;return null===(t=null===(e=this._core)||void 0===e?void 0:e.store.get("login"))||void 0===t?void 0:t.userId}getSDKAppID(){var e,t;return null===(t=null===(e=this._core)||void 0===e?void 0:e.store.get("instance"))||void 0===t?void 0:t.sdkAppId}getFileDownloadProxy(){var e,t;return(null===(t=null===(e=this._core)||void 0===e?void 0:e.store.get("instance"))||void 0===t?void 0:t.fileDownloadProxy)||""}getFileUploadProxy(){var e,t;return(null===(t=null===(e=this._core)||void 0===e?void 0:e.store.get("instance"))||void 0===t?void 0:t.fileUploadProxy)||""}getAuthKey(){var e,t;return(null===(t=null===(e=this._core)||void 0===e?void 0:e.store.get("login"))||void 0===t?void 0:t.authKey)||""}isPrivateNetWork(){var e,t;return null===(t=null===(e=this._core)||void 0===e?void 0:e.store.get("instance"))||void 0===t?void 0:t.proxyServer}getPlatformFlags(){var e;const{IN_BROWSER:t,IN_MINI_APP:s,IN_RN_APP:o,IN_UNI_NATIVE_APP:n}=null===(e=this._core)||void 0===e?void 0:e.utils;return{IN_BROWSER:t,IN_MINI_APP:s,IN_RN_APP:o,IN_UNI_NATIVE_APP:n}}isEmpty(e){var t;const{isEmpty:s}=null===(t=this._core)||void 0===t?void 0:t.utils;return s(e)}_probeImageDimensionsMiniApp(e){var t;const{MINI_APP_NAMESPACE:s}=(null===(t=this._core)||void 0===t?void 0:t.utils)||{};return new Promise((t=>{s.getImageInfo({src:e,success:e=>t({width:e.width,height:e.height}),fail:()=>t({width:0,height:0})})}))}_shouldSkipProbing(){var e;const{IN_RN_APP:t,IS_IE:s,IE_VERSION:o}=(null===(e=this._core)||void 0===e?void 0:e.utils)||{};return t||s&&9===o}_probeImageDimensionsWeb(e){return new Promise((t=>{const s=new Image,o=()=>{s.onload=null,s.onerror=null,s.src=""};s.onload=()=>{t({width:s.width,height:s.height}),o()},s.onerror=()=>{t({width:0,height:0}),o()},s.src=e}))}};var Zn=new class{constructor(){this.uploadFileTryCount=0,this.maxRetries=1,this.systemClockOffset=0,this.httpRequest=null,this.uploadFileType="",this.duration=900,this.fetchCosTryCount=0}init(e){var t;this._core=e;const{IN_MINI_APP:s}=e.utils;this.httpRequest=s?bn:Ln,null===(t=this.httpRequest)||void 0===t||t.init(e)}uploadToCOS(e){return a(this,void 0,void 0,(function*(){const t=`${jn} uploadToCOS`,{file:s}=e;this.uploadFileType=e.uploadFileType,console.log(`${t} options:`,e);try{const o=Date.now(),n=yield this._createCosOptions(e),i=yield this._uploadFile(n);this._handleUploadError(i,e);const r=this._createUploadResult(s,i),a=Date.now()-o,c=Fn(s.size),l=`size:${c} time:${a}ms speed:${$n(1e3*s.size/a)}`;return console.log(`${t} ok. name:${s.name} ${l}`),{uploadOptions:n,response:r}}catch(e){throw console.warn(`${t} failed, error:`,e),e}}))}_handleUploadError(e,t){var s,o;const{ChatError:n}=null===(s=this._core)||void 0===s?void 0:s.helper;if(403===e.statusCode)throw Un(Date.now(),!1),t.url,(null===(o=null==e?void 0:e.data)||void 0===o?void 0:o.uploadIP)&&e.data.uploadIP,new n({message:"Upload failed with status 403"})}_createUploadResult(e,t){return{fileName:e.name,fileSize:e.size,fileType:e.type.slice(e.type.indexOf("/")+1).toLowerCase(),location:t.data.location||"",uploadTime:Un(Date.now(),!1),uploadSpeed:$n(1e3*e.size/Un(Date.now(),!1))}}_createCosOptions(e){return a(this,void 0,void 0,(function*(){const{fileName:t,resources:s,uploadMethod:o}=this._prepareUploadParams(e),n=this._isC2CConversation(e.message.conversationID)?1:2;try{const i=yield this._fetchCosSignatureUrl({fileType:this.uploadFileType,fileName:t,uploadMethod:o,duration:this.duration,userID:e.message.from,conversationType:n}),{uploadUrl:r,downloadUrl:a,requestSnapshotUrl:c,thumbUrl:l,largeUrl:u,fileKey:d}=i,h=!Jn.isPrivateNetWork()&&i.uploadIP;return{url:this._getRawOrUploadProxyUrl(r),fileType:this.uploadFileType,fileName:t,resources:s,downloadUrl:a,requestSnapshotUrl:c,thumbUrl:l,largeUrl:u,fileKey:d,uploadIP:h||"",onProgress:t=>this._handleUploadProgress(t,e)}}catch(e){throw console.error("Failed to create COS pre-signed URL options:",e),e}}))}_prepareUploadParams(e){console.log(`${jn} prepareUploadParams:`,e);const{file:t}=e,{IN_MINI_APP:s,IN_RN_APP:o}=Jn.getPlatformFlags(),n=s||o,i=n&&e.message.type!==Vn,{name:r}=t,a=r.slice(r.lastIndexOf(".")),c=`${Pn(999999)}${a}`;return{fileName:Gn(i?t.name:c),resources:n?t.url:t,uploadMethod:n?1:0}}_handleUploadProgress(e,t){if("function"==typeof t.onProgress)try{t.onProgress(e.percent)}catch(e){throw console.warn("Upload progress callback error:",e),e}}_fetchCosSignatureUrl(e){return a(this,void 0,void 0,(function*(){const t=`${jn} fetchCosSignatureUrl`,s=Jn.isSimpleCos(),o=this._prepareCosRequestData(e),n=s?"im_cos_msg.simple_sig":"im_cos_msg.pre_sig";try{const e=yield function(e,t,s){return a(this,void 0,void 0,(function*(){try{const{helper:o,channel:n}=s,i=o.generateCosSpecifiedData({servcmd:e,data:t}),r=`${i.head.seq}${e}`;return yield n.sendPacket(i,{requestId:r})}catch(e){throw console.warn("getCosSig error:",e),e}}))}(n,o,this._core);this.fetchCosTryCount=0;const i=this._processResponse(e);return console.log(`${t} ok. isSimpleCos:${s} data:`,i),i||{}}catch(s){if(console.error(`${t} failed, error:`,s),this.fetchCosTryCount<1)return this.fetchCosTryCount++,this._fetchCosSignatureUrl(e);throw this.fetchCosTryCount=0,s}}))}_processResponse(e){var t;const s=Jn.isSimpleCos(),o=s?null===(t=null==e?void 0:e.rpt_pre_sig)||void 0===t?void 0:t[0]:e;if(!o)return{};if(s){const{str_final_ip:e,rpt_pre_sig:t,uint32_file_id:s,uint32_exist_flag:n,str_download_url:i,str_upload_url:r,str_snapshot_url:a,str_file_key:c}=o;return{uploadIP:e,preSig:t,fileID:s,existFlag:n,downloadUrl:i,uploadUrl:r,requestSnapshotUrl:a,fileKey:c}}const{upload_url:n,download_url:i,snapshot_url:r,thumb_url:a,large_url:c,file_key:l}=o;return{uploadUrl:n,downloadUrl:i,requestSnapshotUrl:r,thumbUrl:a,largeUrl:c,fileKey:l}}_prepareCosRequestData(e){return Jn.isSimpleCos()?{uint32_upload_method:e.uploadMethod,uint32_platform:Jn.getPlatform(),uint32_sdkappid:Jn.getSDKAppID(),str_user_id:e.userID,uint32_scene:e.conversationType,rpt_upload_object:[{uint32_file_id:1,uint32_file_type:e.fileType,str_file_name:e.fileName}]}:{file_type:e.fileType,file_name:e.fileName,upload_method:e.uploadMethod,Duration:e.duration}}_uploadFile(e){return a(this,void 0,void 0,(function*(){return new Promise(((t,s)=>{this.httpRequest.request(e,((o,n)=>{o&&this.uploadFileTryCount<this.maxRetries&&this.shouldRetry(o)?(this.uploadFileTryCount++,this._uploadFile(e).then(t).catch(s)):(this.uploadFileTryCount=0,o?s(o):t(n))}))}))}))}shouldRetry(e){if(!e)return!1;if(5===Math.floor(e.statusCode/100))return!0;return!(!this.isTimeRelatedError(e)||!this._isClockOutOfSync(e))&&(this._syncSystemClock(e),!0)}isTimeRelatedError(e){var t,s;try{const o=null===(t=e.error)||void 0===t?void 0:t.Code,n=null===(s=e.error)||void 0===s?void 0:s.Message;return"RequestTimeTooSkewed"===o||"AccessDenied"===o&&"Request has expired"===n}catch(e){return!1}}_isClockOutOfSync(e){var t,s,o;const n=(null===(t=e.headers)||void 0===t?void 0:t.date)||(null===(s=e.headers)||void 0===s?void 0:s.Date)||(null===(o=e.error)||void 0===o?void 0:o.ServerTime);if(!n)return!1;const i=Date.now(),r=Date.parse(n);return Math.abs(i+this.systemClockOffset-r)>=3e4}_syncSystemClock(e){var t,s,o;const n=(null===(t=e.headers)||void 0===t?void 0:t.date)||(null===(s=e.headers)||void 0===s?void 0:s.Date)||(null===(o=e.error)||void 0===o?void 0:o.ServerTime);if(n){const e=Date.now(),t=Date.parse(n);this.systemClockOffset=t-e}}_getRawOrUploadProxyUrl(e){const t=Jn.getFileUploadProxy();let s=e;return t&&(s=e.replace(/^https:\/\/[^/]+/,t)),s}_isC2CConversation(e){return"C2C"===e.slice(0,3)}};const Xn=2108,Qn=2251,ei=2252,ti=["jpg","jpeg","gif","png","bmp","image","webp"],si=20971520,oi={JPG:1,JPEG:1,GIF:2,PNG:3,BMP:4,UNKNOWN:255};class ni{constructor(e,t){this.instanceID=Pn(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=Jn.addAuthToUrl(e.imageUrl||e.url||""),this.url=Jn.addAuthToUrl(e.url||t)}setSizeType(e){this.sizeType=e}setType(e){this.type=e}setImageUrl(e){e&&(this.imageUrl=Jn.addAuthToUrl(e))}getImageUrl(){return this.imageUrl}}function ii(e){const{originUrl:t,originWidth:s,originHeight:o,min:n=198}=e,i=parseInt(s)||0,a=parseInt(o)||0,c={url:void 0,width:0,height:0};if((i<=a?i:a)<=n)c.url=t,c.width=i,c.height=a;else{a<=i?(c.width=Math.ceil(i*n/a),c.height=n):(c.width=n,c.height=Math.ceil(a*n/i));const e=t&&t.indexOf("?")>-1?`${t}&`:`${t}?`;c.url=198===n?`${e}imageView2/3/w/198/h/198`:`${e}imageView2/3/w/720/h/720`}if(void 0===t){return r(c,["url"])}return c}class ri{constructor(e){this._imageMemoryURL="",this._percent=0,this.type=qn;const{uuid:t,file:s,imageFormat:o,imageInfoArray:n=[]}=e;this._imageMemoryURL=this.createImageDataAsURL(s),this.content={imageFormat:o,uuid:t,imageInfoArray:[]},this.initImageInfoArray(n),this.autoFixUrl()}static parseServerPushElement(e){const{MsgContent:t}=e,{ImageFormat:s,ImageInfoArray:o,UUID:n}=t,i=function(e){return e.map((e=>({size:e.Size,type:e.Type,width:e.Width,height:e.Height,url:e.URL})))}(o);return new ri({imageFormat:s,imageInfoArray:i,uuid:n})}createImageDataAsURL(e){let t="";const{IN_MINI_APP:s,IN_RN_APP:o,IN_BROWSER:n}=Jn.getPlatformFlags();return e?((s||o)&&(t=e.url),n&&(t=window.URL.createObjectURL(e)),t):t}initImageInfoArray(e=[]){const t={type:0,size:0,width:0,height:0,url:""};for(let s=0;s<3;s++){const o=e[s]||Object.assign({},t),n=new ni(o,this._imageMemoryURL);n.setSizeType(s+1),n.setType(s),this.addImageInfo(n)}this.updateAccessSideImageInfoArray()}autoFixUrl(){const e=["http","https"];this.content.imageInfoArray.forEach((t=>{if(!t.url||""===t.imageUrl)return;const[s,...o]=t.imageUrl.split("://"),n=o.join("://");e.includes(s)||t.setImageUrl(`https://${n}`)}))}updatePercent(e){this._percent=Math.min(e,1)}updateImageFormat(e){this.content.imageFormat=oi[e.toUpperCase()]||oi.UNKNOWN}addImageInfo(e){this.content.imageInfoArray.length>=3||this.content.imageInfoArray.push(e)}updateImageInfoArray(e){const t=this.content.imageInfoArray.length;let s;for(let o=0;o<t;o++)s=this.content.imageInfoArray[o],e[o].size&&(s.size=e[o].size),e[o].url&&s.setImageUrl(e[o].url),e[o].width&&(s.width=e[o].width),e[o].height&&(s.height=e[o].height)}updateAccessSideImageInfoArray(){const[e]=this.content.imageInfoArray;e&&0!==e.width&&0!==e.height&&(!function(e){const t=e[2];e[2]=e[1],e[1]=t;for(let t=0;t<e.length;t++)e[t].setType(t)}(this.content.imageInfoArray),Object.assign(this.content.imageInfoArray[2],ii({originWidth:e.width,originHeight:e.height,min:720})))}validateBeforeSend(){const[e]=this.content.imageInfoArray,t=!!e&&""!==e.imageUrl&&0!==e.size;return{isValid:t,error:t?null:{message:"content can not be empty"}}}transformToServerFormat(e){const{isMergerMessage:t=!1}=e||{},s=t?this.payload:this.content,{uuid:o,imageFormat:n,imageInfoArray:i}=s;return{MsgType:this.type,MsgContent:{ImageFormat:n,ImageInfoArray:this.parseImageInfoArray(i),UUID:o}}}parseImageInfoArray(e){return e.map((e=>({InstanceId:e.instanceID,Type:e.sizeType,MsgType:e.type,Size:e.size,Width:e.width,Height:e.height,URL:Jn.removeAuthToUrl(e.imageUrl)})))}}var ai=new class{constructor(){this._messageOptionsMap=new Map}init(e){var t;this._core=e;const{notificationCenter:s,helper:o,InnerEvent:n,message:i}=e;o.registerApi({apiName:"createImageMessage",context:this}),null===(t=null==i?void 0:i.messageFactory)||void 0===t||t.registerElementClass(qn,ri),s.subscribeInnerEvent(n.DESTROY,this._dispose,this)}createImageMessage(e){var t,s,o,n,i;try{const n=this._core.ssoLog.createSSOLogData({method:"createImageMessage"});console.log(`${jn} createImageMessage options:`,e);const i=null===(t=this._core.store.get("login"))||void 0===t?void 0:t.userId,r=null===(o=null===(s=this._core)||void 0===s?void 0:s.message.messageFactory)||void 0===o?void 0:o.createMessage(Object.assign(Object.assign({},e),{from:i})),a=this._processImage(e);e.payload.file=a;const c={imageFormat:oi.UNKNOWN,uuid:Jn.generateUUID(a),file:a,imageInfoArray:[]},l=new ri(c);return r.setElement(l),this._messageOptionsMap.set(r.clientSequence,e),console.log(`${jn} createImageMessage OK imageMessage:`,r),n.end(),r}catch(e){throw null===(i=(n=this._core.ssoLog.getSSOLogData("createImageMessage")).setError)||void 0===i||i.call(n,e).end(),console.error(`${jn} createImageMessage error:`,e),e}}upload(e){return a(this,void 0,void 0,(function*(){console.log(`${jn} uploadImage message:`,e);const t=e.getElements()[0],{file:s}=this._messageOptionsMap.get(e.clientSequence).payload;this._validateBeforeUploadImage(s);const o=yield this._performImageUpload(t,e,s),n=this._generateImageInfo(o);return t.updateImageInfoArray(n),e}))}_performImageUpload(e,t,s){return a(this,void 0,void 0,(function*(){const{to:o}=t,n={uploadFileType:Kn,file:s,to:o,message:t,onProgress:s=>{var o,n;e.updatePercent(s),null===(n=null===(o=this._messageOptionsMap.get(t.clientSequence))||void 0===o?void 0:o.onProgress)||void 0===n||n.call(o,s)}},{uploadOptions:i,response:r}=yield Zn.uploadToCOS(n);return this._parseResponse(i,r)}))}_generateImageInfo(e){console.log(`${jn} generateImageInfo`);const{location:t,fileSize:s,width:o,height:n,smallImageUrl:i,smallImageWidth:r,smallImageHeight:a,largeImageUrl:c,largeImageWidth:l,largeImageHeight:u,imageInfoArray:d}=e,h=Jn.addAuthToUrl(t),p={size:s,url:h,width:o,height:n};return(null==d?void 0:d.length)>0?this._processImageInfoArray(d,s):i&&c?[Object.assign({},p),{largeImageUrl:c,largeImageWidth:l,largeImageHeight:u},{smallImageUrl:i,smallImageWidth:r,smallImageHeight:a}]:[Object.assign({},p),this._generateThumbInfo(h,o,n,720),this._generateThumbInfo(h,o,n,198)]}_generateThumbInfo(e,t,s,o){return ii({originUrl:e,originWidth:t,originHeight:s,min:o})}_processImageInfoArray(e,t){let s,o,n;for(const i of e)1===i.type?(o=i,o.size=t):2===i.type?(n=i,n.size=t):(s=i,s.size=t);return[Object.assign({},s),Object.assign({},n),Object.assign({},o)]}_parseResponse(e,t){return a(this,void 0,void 0,(function*(){console.log(`${jn} parseResponse`);try{const{thumbUrl:s,largeUrl:o,downloadUrl:n}=e;s&&o&&(yield this._getImageInfoByUrl(s,t,"thumb"),yield this._getImageInfoByUrl(o,t,"large"));if(Jn.isSimpleCos()&&!Jn.isPrivateNetWork()&&(yield this._getImageInfoArray(n,t),null==t?void 0:t.uploadIP)){const e=this._extractDomainFromUrl(n);e&&(yield this._getDownloadIP(e,t))}return t}catch(e){throw console.error("Failed to parse response:",e),e}}))}_extractDomainFromUrl(e){try{const t=e.match(/:\/\/([^\/]+)/);return t?t[1]:null}catch(e){return console.warn("Failed to extract domain from URL:",e),null}}_getImageInfoByUrl(e,t,s){return a(this,void 0,void 0,(function*(){try{const o=Jn.addAuthToUrl(e),{width:n=0,height:i=0}=yield Jn.probeImageWidthHeight(o);t.width=n,t.height=i,"thumb"===s?(t.smallImageUrl=e,t.smallImageWidth=n,t.smallImageHeight=i):(t.largeImageUrl=e,t.largeImageWidth=n,t.largeImageHeight=i)}catch(e){console.warn(`Failed to get ${s} image info:`,e)}}))}_validateBeforeUploadImage(e){var t;const{ChatError:s}=null===(t=this._core)||void 0===t?void 0:t.helper;if(!e)throw new s({code:Qn});this._checkImageType(e),this._checkImageSize(e)}_processImage(e){var t;try{const{IN_MINI_APP:s}=null===(t=this._core)||void 0===t?void 0:t.utils;let{file:o}=e.payload;return o=s?this._processMiniAppImageFile(o):this._processWebImageFile(o),o}catch(e){throw console.warn(`${jn} _processImage error:`,e),e}}_processMiniAppImageFile(e){wn(e)&&console.warn("FileUnsupportedInMiniApp","createImageMessage");const t=e.tempFiles[0].path||e.tempFiles[0].tempFilePath;return{url:t,name:t.slice(t.lastIndexOf("/")+1),size:e.tempFiles&&e.tempFiles[0].size||1,type:t.slice(t.lastIndexOf(".")+1).toLowerCase()}}_processWebImageFile(e){var t;const{ChatError:s}=null===(t=this._core)||void 0===t?void 0:t.helper,o=Jn.extractFileFromInput(e);if(!o)throw new s({message:"Invalid file. Pass either `e.target` (from file input) or a File object"});return o}_getDownloadIP(e,t){return a(this,void 0,void 0,(function*(){const s=`${jn} getDownloadIP domainName: ${e}`;try{const o=yield function(e,t){return a(this,void 0,void 0,(function*(){try{const{helper:s,channel:o}=t,n="im_cos_msg.get_final_ip",i={str_domain:e},r=s.generateProtocolData({servcmd:n,data:i}),a=`${r.head.seq}${n}`;return yield o.sendPacket(r,{requestId:a})}catch(e){throw console.warn("getFinalIP error:",e),e}}))}(e,this._core);if(!o||!o.str_final_ip)return;console.log(`${s} ok. downloadIP:${o}`);const n=t.location.split("/");n[0]=o.str_final_ip,t.location=n.join("/")}catch(e){console.warn(e)}}))}_getImageInfoArray(e,t){return a(this,void 0,void 0,(function*(){const s=`${jn}._getImageInfoArray`;try{const o=yield function(e,t){return a(this,void 0,void 0,(function*(){try{const{helper:s,channel:o}=t,n="im_cos_msg.get_imageinfo",i={str_image_url:e},r=s.generateProtocolData({servcmd:n,data:i}),a=`${r.head.seq}${n}`;return yield o.sendPacket(r,{requestId:a})}catch(e){throw console.warn("getImageInfo error:",e),e}}))}(e,this._core);return t.imageInfoArray=this._processImageInfoResponse(o),console.log(`${s} ok`),t}catch(e){throw t.imageInfoArray=void 0,console.warn(`${s} failed, error:`,e),e}}))}_processImageInfoResponse(e){if(!e)return[];const{rpt_msg_image_info:t}=e;return t.map((e=>({type:e.uint32_image_type,url:e.str_url,width:e.uint32_width,height:e.uint32_height,imageFormat:e.str_image_format})))}_checkImageType(e){const{utils:t,helper:s}=this._core;let o="";if(t.IN_MINI_APP&&(o=e.url.slice(e.url.lastIndexOf(".")+1)),t.IN_BROWSER&&(o=e.name.slice(e.name.lastIndexOf(".")+1)),ti.indexOf(o.toLowerCase())<0)throw new s.ChatError({code:ei})}_checkImageSize(e){const{utils:t,helper:s}=this._core;let o=0;if(o=(t.IN_MINI_APP,e.size),0===o)throw new s.ChatError({code:Xn});if(o>=si)throw new s.ChatError({message:`File size exceeds limit: ${Fn(si)}`})}_reset(){this._messageOptionsMap.clear()}_dispose(){this._reset();const{notificationCenter:e,InnerEvent:t}=this._core;e.unSubscribeInnerEvent(t.DESTROY,this._dispose,this)}};const ci=2108,li=2401,ui="2.5.0",di="1.18.0",hi=104857600;function pi(e,t){const s=e.split("."),o=t.split("."),n=Math.max(s.length,o.length);for(;s.length<n;)s.push("0");for(;o.length<n;)o.push("0");for(let e=0;e<n;e++){const t=parseInt(s[e]),n=parseInt(o[e]);if(t>n)return 1;if(t<n)return-1}return 0}class gi{constructor(e){this.type=Vn,this.uploadProgress=0;const t=this._getFileInfo(e);this.content={downloadFlag:2,fileUrl:Jn.addAuthToUrl(e.url||e.fileUrl)||"",uuid:e.uuid,fileName:t.name||"",fileSize:t.size||0}}static parseServerPushElement(e){const{MsgContent:t}=e,{Download_Flag:s,Url:o,FileName:n,FileSize:i,UUID:r}=t;return new gi({downloadFlag:s,url:o,fileName:n,fileSize:i,uuid:r})}updatePercent(e){this.uploadProgress=Math.min(e,1)}updateFileUrl(e){this.content.fileUrl=e}validateBeforeSend(){const e=""!==this.content.fileUrl&&""!==this.content.fileName&&this.content.fileSize>0;return{isValid:e,error:e?null:{message:"content can not be empty"}}}transformToServerFormat(e){const{isMergerMessage:t=!1}=e||{},s=t?this.payload:this.content,{uuid:o,downloadFlag:n,fileUrl:i,fileName:r,fileSize:a}=s;return{MsgType:this.type,MsgContent:{Download_Flag:n,Url:Jn.removeAuthToUrl(i),FileName:r,FileSize:a,UUID:o}}}_getFileInfo(e){if(e.fileName&&e.fileSize)return{size:e.fileSize,name:e.fileName};const{file:t}=e;return t?(Jn.getPlatform().IN_UNI_NATIVE_APP&&this._processNativeAppFile(t),{size:t.size,name:t.name}):{size:0,name:""}}_processNativeAppFile(e){if(e.path&&e.path.includes(".")){const t=e.path.slice(e.path.lastIndexOf(".")+1).toLowerCase();e.type=t,e.name||(e.name=`${Pn(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 _i=new class{constructor(){this._messageOptionsMap=new Map}init(e){var t;this._core=e;const{notificationCenter:s,helper:o,InnerEvent:n,message:i}=e;o.registerApi({apiName:"createFileMessage",context:this}),null===(t=null==i?void 0:i.messageFactory)||void 0===t||t.registerElementClass(Vn,gi),s.subscribeInnerEvent(n.DESTROY,this._dispose,this)}createFileMessage(e){var t,s,o,n,i;try{const n=this._core.ssoLog.createSSOLogData({method:"createFileMessage"});console.log(`${jn} createFileMessage options:`,e),this._checkVersion();const i=this._processFile(e.payload.file);e.payload.file=i;const r=null===(t=this._core.store.get("login"))||void 0===t?void 0:t.userId,a=null===(o=null===(s=this._core)||void 0===s?void 0:s.message.messageFactory)||void 0===o?void 0:o.createMessage(Object.assign(Object.assign({},e),{from:r})),c={uuid:Jn.generateUUID(i),file:i},l=new gi(c);return a.setElement(l),this._messageOptionsMap.set(a.clientSequence,e),console.log(`${jn} createFileMessage success fileMessage:`,a),n.end(),a}catch(e){throw null===(i=(n=this._core.ssoLog.getSSOLogData("createFileMessage")).setError)||void 0===i||i.call(n,e).end(),console.error(`${jn} createFileMessage error:`,e),e}}upload(e){return a(this,void 0,void 0,(function*(){console.log(`${jn} uploadFile message:`,e);const{file:t}=this._messageOptionsMap.get(e.clientSequence).payload;this._validateBeforeUploadFile(t);const s=e.getElements()[0],o=yield this._performFileUpload(s,e,t),n=Jn.addAuthToUrl(null==o?void 0:o.location);return s.updateFileUrl(n),e}))}_validateBeforeUploadFile(e){var t;const{ChatError:s}=null===(t=this._core)||void 0===t?void 0:t.helper;if(!e)throw new s({code:li});if(e.size>hi)throw new s({message:`File size exceeds limit: ${Fn(hi)}`});if(0===e.size)throw new s({code:ci})}_performFileUpload(e,t,s){return a(this,void 0,void 0,(function*(){const{to:o}=t,n={uploadFileType:Kn,file:s,to:o,message:t,onProgress:s=>{var o,n;e.updatePercent(s),null===(n=null===(o=this._messageOptionsMap.get(t.clientSequence))||void 0===o?void 0:o.onProgress)||void 0===n||n.call(o,s)}},{response:i}=yield Zn.uploadToCOS(n);return i}))}_processFile(e){var t,s;const{IN_BROWSER:o,IN_RN_APP:n,IN_WX_MINI_APP:i,IN_QQ_MINI_APP:r,IN_UNI_NATIVE_APP:a}=null===(t=this._core)||void 0===t?void 0:t.utils,{ChatError:c}=null===(s=this._core)||void 0===s?void 0:s.helper;if(o||a){const t=Jn.extractFileFromInput(e);if(!t)throw new c({message:"Invalid file. Pass either `e.target` (from file input) or a File object"});return t}if(i||r){const{tempFiles:t}=e;return Object.assign(Object.assign({},t[0]),{url:t[0].path})}return n?Object.assign(Object.assign({},e),{url:e.uri}):e}_checkVersion(){var e,t;const{MINI_APP_NAMESPACE:s,IN_MINI_APP:o,IN_WX_MINI_APP:n,IN_QQ_MINI_APP:i,IN_UNI_NATIVE_APP:r}=null===(e=this._core)||void 0===e?void 0:e.utils,{ChatError:a}=null===(t=this._core)||void 0===t?void 0:t.helper;if(o){if(!(n||i||r))throw new a({message:"Unsupported mini app environment"});const e=s.getSystemInfoSync().SDKVersion;if(n&&pi(e,ui)<0){throw new a({message:`WXChooseMessageFile requires SDK version ${ui} or higher`})}if(i&&pi(e,di)<0){throw new a({message:`QQChooseMessageFile requires SDK version ${di} or higher`})}}}_reset(){this._messageOptionsMap.clear()}_dispose(){this._reset();const{notificationCenter:e,InnerEvent:t}=this._core;e.unSubscribeInnerEvent(t.DESTROY,this._dispose,this)}};const mi=2108,fi=2352,vi=["mp4","quicktime","mov"],Ii=104857600;class Si{constructor(e){this.type=Bn,this.uploadProgress=0;const t="number"==typeof(null==e?void 0:e.videoSecond)?null==e?void 0:e.videoSecond:0;this.content={remoteVideoUrl:Jn.addAuthToUrl(e.remoteVideoUrl||e.videoUrl||""),videoFormat:e.videoFormat,videoSecond:parseInt(null==t?void 0:t.toString(),10),videoSize:e.videoSize,videoUrl:Jn.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:Jn.addAuthToUrl(e.thumbUrl),snapshotUrl:Jn.addAuthToUrl(e.thumbUrl)}}static parseServerPushElement(e){const{MsgContent:t}=e,{VideoUrl:s,VideoFormat:o,VideoSecond:n,VideoSize:i,VideoDownloadFlag:r,VideoUUID:a,ThumbUUID:c,ThumbFormat:l,ThumbWidth:u,SnapshotWidth:d,ThumbHeight:h,SnapshotHeight:p,ThumbSize:g,SnapshotSize:_,ThumbDownloadFlag:m,ThumbUrl:f,SnapshotUrl:v}=t;return new Si({videoUrl:s,videoFormat:o,videoSecond:n,videoSize:i,videoDownloadFlag:r,videoUUID:a,thumbUUID:c,thumbFormat:l,thumbWidth:u,snapshotWidth:d,thumbHeight:h,snapshotHeight:p,thumbSize:g,snapshotSize:_,thumbDownloadFlag:m,thumbUrl:f,snapshotUrl:v})}updatePercent(e){this.uploadProgress=Math.min(e,1)}updateVideoUrl(e){e&&(this.content.remoteVideoUrl=e)}updateSnapshotInfo(e){const{snapshotUrl:t,snapshotWidth:s,snapshotHeight:o}=e;Jn.isEmpty(t)||(this.content.thumbUrl=this.content.snapshotUrl=t),Jn.isEmpty(s)||(this.content.thumbWidth=this.content.snapshotWidth=Number(s)),Jn.isEmpty(o)||(this.content.thumbHeight=this.content.snapshotHeight=Number(o))}validateBeforeSend(){const e=""!==this.content.remoteVideoUrl;return{isValid:e,error:e?null:{message:"content can not be empty"}}}transformToServerFormat(e){const{isMergerMessage:t=!1}=e||{},s=t?this.payload:this.content,{remoteVideoUrl:o,videoFormat:n,videoSecond:i,videoSize:r,videoDownloadFlag:a,videoUUID:c,thumbUUID:l,thumbFormat:u,thumbWidth:d,snapshotWidth:h,thumbHeight:p,snapshotHeight:g,thumbSize:_,snapshotSize:m,thumbDownloadFlag:f,thumbUrl:v,snapshotUrl:I}=s;return{MsgType:this.type,MsgContent:{VideoUrl:Jn.removeAuthToUrl(o),VideoFormat:n,VideoSecond:i,VideoSize:r,VideoDownloadFlag:a,VideoUUID:c,ThumbUUID:l,ThumbFormat:u,ThumbWidth:d,SnapshotWidth:h,ThumbHeight:p,SnapshotHeight:g,ThumbSize:_,SnapshotSize:m,ThumbDownloadFlag:f,ThumbUrl:Jn.removeAuthToUrl(v),SnapshotUrl:Jn.removeAuthToUrl(I)}}}}var Ei=new class{constructor(){this._messageOptionsMap=new Map}init(e){var t;this._core=e;const{notificationCenter:s,helper:o,InnerEvent:n,message:i}=e;o.registerApi({apiName:"createVideoMessage",context:this}),null===(t=null==i?void 0:i.messageFactory)||void 0===t||t.registerElementClass(Bn,Si),s.subscribeInnerEvent(n.DESTROY,this._dispose,this)}createVideoMessage(e){var t,s,o,n,i;try{const n=this._core.ssoLog.createSSOLogData({method:"createVideoMessage"});console.log(`${jn} createVideoMessage options:`,e);const i=this._processVideo(e);e.payload.file=i;const r=null===(t=this._core.store.get("login"))||void 0===t?void 0:t.userId,a=null===(o=null===(s=this._core)||void 0===s?void 0:s.message.messageFactory)||void 0===o?void 0:o.createMessage(Object.assign(Object.assign({},e),{from:r})),c={videoFormat:i.videoFile.type,videoSecond:kn(i.videoFile.second,0),videoSize:i.videoFile.size,remoteVideoUrl:"",videoUrl:i.videoFile.url,videoUUID:Jn.generateUUID(i.videoFile),thumbUUID:Jn.generateUUID(i.videoFile,"jpg"),thumbWidth:i.width||200,thumbHeight:i.height||200,thumbUrl:i.thumbUrl,thumbSize:i.thumbSize,thumbFormat:"jpg"},l=new Si(c);return a.setElement(l),this._messageOptionsMap.set(a.clientSequence,e),n.end(),a}catch(e){throw null===(i=(n=this._core.ssoLog.getSSOLogData("createVideoMessage")).setError)||void 0===i||i.call(n,e).end(),console.error(`${jn} createVideoMessage error:`,e),e}}upload(e){return a(this,void 0,void 0,(function*(){console.log(`${jn} uploadVideo message:`,e);const t=e.getElements()[0],{file:s}=this._messageOptionsMap.get(e.clientSequence).payload;this._validateBeforeUploadVideo(s);const o=yield this._performVideoUpload(t,e,s),{location:n,snapshotInfo:i}=o,r=Jn.addAuthToUrl(n);return t.updateVideoUrl(r),Jn.isEmpty(i)||t.updateSnapshotInfo(i),e}))}_validateBeforeUploadVideo(e){var t;const{ChatError:s}=null===(t=this._core)||void 0===t?void 0:t.helper;if(e.videoFile.size>Ii)throw new s({message:`File size exceeds limit: ${Fn(Ii)}`});if(0===e.videoFile.size)throw new s({code:mi});if(-1===vi.indexOf(e.videoFile.type))throw new s({code:fi})}_performVideoUpload(e,t,s){return a(this,void 0,void 0,(function*(){const{to:o}=t,n={uploadFileType:Hn,file:s,to:o,message:t,onProgress:s=>{var o,n;e.updatePercent(s),null===(n=null===(o=this._messageOptionsMap.get(t.clientSequence))||void 0===o?void 0:o.onProgress)||void 0===n||n.call(o,s)}},{response:i,uploadOptions:r}=yield Zn.uploadToCOS(n);return{snapshotInfo:yield this._getSnapshotInfoByUrl(r.requestSnapshotUrl),location:i.location}}))}_processVideo(e){var t,s;try{const{ChatError:o}=null===(t=this._core)||void 0===t?void 0:t.helper,{IN_MINI_APP:n,IN_BROWSER:i}=null===(s=this._core)||void 0===s?void 0:s.utils;let{file:r}=e.payload,a={};if(n&&(a=this._processMiniVideoFile(r),r.name=a.name,r.url=a.url),i){const e=Jn.extractFileFromInput(r);if(!e)throw new o({message:"Invalid file. Pass either `e.target` (from file input) or a File object"});r=e,a=this._processWebVideoFile(r)}return r.videoFile=a,r.thumbUrl="",r.thumbSize=0,r}catch(e){throw console.warn(`${jn} _processFile error:`,e),e}}_processMiniVideoFile(e){var t,s;const{IN_ALIPAY_MINI_APP:o}=null===(t=this._core)||void 0===t?void 0:t.utils,{ChatError:n}=null===(s=this._core)||void 0===s?void 0:s.helper;if(o)throw new n({message:"VideoUnsupportedInAlipay"});if(wn(e))throw new n({message:"FileUnsupportedInMiniApp"});return Array.isArray(e.tempFiles)&&(e=e.tempFiles[0]),{url:e.tempFilePath,name:e.tempFilePath.slice(e.tempFilePath.lastIndexOf("/")+1),size:e.size||1,second:e.duration||0,type:e.tempFilePath.slice(e.tempFilePath.lastIndexOf(".")+1).toLowerCase()}}_processWebVideoFile(e){const{name:t,size:s=1,duration:o=0,type:n}=e,i=n.split("/")[1];return{url:window.URL.createObjectURL(e),name:t,size:s,second:o,type:i}}_getSnapshotInfoByUrl(e){return a(this,void 0,void 0,(function*(){try{console.log(`${jn} _getSnapshotInfoByUrl url:`,e);const t={version:1,platform:Jn.getPlatform(),cover_name:Gn(Pn(99999)),snapshot_url:e},s=yield function(e,t){return a(this,void 0,void 0,(function*(){try{const s="im_cos_msg.video_cover",{helper:o,channel:n}=t,i=o.generateCosSpecifiedData({servcmd:s,data:e}),r=`${i.head.seq}${s}`;return yield n.sendPacket(i,{requestId:r})}catch(e){throw console.warn("getSnapshotInfo error:",e),e}}))}(t,this._core),{download_url:o}=s||{};if(console.log(`${jn} _getSnapshotInfoByUrl OK snapshotUrl:`,o),Jn.isEmpty(o))return{};const n=Jn.addAuthToUrl(o),{width:i=0,height:r=0}=yield Jn.probeImageWidthHeight(n);return{snapshotUrl:n,snapshotWidth:i,snapshotHeight:r}}catch(e){throw console.error(`${jn} _getSnapshotInfoByUrl error:`,e),e}}))}_reset(){this._messageOptionsMap.clear()}_dispose(){this._reset();const{notificationCenter:e,InnerEvent:t}=this._core;e.unSubscribeInnerEvent(t.DESTROY,this._dispose,this)}};class Ci{constructor(e){this.uploadProgress=0,this.type=xn,this.content={downloadFlag:2,second:e.second,size:e.size,url:Jn.addAuthToUrl(e.url),remoteAudioUrl:Jn.addAuthToUrl(e.url||""),uuid:e.uuid}}static parseServerPushElement(e){const{MsgContent:t}=e,{Url:s,Download_Flag:o,Second:n,Size:i,UUID:r}=t;return new Ci({url:s,downloadFlag:o,second:n,size:i,uuid:r})}updatePercent(e){this.uploadProgress=Math.min(e,1)}updateAudioUrl(e){this.content.remoteAudioUrl=e}validateBeforeSend(){const e=""!==this.content.remoteAudioUrl;return{isValid:e,error:e?null:{message:"content can not be empty"}}}transformToServerFormat(e){const{isMergerMessage:t=!1}=e||{},s=t?this.payload:this.content,{uuid:o,downloadFlag:n,remoteAudioUrl:i,size:r,second:a}=s;return{MsgType:this.type,MsgContent:{Url:Jn.removeAuthToUrl(i),Download_Flag:n,Second:a,Size:r,UUID:o}}}}const yi=2108,Mi=2300,Ai=20971520;var Oi=new class{constructor(){this._messageOptionsMap=new Map}init(e){var t;this._core=e;const{notificationCenter:s,helper:o,InnerEvent:n,message:i}=e;o.registerApi({apiName:"createAudioMessage",context:this}),null===(t=null==i?void 0:i.messageFactory)||void 0===t||t.registerElementClass(xn,Ci),s.subscribeInnerEvent(n.DESTROY,this._dispose,this)}createAudioMessage(e){var t,s,o,n,i;try{const n=this._core.ssoLog.createSSOLogData({method:"createAudioMessage"});console.log(`${jn} createAudioMessage options:`,e);let{file:i}=e.payload;i=this._processAudioFile(e.payload.file),e.payload.file=i;const r=null===(t=this._core.store.get("login"))||void 0===t?void 0:t.userId,a=null===(o=null===(s=this._core)||void 0===s?void 0:s.message.messageFactory)||void 0===o?void 0:o.createMessage(Object.assign(Object.assign({},e),{from:r})),c={second:Math.floor((i.duration||i.second)/1e3),size:i.fileSize||i.size||1,url:i.tempFilePath||i.uri||i.url,uuid:Jn.generateUUID(i)},l=new Ci(c);return a.setElement(l),this._messageOptionsMap.set(a.clientSequence,e),n.end(),a}catch(e){throw null===(i=(n=this._core.ssoLog.getSSOLogData("createAudioMessage")).setError)||void 0===i||i.call(n,e).end(),console.error(`${jn} createAudioMessage error:`,e),e}}upload(e){return a(this,void 0,void 0,(function*(){console.log(`${jn} uploadAudio message:`,e);const{file:t}=this._messageOptionsMap.get(e.clientSequence).payload;this._validateBeforeUploadAudio(t);const s=e.getElements()[0],o=yield this._performAudioUpload(s,e,t),n=Jn.addAuthToUrl(null==o?void 0:o.location);return s.updateAudioUrl(n),e}))}_validateBeforeUploadAudio(e){var t;const{ChatError:s}=null===(t=this._core)||void 0===t?void 0:t.helper;if(!e)throw new s({code:Mi});if(e.size>Ai)throw new s({message:`File size exceeds limit: ${Fn(Ai)}`});if(0===e.size)throw new s({code:yi})}_performAudioUpload(e,t,s){return a(this,void 0,void 0,(function*(){const{to:o}=t,n={uploadFileType:Yn,file:s,to:o,message:t,onProgress:s=>{var o,n;e.updatePercent(s),null===(n=null===(o=this._messageOptionsMap.get(t.clientSequence))||void 0===o?void 0:o.onProgress)||void 0===n||n.call(o,s)}},{response:i}=yield Zn.uploadToCOS(n);return i}))}_processAudioFile(e){var t;const{IN_MINI_APP:s,IN_BROWSER:o}=null===(t=this._core)||void 0===t?void 0:t.utils;return s?this._processMiniFile(e):o?this._processWebFile(e):void 0}_processMiniFile(e){return{url:e.tempFilePath,name:e.tempFilePath.slice(e.tempFilePath.lastIndexOf("/")+1),size:e.fileSize,second:e.duration,type:e.tempFilePath.slice(e.tempFilePath.lastIndexOf(".")+1).toLowerCase()}}_processWebFile(e){if(e.tempFilePath||e.uri)return e;const t=URL.createObjectURL(e);return e.tempFilePath=t,e}_reset(){this._messageOptionsMap.clear()}_dispose(){this._reset();const{notificationCenter:e,InnerEvent:t}=this._core;e.unSubscribeInnerEvent(t.DESTROY,this._dispose,this)}};const Ti={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}},Di={createImageMessage:Ti,createAudioMessage:Ti,createVideoMessage:Ti,createFileMessage:Ti},Ri={createImageMessage:!0,createAudioMessage:!0,createVideoMessage:!0,createFileMessage:!0},Li={[qn]:ai,[Vn]:_i,[Bn]:Ei,[xn]:Oi};var Ni=new class{install(e){this._core=e;const{constants:{OuterConstant:{MSG_AUDIO:t,MSG_FILE:s,MSG_IMAGE:o,MSG_VIDEO:n}}}=e;ai.init(e),_i.init(e),Ei.init(e),Oi.init(e),Zn.init(e),Jn.init(e),e.helper.registerApi({apiName:"sendMessage",context:this,matcher:e=>[t,s,o,n].includes(e[0].type)}),e.helper.registerValidateConfig({auth:Ri,params:Di})}sendMessage(e,t){return a(this,void 0,void 0,(function*(){var s,o,n;try{return console.log("sendMessage message:",e),yield this._upload(e),yield null===(n=null===(o=null===(s=this._core)||void 0===s?void 0:s.message)||void 0===o?void 0:o.messageSender)||void 0===n?void 0:n.sendMessage(e,t)}catch(e){throw console.error("sendMessage error:",e),e}}))}_upload(e){return a(this,void 0,void 0,(function*(){var t,s;if(!0!==e._relayFlag)try{const t=Li[e.type];if(t){const s=this._core.ssoLog.createSSOLogData({method:"upload"});s.setLogInfo({message:`type:${e.type}`}),yield t.upload(e),s.end()}}catch(o){throw e.status=zn.FAIL,o instanceof Error&&(o.data={message:e}),this._core.message.messageDataHandler.storeConversationMessage(e),null===(s=(t=this._core.ssoLog.getSSOLogData("upload")).setError)||void 0===s||s.call(t,o).end(),o}}))}};const bi=new class{init(e){this.core=e}},wi=e=>{const{core:{OuterConstant:t,utils:{isString:s}}}=bi;return s(e)&&e.slice(0,3)===t.CONV_C2C},Pi=e=>{const{core:{OuterConstant:t,utils:{isString:s}}}=bi;return s(e)&&e.slice(0,5)===t.CONV_GROUP},Ui=e=>{const{core:{OuterConstant:t,utils:{isString:s}}}=bi;return s(e)&&e===t.CONV_SYSTEM},Gi=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:bi.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 ki(e){const{core:{utils:{isString:t}}}=bi,s=[];if(!t(e))return s;const o=e.length;if(0===o)return s;for(let t=o-1;t>=0;t--)"1"===e[t]&&s.push(2**(o-t-1));return s}function Fi(e){const{OuterConstant:t}=bi.core;let s="";return 0===e?s=t.MSG_REMIND_ACPT_AND_NOTE:1===e?s=t.MSG_REMIND_DISCARD:2===e?s=t.MSG_REMIND_ACPT_NOT_NOTE:3===e&&(s=t.NOT_RECEIVE_OFFLINE_PUSH_EXCEPT_AT),s}function $i(e){const{OuterConstant:t}=bi.core;let s;return e.startsWith(t.CONV_C2C)&&(s=e.replace(t.CONV_C2C,"")),"@TLS#ERROR"===s||"@TLS#NOT_FOUND"===s}var qi,xi,Vi,Bi,ji;!function(e){e.NOT_START="notStart",e.PENDING="pending",e.RESOLVED="resolved",e.REJECTED="rejected"}(qi||(qi={})),function(e){e[e.C2C=1]="C2C",e[e.GROUP=2]="GROUP"}(xi||(xi={})),function(e){e[e.C2C=8]="C2C",e[e.GROUP=2]="GROUP"}(Vi||(Vi={})),function(e){e[e.ONLY_CONVERSATIONID=1]="ONLY_CONVERSATIONID"}(Bi||(Bi={})),function(e){e[e.CONV_DELETED=1]="CONV_DELETED",e[e.CONV_PINED=2]="CONV_PINED",e[e.CONV_UNPINED=3]="CONV_UNPINED",e[e.CONV_MARK_UPDATED=4]="CONV_MARK_UPDATED",e[e.CONV_GROUP_ADDED=5]="CONV_GROUP_ADDED",e[e.CONV_GROUP_DELETED=6]="CONV_GROUP_DELETED",e[e.CONV_GROUP_UPDATED=7]="CONV_GROUP_UPDATED"}(ji||(ji={}));var Wi;!function(e){e[e.CONV_NOT_FOUND=2500]="CONV_NOT_FOUND",e[e.USER_OR_GRP_NOT_FOUND=2501]="USER_OR_GRP_NOT_FOUND",e[e.CONV_UN_RECORDED_TYPE=2502]="CONV_UN_RECORDED_TYPE"}(Wi||(Wi={}));class Ki{constructor(e){this.conversationID=e.conversationID||"",this.unreadCount=e.unreadCount||0,this.type=e.type||"",this.lastMessage=Gi(e.lastMessage),this.peerReadTime=e.peerReadTime||0,this.groupAtInfoList=[],this.remark=e.remark||"",this.isPinned=e.isPinned||!1,this.messageRemindType=e.messageRemindType,this.markList=e.markList||[],this.customData=e.customData||"",this.conversationGroupList=e.conversationGroupList||[],this.draftText=e.draftText||"",this.userProfile=e.userProfile,this.groupProfile=e.groupProfile,this.subType=e.subType||"",this._isInfoCompleted=!1,this._init()}_init(){const{core:{OuterConstant:e,utils:{isUndefined:t}}}=bi;t(this.userProfile)&&this.type===e.CONV_C2C?this.userProfile={}:t(this.groupProfile)&&this.type===e.CONV_GROUP&&(this.groupProfile={}),this.subType&&this.type===e.CONV_GROUP&&(this.subType=this.groupProfile.type||"")}updateUnreadCount(e){const{core:{OuterConstant:t,utils:{isUndefined:s}}}=bi,{nextUnreadCount:o,isFromGetConversations:n,isUnreadC2CMessage:i}=e;s(o)||(this.subType!==t.GRP_AVCHATROOM?n&&this.type===t.CONV_GROUP||n&&this.type===t.CONV_TOPIC||i&&this.type===t.CONV_C2C?this.unreadCount=o:this.unreadCount+=o:this.unreadCount=0)}updateLastMessage(e){this.lastMessage=Gi(e)}reduceUnreadCount(){return this.unreadCount>=1&&(this.unreadCount-=1,!0)}isLastMessageRevoked(e){const{core:{OuterConstant:t}}=bi,{sequence:s,time:o}=e;return this.type===t.CONV_C2C&&s===this.lastMessage.lastSequence&&o===this.lastMessage.lastTime||this.type===t.CONV_GROUP&&s===this.lastMessage.lastSequence}setLastMessageRevoked(e){this.lastMessage.isRevoked=e}setLastMessageRevoker(e){this.lastMessage.revoker=e}setDraftText(e){this.draftText=e}updateGroupAtInfoList(e){const{core:{OuterConstant:t}}=bi;let[...s]=e.groupAtType;s.includes(t.CONV_AT_ME)||s.includes(t.CONV_AT_ALL)||(s=[t.CONV_AT_ALL_AT_ME]);const o={from:e.from,groupID:e.groupID,messageSequence:e.sequence,atTypeArray:s,__random:e.__random,__sequence:e.__sequence};this.groupAtInfoList.push(o)}clearGroupAtInfoList(){this.groupAtInfoList.length=0}getProfileCompleted(){return this._isInfoCompleted}setProfileCompleted(){this._isInfoCompleted=!0}}var Hi=new class{constructor(){this._name="ConversationDataHandler",this._totalUnreadCount=0,this._groupAtTipsList=[]}init(e){this._core=e;const{helper:t,notificationCenter:s,appStore:{conversationStore:o},constants:{WORKFLOW_NAME:n,WORKFLOW_STEP:i},InnerEvent:{MESSAGE_PUSH:r,NEW_MESSAGE:a,MESSAGE_DELETED:c,MESSAGE_REVOKED:l,MESSAGE_MODIFIED:u,CONVERSATION_UPDATED:d,LOGOUT:h,DESTROY:p}}=e;this._conversationStore=o,t.registerWorkflowStep(n.SYNC_SERVER_INFO_AFTER_LOGIN,i.CONVERSATION_UPDATE_AFTER_UNREAD_SYNC_FINISHED,this._handleUnreadSyncFinished,this),t.registerWorkflowStep(n.SYNC_SERVER_INFO_AFTER_LOGIN,i.CONVERSATION_UPDATE_AFTER_GROUP_LIST_SYNC_FINISHED,this._handleGroupListSyncFinished,this),t.registerWorkflowStep(n.RECEIVE_C2C_NEW_MESSAGE,i.CREATE_OR_UPDATE_CONVERSATION_BY_RECEIVE_NEW_MESSAGE,this._handleNewMessage,this),t.registerWorkflowStep(n.RECEIVE_C2C_NEW_MESSAGE,i.CONVERSATION_UPDATE_AFTER_UNREAD_SYNC_FINISHED,this._handleUnreadSyncFinished,this),t.registerWorkflowStep(n.RECEIVE_GROUP_NEW_MESSAGE,i.CREATE_OR_UPDATE_CONVERSATION_BY_RECEIVE_NEW_MESSAGE,this._handleNewMessage,this),t.registerWorkflowStep(n.SYNC_SERVER_INFO_AFTER_RE_ONLINE,i.CONVERSATION_UPDATE_AFTER_UNREAD_SYNC_FINISHED,this._handleUnreadSyncFinished,this);const{InnerEventSubType:{GROUP_AT_TIPS:g}}=s;s.subscribeInnerEvent(a,this._handleNewMessage,this),s.subscribeInnerEvent(r,g,this._handleNewGroupAtTips,this),s.subscribeInnerEvent(c,this._handleMessageDeleted,this),s.subscribeInnerEvent(l,this._handleMessageRevoked,this),s.subscribeInnerEvent(u,this._handleMessageModified,this),s.subscribeInnerEvent(d,this._handleConversationUpdated,this),s.subscribeInnerEvent(h,this._reset,this),s.subscribeInnerEvent(p,this._dispose,this),console.log(`${this._name}.init`)}_handleUnreadSyncFinished(e){const{constants:{WORKFLOW_STEP:t}}=this._core,{conversationUpdateFieldList:s=[],groupTipList:o=[],isUnreadC2CMessage:n}=e.result[t.UNREAD_MESSAGE_SYNC]||{};let i=!1;s.forEach((e=>{const{conversationID:t,unreadCount:s}=e,o=this.getLocalConversation(t);o&&o.unreadCount!==s&&(o.updateUnreadCount({nextUnreadCount:s,isUnreadC2CMessage:n}),i=!0)})),i&&this.emitConversationListUpdate(),this._handleGroupAtTipsSynced(o)}_handleGroupAtTipsSynced(e){for(let t=0;t<e.length;t++)12===e[t].Event&&this._handleNewGroupAtTips(e[t])}_handleGroupListSyncFinished(e){const{constants:{WORKFLOW_STEP:t}}=this._core,s=e.result[t.GROUP_LIST_SYNC]||[],{OuterConstant:{CONV_GROUP:o}}=this._core;let n=!1;for(let e=0;e<s.length;e++){const t=s[e],i=`${o}${t.groupID}`;if(!this.hasLocalConversation(i))continue;const r=this.getLocalConversation(i);r.groupProfile=JSON.parse(JSON.stringify(t)),r.lastMessage.lastSequence<t.nextMessageSeq&&(r.lastMessage.lastSequence=t.nextMessageSeq-1),r.subType||(r.subType=t.type),n=!0}n&&this.emitConversationListUpdate()}_handleNewMessage(e){const{conversationUpdateFieldList:t=[],isInstantMessage:s=!0,isUnreadC2CMessage:o=!1,updateUnreadCount:n=!0}=e.result||{};if(console.log(`${this._name}._handleNewMessage, conversationUpdateFieldList length:`,t.length,e),0===t.length)return;this.updateLocalConversationList({conversationUpdateFieldList:t,isInstantMessage:s,isUnreadC2CMessage:o,isFromGetConversations:!1,updateUnreadCount:n});t.filter((e=>this._isConversationNeedShow(e.conversationID))).length>0&&this.emitConversationListUpdate()}_handleNewGroupAtTips(e){const{GroupTips:t=[]}=e;t.forEach((e=>{const{GroupAtTips:t,MsgBody:s,GroupAtType:o,MsgRandom:n,ClientSeq:i}=e;let r={};t?r=this._convertGroupAtTipsKey(t):s?r=Object.assign(Object.assign({},this._convertGroupAtTipsKey(s)),{sync:!0}):o&&(r=Object.assign(Object.assign({},this._convertGroupAtTipsKey(e)),{sync:!0})),r.__random=n,r.__sequence=i,this._groupAtTipsList.push(r)})),console.log(`${this._name}._handleNewGroupAtTips groupAtTipsList: ${JSON.stringify(this._groupAtTipsList)}`),this._updateGroupAtInfoList()}_convertGroupAtTipsKey(e){const{From_Account:t,GroupId:s,MsgSeq:o,GroupAtType:n}=e;return{from:t,groupID:s,sequence:o,groupAtType:n}}_updateGroupAtInfoList(){if(0===this._groupAtTipsList.length)return;const{common:e,OuterConstant:t}=this._core,s=e.getCurrentUserID();let o=!1;this._groupAtTipsList.forEach((e=>{const{groupID:n,from:i}=e;if(i!==s){const s=this.getLocalConversation(`${t.CONV_GROUP}${n}`);s&&(s.updateGroupAtInfoList(e),o=!0)}})),o&&this.emitConversationListUpdate(),this._groupAtTipsList.length=0}_handleMessageDeleted(e){var t,s;console.log(`${this._name}._handleMessageDeleted, conversationID:`,e);const{message:{messageDataHandler:o},OuterConstant:n}=this._core,i=(null==o?void 0:o.getLocalMessageList(e))||[];let r={};for(let e=(i.length||0)-1;e>=0;e--)if(!i[e].isDeleted){r=i[e];break}const a=this.getLocalConversation(e);if(!a)return;let c=!1;a.lastMessage.lastSequence===r.sequence&&a.lastMessage.lastTime===r.time||((null===(s=null===(t=this._core)||void 0===t?void 0:t.helper)||void 0===s?void 0:s.isEmpty(r))&&(r=void 0),a.updateLastMessage(r),c=!0),e.startsWith(n.CONV_C2C)&&this.updateUnreadCount(e),c&&(this.emitConversationListUpdate(),console.log(`${this._name}._handleMessageDeleted. update conversationID:${e} with lastMessage:`,a.lastMessage))}_handleMessageRevoked(e){const{messageList:t=[],updateUnreadCount:s=!0}=e;if(console.log(`${this._name}._handleMessageRevoked messageList:${t.length}`),0===t.length)return;let o=null,n=!1;t.forEach((e=>{o=this.getLocalConversation(e.conversationID),o&&(s&&o.reduceUnreadCount()&&(n=!0),o.isLastMessageRevoked({sequence:e.sequence,time:e.time})&&(o.setLastMessageRevoked(!0),o.setLastMessageRevoker(e.revoker),n=!0))})),n&&this.emitConversationListUpdate()}_handleMessageModified(e){console.log(`${this._name}._handleMessageModified`,JSON.stringify(e));const{conversationID:t,messageList:s}=e,o=this.getLocalConversation(t),{utils:{isEmpty:n},common:{getMessagePreviewText:i}}=this._core;if(n(o))return;const{lastMessage:r}=o;if(r){const e=(null==s?void 0:s[0])||{};r.lastTime===e.time&&r.lastSequence===e.sequence&&r.version!==e.version&&(r.type=e.type,r.payload=e.payload,r.messageForShow=i(e.type,e.payload),r.cloudCustomData=e.cloudCustomData,r.version=e.version,this.emitConversationListUpdate(),console.log(`${this._name} conversationID:${t} lastMessage updated`))}}_handleConversationUpdated(){this.emitConversationListUpdate()}updateLocalConversationList(e){const{isFromGetConversations:t}=e,{newConversationList:s}=this._getTmpConversationListMapping(e);this._sortConversationList(),t||this._updateNewConversationProfile(s),console.log(`${this._name}.updateLocalConversationList newConversationList: ${s.length}`)}_getTmpConversationListMapping(e){const{OuterConstant:t}=this._core,{conversationUpdateFieldList:s,isFromGetConversations:o,isInstantMessage:n,isUnreadC2CMessage:i=!1,updateUnreadCount:r}=e,a=[],c=null==s?void 0:s.length;for(let e=0;e<c;e++){const c=new Ki(s[e]),{conversationID:l,type:u}=c;if(!$i(l))if(this.hasLocalConversation(l)){const a=this.getLocalConversation(l);if(o){this.setLocalConversation(l,c),u===t.CONV_C2C?c.unreadCount=(null==a?void 0:a.unreadCount)||0:u===t.CONV_GROUP&&(c.groupProfile=JSON.parse(JSON.stringify(null==a?void 0:a.groupProfile)));continue}this._mergeConversationInfo({conversationID:l,tmpConversation:c,lastMessage:s[e].lastMessage,isFromGetConversations:o,isInstantMessage:n}),this._patchLastMessage({conversationID:l,lastMessage:s[e].lastMessage,isInstantMessage:n}),!0===r&&(null==a||a.updateUnreadCount({nextUnreadCount:c.unreadCount,isFromGetConversations:o,isUnreadC2CMessage:i}))}else a.push(c),this.setLocalConversation(l,c)}return{newConversationList:a}}_mergeConversationInfo(e){const{conversationID:t,tmpConversation:s,lastMessage:o,isFromGetConversations:n,isInstantMessage:i}=e,r=this.getLocalConversation(t),a=["unreadCount","allowType","adminForbidType","payload"];!1===i&&a.push("lastMessage"),n&&a.push("isPinned");const{utils:{isUndefined:c,isEmpty:l},common:{deepMerge:u}}=this._core;c(i)&&o&&null===(null==r?void 0:r.lastMessage.payload)&&(r.lastMessage.payload=o.payload),l(null==r?void 0:r.lastMessage.revoker)||(r.lastMessage.revoker=null);u(r,s,a,[null,void 0,"",0,NaN])}_patchLastMessage(e){const{OuterConstant:t}=this._core,{conversationID:s,lastMessage:o,isInstantMessage:n}=e,i=this.getLocalConversation(s);if(i&&o){const{payload:e,nameCard:s,nick:r,cloudCustomData:a=""}=o;n&&(e&&(i.lastMessage.payload=e),i.type===t.CONV_GROUP&&(i.lastMessage.nameCard=s,i.lastMessage.nick=r)),i.lastMessage.cloudCustomData!==a&&(i.lastMessage.cloudCustomData=a)}}_sortConversationList(){const{utils:{isEmpty:e}}=this._core,t=[...this._conversationStore.getConversationMap()],s=[],o=[],n=[],i=[];t.forEach((t=>{!0===t[1].isPinned?e(t[1].lastMessage.lastTime)?o.push(t):s.push(t):e(t[1].lastMessage.lastTime)?i.push(t):n.push(t)}));const r=s.sort(((e,t)=>t[1].lastMessage.lastTime-e[1].lastMessage.lastTime)).concat(o).concat(n.sort(((e,t)=>t[1].lastMessage.lastTime-e[1].lastMessage.lastTime))).concat(i);this._updateConversationMapFromList(r)}_updateNewConversationProfile(e){if(0===e.length)return;const t=[],s=[],{OuterConstant:{CONV_GROUP:o,CONV_C2C:n}}=this._core;e.forEach((e=>{const{conversationID:i,type:r}=e;if(r===n){const e=i.replace(n,"");t.push(e)}else if(r===o){const e=i.replace(o,"");s.push(e)}})),t.length>0&&this._updateC2CConversation(t),s.length>0&&this._updateGroupConversation(s)}_updateC2CConversation(e){var t;const{OuterConstant:{CONV_C2C:s},appStore:{userStore:o},user:n}=this._core;let i=!1;null===(t=n.userProfile)||void 0===t||t.getUserProfile({userIDList:e}).then((e=>{((null==e?void 0:e.data)||[]).forEach((e=>{var t;const{userID:n}=e,r=this.getLocalConversation(`${s}${n}`);if(r){const s=(null===(t=o.getFriend(n))||void 0===t?void 0:t.remark)||"";r.remark=s,r.userProfile=e,i=!0}})),i&&this.emitConversationListUpdate()})).catch((e=>{}))}_updateGroupConversation(e){const{OuterConstant:{CONV_GROUP:t},appStore:{groupStore:s}}=this._core;let o=!1;e.forEach((e=>{const n=s.getGroup(e),i=this.getLocalConversation(`${t}${e}`);n&&i&&(i.groupProfile=n,o=!0)})),o&&this.emitConversationListUpdate()}_isConversationNeedShow(e){const t=this.getLocalConversation(e);if(this._core.utils.isUndefined(t))return!0;const{OuterConstant:s}=this._core,o=t.type===s.CONV_TOPIC,n=t.type===s.CONV_GROUP&&t.subType===s.GRP_ROOM,i=t.type===s.CONV_GROUP&&t.subType===s.GRP_LIVE;return!(o||n||i)}updateUnreadCount(e,t=!0){var s,o;let n=!1;const i=this.getLocalConversation(e),r=null===(o=null===(s=this._core)||void 0===s?void 0:s.message.messageDataHandler)||void 0===o?void 0:o.getLocalMessageList(e);if(!i)return n;const a=i.unreadCount,c=null==r?void 0:r.filter((e=>!e.isRead&&!e._onlineOnlyFlag&&!e.isDeleted)).length;return console.log(`${this._name}._updateUnreadCount conversationID:${e} currentUnreadCount:${a} newUnreadCount:${c}`),a!==c&&(i.unreadCount=c,n=!0,!0===t&&this.emitConversationListUpdate()),n}emitConversationListUpdate(e=!1){e&&this._sortConversationList();const{OuterEvent:{CONVERSATION_LIST_UPDATED:t}}=this._core,s=this.getLocalConversationList();this._emitEvent({name:t,data:s}),this._emitTotalUnreadCountUpdate()}_emitTotalUnreadCountUpdate(){var e;const t=this.getTotalUnreadMessageCount();this._totalUnreadCount!==t&&(console.log(`${this._name}._emitTotalUnreadCountUpdate from ${this._totalUnreadCount} to ${t}`),this._totalUnreadCount=t,this._emitEvent({name:null===(e=this._core)||void 0===e?void 0:e.OuterEvent.TOTAL_UNREAD_MESSAGE_COUNT_UPDATED,data:t}))}_emitEvent(e){var t;null===(t=this._core)||void 0===t||t.notificationCenter.emitOuterEvent(e.name,e)}getTotalUnreadMessageCount(){const{OuterConstant:e}=this._core,t=this.getLocalConversationList();let s=0;return t.forEach((t=>{t.type!==e.CONV_SYSTEM&&(""!==t.messageRemindType&&t.messageRemindType!==e.MSG_REMIND_ACPT_AND_NOTE||(s+=t.unreadCount))})),s}getLocalConversationList(){return[...this._conversationStore.getConversationMap().values()].filter((e=>this._isConversationNeedShow(e.conversationID)))}hasLocalConversation(e){return this._conversationStore.getConversationMap().has(e)}getLocalConversation(e){return this._conversationStore.getConversationMap().get(e)}setLocalConversation(e,t){return this._conversationStore.getConversationMap().set(e,t)}deleteLocalConversation(e){this._conversationStore.getConversationMap().delete(e)}_updateConversationMapFromList(e){this._clearConversationMap();for(const[t,s]of e)this.setLocalConversation(t,s)}_clearConversationMap(){this._conversationStore.getConversationMap().clear()}patchMessageRemindType(e,t){let s=!1;e.forEach((e=>{const o=this.getLocalConversation(e);(null==o?void 0:o.messageRemindType)!==t&&(o.messageRemindType=t,s=!0)})),console.log(`${this._name}.patchMessageRemindType conversationIDList:${e} messageRemindType:${t} hasUpdated:${s}`),s&&this.emitConversationListUpdate()}markMessageAsRead(e){const{message:{messageDataHandler:t}}=this._core,{conversationID:s,lastReadTime:o=0,lastReadSequence:n=0}=e,i=null==t?void 0:t.getLocalMessageList(s);if(0===i.length)return;const{length:r}=i;for(let e=r-1;e>=0;e--){const t=i[e],s=o&&t.time>o,r=n&&t.sequence>n;if(!s&&!r){if("in"===t.flow&&t.isRead)break;t.setIsRead(!0)}}}appendToPinnedConversation(e){const t=[...this._conversationStore.getConversationMap().entries()],s=t.findIndex((e=>!1===e[1].isPinned));t.splice(s,0,[e.conversationID,e]),this._updateConversationMapFromList(t),this.emitConversationListUpdate()}_reset(){this._clearConversationMap(),this._totalUnreadCount=0,this._groupAtTipsList=[]}_dispose(){const{notificationCenter:e,InnerEvent:{NEW_MESSAGE:t,MESSAGE_DELETED:s,MESSAGE_REVOKED:o,MESSAGE_MODIFIED:n,CONVERSATION_UPDATED:i,LOGOUT:r,DESTROY:a}}=this._core,{InnerEventSubType:{GROUP_AT_TIPS:c}}=e;e.unSubscribeInnerEvent(t,this._handleNewMessage,this),e.unSubscribeInnerEvent(t,c,this._handleNewGroupAtTips,this),e.unSubscribeInnerEvent(s,this._handleMessageDeleted,this),e.unSubscribeInnerEvent(o,this._handleMessageRevoked,this),e.unSubscribeInnerEvent(n,this._handleMessageModified,this),e.unSubscribeInnerEvent(i,this._handleConversationUpdated,this),e.unSubscribeInnerEvent(r,this._reset,this),e.unSubscribeInnerEvent(a,this._dispose,this)}};function Yi(e,t,s){return a(this,void 0,void 0,(function*(){const{helper:o,channel:n}=s,i=o.generateProtocolData({servcmd:e,data:t}),r=`${i.head.seq}${e}`;return yield n.sendPacket(i,{requestId:r})}))}var zi=new class{constructor(){this._name="SyncConversationList",this._pagingStatus="",this._pagingTimeStamp=0,this._pagingStartIndex=0,this._pagingPinnedTimeStamp=0,this._pagingPinnedStartIndex=0}init(e){this._core=e;const{notificationCenter:t,InnerEvent:s,helper:o,constants:n}=e;o.registerWorkflowStep(n.WORKFLOW_NAME.SYNC_SERVER_INFO_AFTER_RE_ONLINE,n.WORKFLOW_STEP.CONVERSATION_RECOVER,this._syncConversationListOnReOnline,this),o.registerWorkflowStep(n.WORKFLOW_NAME.SYNC_SERVER_INFO_AFTER_LOGIN,n.WORKFLOW_STEP.CONVERSATION_LIST_SYNC,this._syncConversationList,this),t.subscribeInnerEvent(s.DESTROY,this._dispose,this),console.log(`${this._name}.init`)}isSyncCompleted(){return this._pagingStatus===qi.RESOLVED}_syncConversationListOnReOnline(){return a(this,void 0,void 0,(function*(){return this._syncConversationList()}))}_syncConversationList(){return a(this,void 0,void 0,(function*(){yield this._pagingGetConversationList(!0),this._pagingStatus=qi.RESOLVED,Hi.emitConversationListUpdate()}))}_pagingGetConversationList(e){return a(this,void 0,void 0,(function*(){try{this._pagingStatus=qi.PENDING;const{common:t}=this._core,s=yield function(e,t){return a(this,void 0,void 0,(function*(){const{fromAccount:s,pagingTimeStamp:o,pagingStartIndex:n,pagingPinnedTimeStamp:i,pagingPinnedStartIndex:r}=e;return Yi("recentcontact.page_get",{AssistFlags:31,MsgAssistFlags:15,OrderType:1,From_Account:s,StartIndex:n,TimeStamp:o,TopStartIndex:r,TopTimeStamp:i},t)}))}({fromAccount:t.getCurrentUserID(),pagingTimeStamp:e?this._pagingTimeStamp:0,pagingStartIndex:e?this._pagingStartIndex:0,pagingPinnedTimeStamp:e?this._pagingPinnedTimeStamp:0,pagingPinnedStartIndex:e?this._pagingPinnedStartIndex:0},this._core),{CompleteFlag:o,SessionItem:n=[],TimeStamp:i,StartIndex:r,TopTimeStamp:c,TopStartIndex:l}=s||{};if(n.length>0){const e=this._getConversationOptions(n);Hi.updateLocalConversationList({conversationUpdateFieldList:e,isFromGetConversations:!0,updateUnreadCount:!0}),Hi.emitConversationListUpdate()}this._pagingTimeStamp=i,this._pagingStartIndex=r,this._pagingPinnedTimeStamp=c,this._pagingPinnedStartIndex=l,1!==o&&this._pagingGetConversationList(e)}catch(e){throw console.error(`${this._name}._pagingGetConversationList fail:`,e),e}}))}_getConversationOptions(e){const{utils:{isUndefined:t}}=this._core,s=this._convertConversationKey(e);return this._filterValidConversations(s).map((e=>(t(e.lastMsg)&&(e.lastMsg={elements:[]}),e.type===xi.C2C?this._assembleC2COption(e):this._assembleGroupOption(e))))}_filterValidConversations(e){return e.filter((({type:e,userID:t})=>e===xi.C2C&&!$i(t)||2===e))}_assembleC2COption(e){var t,s,o,n,i,r;const{OuterConstant:a}=this._core,c=this._createUserprofile(e);return{conversationID:`${a.CONV_C2C}${e.userID}`,type:a.CONV_C2C,lastMessage:{lastTime:e.time,lastSequence:e.sequence,fromAccount:e.lastC2CMsgFromAccount,type:(null===(t=e.lastMsg)||void 0===t?void 0:t.elements[0])?null===(s=e.lastMsg)||void 0===s?void 0:s.elements[0].type:null,payload:(null===(o=e.lastMsg)||void 0===o?void 0:o.elements[0])?this._amendLayersOverLimitProp(e.lastMsg.elements[0].content):null,cloudCustomData:(null===(n=e.lastMsg)||void 0===n?void 0:n.cloudCustomData)||"",isRevoked:e.lastMessageFlag===Vi.C2C,onlineOnlyFlag:!1,nick:"",nameCard:"",version:0,isPeerRead:this._computeIsPeerRead(e),revoker:(null===(r=null===(i=e.lastMsg)||void 0===i?void 0:i.revokerInfo)||void 0===r?void 0:r.revoker)||null},unreadCount:0,userProfile:c,peerReadTime:e.peerReadTime,isPinned:1===e.isPinned,customData:e.customMark||"",markList:ki(e.standardMark),conversationGroupList:[],remark:e.friendRemark||"",messageRemindType:this._transMsgRemindType(e.messageRemindType)}}_createUserprofile(e){var t;const{userID:s,nick:o,peerAvatar:n}=e,i=[{tag:"Tag_Profile_IM_Nick",value:o},{tag:"Tag_Profile_IM_Image",value:n}];return null===(t=this._core.user.userProfile)||void 0===t?void 0:t.createProfile(s,i)}_computeIsPeerRead(e){const{common:t}=this._core,s=t.getCurrentUserID(),{lastC2CMsgFromAccount:o,time:n,c2cPeerReadTime:i}=e;return o===s&&n<=i}_assembleGroupOption(e){var t,s,o;const{OuterConstant:n}=this._core;return{conversationID:`${n.CONV_GROUP}${e.groupID}`,type:n.CONV_GROUP,lastMessage:Object.assign(Object.assign({lastTime:e.time,lastSequence:e.sequence,fromAccount:e.msgGroupFromAccount},this._patchTypeAndPayload(e)),{cloudCustomData:(null===(t=e.lastMsg)||void 0===t?void 0:t.cloudCustomData)||"",isRevoked:e.lastMessageFlag===Vi.GROUP,onlineOnlyFlag:!1,nick:e.msgGroupFromNickName||"",nameCard:e.msgGroupFromCardName||"",revoker:(null===(o=null===(s=e.lastMsg)||void 0===s?void 0:s.revokerInfo)||void 0===o?void 0:o.revoker)||null}),groupProfile:{groupID:e.groupID,name:e.groupNick,avatar:e.groupImage,type:e.groupType,nextMessageSeq:e.nextMessageSeq},unreadCount:this._computeGroupUnreadCount(e),peerReadTime:0,isPinned:1===e.isPinned,version:0,customData:e.customMark||"",markList:ki(e.standardMark),conversationGroupList:[],messageRemindType:this._transMsgRemindType(e.messageRemindType),subType:e.groupType}}_convertConversationKey(e){return e.map((e=>({type:e.Type,userID:e.To_Account,nick:e.C2cNick,peerAvatar:e.C2cImage,time:e.MsgTimeStamp,sequence:e.MsgSeq,lastC2CMsgFromAccount:e.LastC2cMsgFrom_Account,lastMsg:this._convertLastMsgKey(e.LastMsg),lastMessageFlag:e.LastMsgFlags,c2cPeerReadTime:e.LastC2cMsgPeerReadTime,peerReadTime:e.C2cPeerReadTime,friendRemark:e.C2cRemark,isPinned:e.TopFlags,standardMark:e.StandardMark,customMark:e.CustomMark,messageRemindType:e.MsgRecvOption,groupID:e.ToAccount,groupNick:e.GroupNick,groupImage:e.GroupImage,groupType:e.GroupType,nextMessageSeq:e.GroupNextMsgSeq,msgGroupFromAccount:e.MsgGroupFrom_Account,msgGroupFromNickName:e.MsgGroupFromNickName,MsgGroupFromCardName:e.MsgGroupFromCardName,unreadCount:e.UnreadMsgCount,noUnreadCount:e.GroupIgnoredUnreadSeqCount})))}_convertLastMsgKey(e){var t,s,o,n;if(null===(s=null===(t=this._core)||void 0===t?void 0:t.helper)||void 0===s?void 0:s.isEmpty(e))return null;let i="",r=null;return e.MsgBody&&(i=null===(o=e.MsgBody[0])||void 0===o?void 0:o.MsgType,r=this._parseContent(i,e.MsgBody[0])),{event:e.Event,elements:[{type:i,content:r,cloudCustomData:e.CloudCustomData}],revokerInfo:{revoker:null===(n=e.RevokerInfo)||void 0===n?void 0:n.revoker}}}_parseContent(e,t){var s;if(!t)return t;const o=this._core.message.messageFactory.getElementClass(e);return o?null===(s=o.parseServerPushElement(t))||void 0===s?void 0:s.content:t}_amendLayersOverLimitProp(e){const{LayersOverLimit:t}=e;return r(e,["LayersOverLimit"]).layersOverLimit=1===t,e}_transMsgRemindType(e){const{OuterConstant:t}=this._core;let s="";return 0===e?s=t.MSG_REMIND_ACPT_AND_NOTE:1===e?s=t.MSG_REMIND_DISCARD:2===e?s=t.MSG_REMIND_ACPT_NOT_NOTE:3===e&&(s=t.NOT_RECEIVE_OFFLINE_PUSH_EXCEPT_AT),s}_patchTypeAndPayload(e){const{OuterConstant:t,utils:{isUndefined:s}}=this._core,{event:o,elements:n=[]}=e.lastMsg||{};return s(o)?{type:n[0]?n[0].type:null,payload:n[0]?this._amendLayersOverLimitProp(n[0].content):null}:{type:t.MSG_GRP_TIP,payload:{}}}_computeGroupUnreadCount(e){const{unreadCount:t=0,noUnreadCount:s=0}=e,o=t-s;return o>0?o:0}_dispose(){const{notificationCenter:e,InnerEvent:t}=this._core;e.unSubscribeInnerEvent(t.DESTROY,this._dispose,this)}};var Ji=new class{constructor(){this._name="GetConversationList"}init(e){this._core=e;const{helper:t}=e;t.registerApi({apiName:"getConversationList",context:this})}getConversationList(e){return a(this,void 0,void 0,(function*(){return{code:0,data:{conversationList:this._getConversationList(e),isSyncCompleted:zi.isSyncCompleted()}}}))}_getConversationList(e){const{utils:{isUndefined:t,isArray:s,isPlainObject:o}}=this._core;if(t(e))return Hi.getLocalConversationList();if(s(e)){if(0===e.length)return[];return Hi.getLocalConversationList().filter((t=>e.includes(t.conversationID)))}if(o(e)){const{type:t,markType:s,groupName:o,hasUnreadCount:n,hasGroupAtInfo:i}=e;return Hi.getLocalConversationList().filter((e=>this._filterType(e,t)&&this._filterMarkType(e,s)&&this._filterGroupName(e,o)&&this._filterUnreadCount(e,n)&&this._filterGroupAtInfo(e,i)))}return[]}_filterType(e,t){const{OuterConstant:s}=this._core;return t!==s.CONV_C2C&&t!==s.CONV_GROUP||e.type===t}_filterGroupName(e,t){const{utils:{isString:s}}=this._core;return!s(t)||(""===t?0===e.conversationGroupList.length:e.conversationGroupList.includes(t))}_filterMarkType(e,t){const{utils:{isNumber:s}}=this._core;return!s(t)||(0===t?0===e.markList.length:e.markList.includes(t))}_filterUnreadCount(e,t){let s=!0;return!0===t?s=e.unreadCount>=1:!1===t&&(s=0===e.unreadCount),s}_filterGroupAtInfo(e,t){let s=!0;return!0===t?s=e.groupAtInfoList.length>=1:!1===t&&(s=0===e.groupAtInfoList.length),s}};function Zi(e,t,s){return a(this,void 0,void 0,(function*(){const{helper:o,channel:n}=s,i=o.generateProtocolData({servcmd:e,data:t}),r=`${i.head.seq}${e}`;return yield n.sendPacket(i,{requestId:r})}))}var Xi=new class{constructor(){this._name="GetC2CMessageRemindType"}init(e){this._core=e}get(e){return a(this,void 0,void 0,(function*(){try{const{common:t}=this._core,s=yield function(e,t){return a(this,void 0,void 0,(function*(){const{toAccount:s,userIDList:o}=e;return Zi("openim.get_c2c_peer_mute_notifications",{To_Account:s,Peer_Account:o},t)}))}({toAccount:t.getCurrentUserID(),userIDList:e},this._core),{MuteNotificationsList:o=[]}=s||{};o.forEach((e=>{const{Peer_Account:t,MuteNotifications:s}=e,o=`${this._core.OuterConstant.CONV_C2C}${t}`,n=Fi(s);Hi.patchMessageRemindType([o],n)}))}catch(e){console.error(`${this._name}.get fail:`,e)}}))}};var Qi=new class{constructor(){this._name="GetGroupMessageRemindType"}init(e){this._core=e}get(e){return a(this,void 0,void 0,(function*(){if(0!==e.length)try{const t=yield function(e,t){return a(this,void 0,void 0,(function*(){const{groupIDList:s,responseFilter:o}=e;return Zi("group_open_http_svc.get_group_self_member_info",{GroupIdList:s,ResponseFilter:o},t)}))}({groupIDList:e,responseFilter:{MemberInfoFilter:["MsgFlag"]}},this._core),{GroupInfo:s=[]}=t||{};s.forEach((e=>{var t;const{GroupId:s,MemberList:o}=e,n=(null===(t=o[0])||void 0===t?void 0:t.MsgFlag)||"",i=`${this._core.OuterConstant.CONV_GROUP}${s}`;Hi.patchMessageRemindType([i],n)}))}catch(e){console.error(`${this._name}.get fail:`,e)}}))}};var er=new class{constructor(){this._name="GetConversationProfile"}init(e){this._core=e;const{helper:t}=e;t.registerApi({apiName:"getConversationProfile",context:this})}getConversationProfile(e){return a(this,void 0,void 0,(function*(){const{OuterConstant:{CONV_C2C:t,CONV_GROUP:s,GRP_AVCHATROOM:o},appStore:{groupStore:n},utils:{isEmpty:i}}=this._core,r={code:0,data:{}};let a=Hi.getLocalConversation(e);if(Ui(e))return r.data.conversation=a,r;let c=!1;const l=wi(e)?t:s;if(i(a)&&(c=!0,a=new Ki({conversationID:e,type:l})),console.log(`${this._name}.getConversationProfile conversationID:${e} isNewConversation:${c}`),r.data.conversation=a,null==a?void 0:a.getProfileCompleted())return r;if(l===t){const s=e.replace(t,"");yield this._handleC2CConversation(a,s),c&&(yield Xi.get([s]))}if(l===s){const t=e.replace(s,"");if(!n.getGroup(t))return r;yield this._handleGroupConversation(a,t),c&&a.groupProfile.type!==o&&(yield Qi.get([t]))}return r}))}_handleC2CConversation(e,t){return a(this,void 0,void 0,(function*(){var s,o;const{user:n,helper:i,utils:{isEmpty:r},appStore:{conversationStore:a,userStore:c}}=this._core,{conversationID:l}=e,u=yield null===(s=n.userProfile)||void 0===s?void 0:s.getUserProfile({userIDList:[t]});if(0===(null==u?void 0:u.data.length))throw new i.ChatError({code:Wi.USER_OR_GRP_NOT_FOUND});e.userProfile=null==u?void 0:u.data[0];const d=null===(o=c.getFriend(t))||void 0===o?void 0:o.remark;r(d)||e.remark===d||(e.remark=d),e.setProfileCompleted();const h=Hi.hasLocalConversation(l);console.log(`${this._name}._handleC2CConversation conversationID:${l} hasLocalConversation: ${h}`),h?a.updateConversation(l,e):Hi.appendToPinnedConversation(e)}))}_handleGroupConversation(e,t){return a(this,void 0,void 0,(function*(){const{apiMap:{getGroupProfile:s},appStore:{conversationStore:o}}=this._core,{conversationID:n}=e,i=yield s({groupID:t});e.groupProfile=null==i?void 0:i.data.group,e.setProfileCompleted();const r=Hi.hasLocalConversation(n);console.log(`${this._name}._handleGroupConversation conversationID:${n} hasLocalConversation: ${r}`),r?o.updateConversation(n,e):Hi.appendToPinnedConversation(e)}))}};var tr=new class{init(e){const{helper:t}=e;t.registerApi({apiName:"getTotalUnreadMessageCount",context:this})}getTotalUnreadMessageCount(){return Hi.getTotalUnreadMessageCount()}};var sr=new class{constructor(){this._name="SetMessageRead"}init(e){this._core=e;const{helper:t}=e;t.registerApi({apiName:"setMessageRead",context:this})}handleC2CMessageReadSync(e){const{helper:{isEmpty:t},OuterConstant:s}=this._core;e.forEach((e=>{const{ReadC2cMsgNotify:o}=e;if(!t(o)){const{UinPairReadArray:e=[]}=o;e.forEach((e=>{const{From_Account:t,LastReadTime:o}=e,n=`${s.CONV_C2C}${t}`;console.log(`${this._name}.handleC2CMessageReadSync conversationID:${n} lastReadTime:${o}`),Hi.markMessageAsRead({conversationID:n,lastReadTime:o}),Hi.updateUnreadCount(n)}))}}))}handleGroupMessageReadSync(e){const{OuterConstant:t,utils:{isUndefined:s}}=this._core;e.forEach((e=>{const{GroupReadInfoArray:o}=e.MsgBody;s(o)||o.forEach((e=>{const{GroupId:s,LastReadMsgSeq:o}=e,n=`${t.CONV_GROUP}${s}`;console.log(`${this._name}.handleGroupMessageReadSync conversationID:${n} lastReadSequence:${o}`),Hi.markMessageAsRead({conversationID:n,lastReadSequence:o}),Hi.updateUnreadCount(n),this._clearGroupAtInfoList(n)}))}))}setMessageRead(e){return a(this,void 0,void 0,(function*(){var t,s;const{OuterConstant:o}=this._core,{conversationID:n}=e,i={code:0,data:{}},r=Hi.getLocalConversation(n);if(console.log(`${this._name}.setMessageRead conversationID:${n} unreadCount:${(null==r?void 0:r.unreadCount)||0}`),!r)return i;const a=!(null===(s=null===(t=this._core)||void 0===t?void 0:t.helper)||void 0===s?void 0:s.isEmpty(r.groupAtInfoList));if(r.type===o.CONV_GROUP&&a&&this._deleteGroupAtTips(n),0===r.unreadCount)return i;if(r.type===o.CONV_C2C){const e=this._getLocalMessageMaxTime(r);yield this._setC2CMessageRead(n,e)}if(r.type===o.CONV_GROUP){const e=this._getLocalMessageMaxSequence(r);yield this._setGroupMessageRead(n,e)}return r.type===o.CONV_SYSTEM&&(r.unreadCount=0),Hi.emitConversationListUpdate(),i}))}_deleteGroupAtTips(e){return a(this,void 0,void 0,(function*(){console.log(`${this._name}._deleteGroupAtTips conversationID:${e}`);const t=Hi.getLocalConversation(e);if(!t)return;const s=(null==t?void 0:t.groupAtInfoList)||[];if(0!==s.length)try{const{common:t}=this._core,o=s.map((e=>({From_Account:e.from,To_Account:t.getCurrentUserID(),MsgSeq:e.__sequence,MsgRandom:e.__random,GroupId:e.groupID})));yield function(e,t){return a(this,void 0,void 0,(function*(){const{messageListToDelete:s}=e;return Yi("openim.deletemsg",{DelMsgList:s},t)}))}({messageListToDelete:o},this._core),console.log(`${this._name}._deleteGroupAtTips ok. count:${s.length}`),this._clearGroupAtInfoList(e)}catch(e){console.error(`${this._name}._deleteGroupAtTips fail:`,e)}}))}_clearGroupAtInfoList(e){const t=Hi.getLocalConversation(e);if(!t)return;let s=!1;t.groupAtInfoList.length>0&&(t.clearGroupAtInfoList(),s=!0,console.log(`${this._name}._clearGroupAtInfoList conversationID:${e} needEmitConversationUpdate:${s}`)),s&&Hi.emitConversationListUpdate()}_getLocalMessageMaxTime(e){var t;const{conversationID:s}=e,o=this._core.message.messageDataHandler.getLocalMessageList(s),n=Math.max(...o.map((e=>e.time)));let i=(null===(t=null==e?void 0:e.lastMessage)||void 0===t?void 0:t.lastTime)||0;return n>i&&(console.log(`${this._name}._getLocalMessageMaxTime update lastMessageTime from ${i} to ${n}`),i=n),i}_getLocalMessageMaxSequence(e){var t;const{conversationID:s}=e,o=this._core.message.messageDataHandler.getLocalMessageList(s),n=Math.max(...o.map((e=>e.sequence)));let i=(null===(t=null==e?void 0:e.lastMessage)||void 0===t?void 0:t.lastSequence)||0;return n>i&&(console.log(`${this._name}._getLocalMessageMaxSequence update lastMessageSequence from ${i} to ${n}`),i=n),i}_setC2CMessageRead(e,t){return a(this,void 0,void 0,(function*(){try{yield function(e,t){return a(this,void 0,void 0,(function*(){return Yi("openim.msgreaded",e,t)}))}({C2CMsgReaded:{Cookie:"",C2CMsgReadedItem:[{To_Account:e.replace("C2C",""),LastedMsgTime:t,Receipt:1}]}},this._core),console.log(`${this._name}._setC2CMessageRead ok, lastReadTime:${t}`),Hi.markMessageAsRead({conversationID:e,lastReadTime:t}),Hi.updateUnreadCount(e)}catch(e){throw console.warn(`${this._name}._setC2CMessageRead fail:`,e),e}}))}_setGroupMessageRead(e,t){return a(this,void 0,void 0,(function*(){try{yield function(e,t){return a(this,void 0,void 0,(function*(){const{groupID:s,lastMessageSequence:o}=e;return Yi("group_open_http_svc.msg_read_report",{GroupId:s,MsgReadedSeq:o},t)}))}({groupID:e.replace("GROUP",""),lastMessageSequence:t},this._core),console.log(`${this._name}._setGroupMessageRead ok, lastReadSequence:${t}`),Hi.markMessageAsRead({conversationID:e,lastReadSequence:t}),Hi.updateUnreadCount(e)}catch(e){throw console.warn(`${this._name}._setGroupMessageRead fail:`,e),e}}))}};var or=new class{constructor(){this._name="PinConversation"}init(e){this._core=e;const{helper:t}=e;t.registerApi({apiName:"pinConversation",context:this})}handleConversationPinned(e,t){const{utils:{isArray:s}}=this._core;if(!s(e))return;const{OuterConstant:o}=this._core;let n=!1;e.forEach((e=>{const{Type:s,To_Account:i,GroupId:r}=e;let a;1===s?a=Hi.getLocalConversation(`${o.CONV_C2C}${i}`):2===s&&(a=Hi.getLocalConversation(`${o.CONV_GROUP}${r}`)),a&&(console.log(`${this._name}.handleConversationPinned conversationID:${a.conversationID} localPinned:${a.isPinned} remotePinned:${t}`),t&&!a.isPinned&&(a.isPinned=!0,n=!0),!t&&a.isPinned&&(a.isPinned=!1,n=!0))})),n&&Hi.emitConversationListUpdate(!0)}pinConversation(e){return a(this,void 0,void 0,(function*(){const{OuterConstant:t,common:s}=this._core,{conversationID:o,isPinned:n}=e,i={code:0,data:{conversationID:o}},r=Hi.getLocalConversation(o);if(r&&r.isPinned===n)return i;if(Ui(o))return r&&(r.isPinned=n),Hi.emitConversationListUpdate(!0),i;try{let e=null;wi(o)?e={Type:1,To_Account:o.replace(t.CONV_C2C,"")}:Pi(o)&&(e={Type:2,GroupId:o.replace(t.CONV_GROUP,"")});const c=yield function(e,t){return a(this,void 0,void 0,(function*(){const{fromAccount:s,operationType:o,itemList:n}=e;return Yi("recentcontact.top",{From_Account:s,OperationType:o,RecentContactItem:n},t)}))}({fromAccount:s.getCurrentUserID(),operationType:!0===n?1:2,itemList:[e]},this._core);if(console.log(`${this._name}.pinConversation ok, conversationID:${o} isPinned:${n}.`),c){if(r)r.isPinned!==n&&(r.isPinned=n);else{const e=new Ki({conversationID:o,type:wi(o)?t.CONV_C2C:t.CONV_GROUP,isPinned:n});Hi.setLocalConversation(o,e)}Hi.emitConversationListUpdate(!0)}return i}catch(e){throw console.error(`${this._name}.pinConversation fail:`,e),e}}))}};var nr=new class{constructor(){this._name="DeleteConversation"}init(e){this._core=e;const{helper:t}=e;t.registerApi({apiName:"deleteConversation",context:this})}handleConversationDeleted(e){const{utils:{isArray:t}}=this._core;if(!t(e))return;const{OuterConstant:s}=this._core,o=[];e.forEach((e=>{const{Type:t,Peer_Account:n,GroupId:i}=e;1===t&&o.push(`${s.CONV_C2C}${n}`),2===t&&o.push(`${s.CONV_GROUP}${i}`)})),console.log(`${this._name}.handleConversationDeleted conversationIDList:${o}`),this._deleteLocalConversationList(o)}deleteConversation(e){return a(this,void 0,void 0,(function*(){const{utils:{isString:t}}=this._core;if(t(e))return console.log(`${this._name}.deleteConversation conversationID:${e}`),void(yield this._deleteConversation({conversationIDList:[e],flag:Bi.ONLY_CONVERSATIONID}));const s=Object.assign({},e);s.conversationIDList.length>100&&(s.conversationIDList=s.conversationIDList.slice(0,100)),yield this._deleteConversation(s)}))}_deleteConversation(e){return a(this,void 0,void 0,(function*(){const{conversationIDList:t,clearHistoryMessage:s=!0,flag:o=0}=e;console.log(`${this._name}._deleteConversation conversationIDList:${t} clearHistoryMessage:${s}`);try{const e=yield Promise.all([this._deleteConversationFromLocal(t),this._deleteConversationFromServer(t,s)]),n=[...e[0],...e[1]];if(0===n.length)throw new this._core.helper.ChatError({code:Wi.CONV_NOT_FOUND});return console.log(`${this._name}._deleteConversation ok.`),{code:0,data:o===Bi.ONLY_CONVERSATIONID?{conversationID:n[0]}:{conversationIDList:n}}}catch(e){throw console.error(`${this._name}._deleteConversation fail:`,e),e}}))}_deleteConversationFromLocal(e){const{OuterConstant:t}=this._core;return e.filter((e=>{var s;if(!Hi.hasLocalConversation(e))return!1;const o=null===(s=Hi.getLocalConversation(e))||void 0===s?void 0:s.type;return o!==t.CONV_GROUP||this._hasLocalGroup(e)?o===t.CONV_SYSTEM&&(this._deleteLocalConversation(e),!0):(this._deleteLocalConversation(e),!0)}))}_deleteConversationFromServer(e,t){return a(this,void 0,void 0,(function*(){const{OuterConstant:s,common:o}=this._core,n={fromAccount:o.getCurrentUserID(),conversationList:[],clearHistoryMessage:t?1:0};if(e.forEach((e=>{var t;if(Hi.hasLocalConversation(e)){const o=(null===(t=Hi.getLocalConversation(e))||void 0===t?void 0:t.type)||"",i=e.replace(o,"");o===s.CONV_C2C?n.conversationList.push({To_Account:i,Type:1}):o===s.CONV_GROUP&&this._hasLocalGroup(e)&&n.conversationList.push({ToGroupid:i,Type:2})}})),0===n.conversationList.length)return[];const i=yield function(e,t){return a(this,void 0,void 0,(function*(){const{fromAccount:s,conversationList:o,clearHistoryMessage:n}=e;return Yi("recentcontact.batch_delete",{From_Account:s,ContactItem:o,ClearRamble:n},t)}))}(n,this._core);if(i){const{ResultItem:e=[]}=i,t=[];return e.length>0&&e.forEach((e=>{if(0===e.ResultCode){const o=1===e.type?`${s.CONV_C2C}${e.To_Account}`:`${s.CONV_GROUP}${e.ToGroupid}`;t.push(o)}})),this._deleteLocalConversationList(t),t}return[]}))}_deleteLocalConversationList(e){let t=!1;e.forEach((e=>{Hi.hasLocalConversation(e)&&(this._deleteLocalConversation(e,!1),t=!0)})),console.log(`${this._name}._deleteLocalConversationList isUpdate:${t}`),t&&Hi.emitConversationListUpdate()}_deleteLocalConversation(e,t=!0){const s=Hi.hasLocalConversation(e);console.log(`${this._name}._deleteLocalConversation conversationID:${e} has:${s}`),s&&(Hi.deleteLocalConversation(e),this._deleteConversationLocalMessage(e),t&&Hi.emitConversationListUpdate())}_hasLocalGroup(e){const{OuterConstant:{CONV_GROUP:t},appStore:{groupStore:s}}=this._core,o=e.replace(t,"");return!!s.getGroup(o)}_deleteConversationLocalMessage(e){console.log(`${this._name}._deleteConversationLocalMessage conversationID:${e}`),this._core.message.messageDataHandler.deleteConversationMessageList(e)}};var ir=new class{constructor(){this._name="SetConversationDraft"}init(e){this._core=e;const{helper:t}=e;t.registerApi({apiName:"setConversationDraft",context:this})}setConversationDraft(e){return a(this,void 0,void 0,(function*(){const{conversationID:t,draftText:s}=e;if(console.log(`${this._name} conversationID:${t} draftText:${s}`),!Hi.hasLocalConversation(t))throw new this._core.helper.ChatError({code:Wi.CONV_NOT_FOUND});const o=Hi.getLocalConversation(t);return null==o||o.setDraftText(s),Hi.emitConversationListUpdate(),{code:0,data:{conversation:o}}}))}};var rr=new class{constructor(){this._name="SetC2CMessageRemindType"}init(e){this._core=e}set(e,t){return a(this,void 0,void 0,(function*(){e.length>30&&(console.warn(`${this._name}.set userIDList length:${e.length} exceeds limit 30`),e.splice(30));const s=function(){const{MSG_REMIND_ACPT_AND_NOTE:e,MSG_REMIND_DISCARD:t,MSG_REMIND_ACPT_NOT_NOTE:s}=bi.core.OuterConstant;return{[e]:0,[t]:1,[s]:2}}()[t],o=yield function(e,t){return a(this,void 0,void 0,(function*(){const{userIDList:s,receiveMessageOption:o}=e;return Zi("openim.set_c2c_peer_mute_notifications",{Peer_Account:s,Mute_Notifications:o},t)}))}({userIDList:e,receiveMessageOption:s},this._core),{ErrorList:n=[]}=o||{},i=[];n.forEach((t=>{const{Peer_Account:s,ErrorCode:o}=t;i.push({userID:s,code:o});const n=e.indexOf(s);n>-1&&e.splice(n,1)}));const r=[],c=[],{OuterConstant:l}=this._core;return e.forEach((e=>{c.push(`${l.CONV_C2C}${e}`),r.push({userID:e})})),Hi.patchMessageRemindType(c,t),{code:0,data:{successUserIDList:r,failureUserIDList:i}}}))}};var ar=new class{constructor(){this._name="SetGroupMessageRemindType"}init(e){this._core=e}set(e,t){return a(this,void 0,void 0,(function*(){const{common:s,OuterConstant:o}=this._core;yield function(e,t){return a(this,void 0,void 0,(function*(){const{groupID:s,userID:o,receiveMessageOption:n}=e;return Zi("group_open_http_svc.modify_group_member_info",{GroupId:s,Member_Account:o,MsgFlag:n},t)}))}({groupID:e,userID:s.getCurrentUserID(),receiveMessageOption:t},this._core);const n=`${o.CONV_GROUP}${e}`;return Hi.patchMessageRemindType([n],t),{code:0,data:{groupID:e,messageRemindType:t}}}))}};var cr=new class{constructor(){this._name="SetMessageRemindType"}init(e){this._core=e;const{helper:t}=e;t.registerApi({apiName:"setMessageRemindType",context:this})}handleC2CMessageRemindTypeSync(e){const{helper:{isEmpty:t},OuterConstant:s}=this._core;e.forEach((e=>{const{MuteNotificationsSync:o}=e;if(!t(o)){const{To_Account:e,MuteNotifications:t}=o,n=e.map((e=>`${s.CONV_C2C}${e}`)),i=Fi(t);console.log(`${this._name}.handleC2CMessageRemindTypeSync conversationIDList:${n} messageRemindType:${i}`),Hi.patchMessageRemindType(n,i)}}))}setMessageRemindType(e){return a(this,void 0,void 0,(function*(){const t="setMessageRemindType",{groupID:s,userIDList:o,messageRemindType:n}=e,{helper:i,utils:{isUndefined:r}}=this._core;try{if(!r(s)){console.log(`${this._name}.${t} groupID:${s} messageRemindType:${n}`);return yield ar.set(s,n)}if(!r(o)){console.log(`${this._name}.${t} userIDList:${o} messageRemindType:${n}`);return yield rr.set(o,n)}throw new i.ChatError({functionName:t,message:"userIDList or groupID is required"})}catch(e){const s=new i.ChatError({functionName:t,code:null==e?void 0:e.errorCode,message:null==e?void 0:e.errorInfo});throw console.error(`${this._name}.${t} fail:`,s),s}}))}};var lr=new class{init(e){console.log("ConversationAction.init"),this._core=e,zi.init(e),Ji.init(e),er.init(e),tr.init(e),sr.init(e),or.init(e),nr.init(e),ir.init(e),cr.init(e);const{notificationCenter:t,InnerEvent:{MESSAGE_PUSH:s,DESTROY:o}}=this._core,{InnerEventSubType:{CONV_MODIFIED:n,C2C_MESSAGE_READ_SYNC:i,GROUP_MESSAGE_READ_SYNC:r,C2C_REMIND_TYPE_SYNC:a}}=t;t.subscribeInnerEvent(s,n,this._onConversationModified,this),t.subscribeInnerEvent(s,i,this._onC2CMessageReadSync,this),t.subscribeInnerEvent(s,a,this._onC2CMessageRemindTypeSync,this),t.subscribeInnerEvent(s,r,this._onGroupMessageReadSync,this),t.subscribeInnerEvent(o,this._dispose,this)}handleLoginSuccess(){zi.handleLoginSuccess()}_onConversationModified(e){const{RecentContactMod:t=[]}=e;t.forEach((e=>{const{PushType:t}=e;if(t===ji.CONV_DELETED){const{RecentContactList:t}=e.RecentContactDeleteItem;nr.handleConversationDeleted(t)}if(t===ji.CONV_PINED){const{RecentContactList:t}=e.RecentContactTopItem;or.handleConversationPinned(t,!0)}if(t===ji.CONV_UNPINED){const{RecentContactList:t}=e.RecentContactTopItem;or.handleConversationPinned(t,!1)}}))}_onC2CMessageReadSync(e){const{C2cNotifyMsgArray:t=[]}=e;sr.handleC2CMessageReadSync(t)}_onC2CMessageRemindTypeSync(e){const{C2cNotifyMsgArray:t=[]}=e;cr.handleC2CMessageRemindTypeSync(t)}_onGroupMessageReadSync(e){const{GroupTips:t=[]}=e;sr.handleGroupMessageReadSync(t)}_dispose(){const{notificationCenter:e,InnerEvent:{MESSAGE_PUSH:t,DESTROY:s}}=this._core,{InnerEventSubType:{CONV_MODIFIED:o,C2C_MESSAGE_READ_SYNC:n,GROUP_MESSAGE_READ_SYNC:i,C2C_REMIND_TYPE_SYNC:r}}=e;e.unSubscribeInnerEvent(t,o,this._onConversationModified,this),e.unSubscribeInnerEvent(t,n,this._onC2CMessageReadSync,this),e.unSubscribeInnerEvent(t,r,this._onC2CMessageRemindTypeSync,this),e.unSubscribeInnerEvent(t,i,this._onGroupMessageReadSync,this),e.unSubscribeInnerEvent(s,this._dispose,this)}};var ur=new class{init(e){console.log("ReceiveMessageOptions.init"),this._core=e,rr.init(e),ar.init(e),Xi.init(e),Qi.init(e)}};const dr=e=>!wi(e)&&!Pi(e)&&!Ui(e),hr={getConversationProfile:[{key:"conversationID",required:!0,rules:["string"],allowEmpty:!1,customValidator:e=>!dr(e)||"conversationID is invalid."}],setMessageRead:{conversationID:{required:!0,rules:["string"],allowEmpty:!1,customValidator:e=>!dr(e)||"conversationID is invalid."}},pinConversation:{conversationID:{required:!0,rules:["string"],allowEmpty:!1,customValidator:e=>!dr(e)||"conversationID is invalid."},isPinned:{required:!0,rules:["boolean"],allowEmpty:!1}},deleteConversation:[{key:"options",required:!0,rules:["string","object"],allowEmpty:!1,customValidator:e=>{const{core:{utils:{isArray:t,isObject:s,isString:o}}}=bi;if(!o(e)&&!s(e))return"options is String or Object.";if(o(e)&&dr(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(dr(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=>!(!wi(e)&&!Pi(e))||"conversationID is invalid."},draftText:{required:!0,rules:["string"],allowEmpty:!0}}},pr={getConversationList:!0,getConversationProfile:!0,getTotalUnreadCount:!0,setMessageRead:!0,pinConversation:!0,deleteConversation:!0,setConversationDraft:!0,setMessageRemindType:!0};var gr=new class{install(e){bi.init(e),lr.init(e),ur.init(e),Hi.init(e),e.helper.registerValidateConfig({auth:pr,params:hr})}handleLoginSuccess(){lr.handleLoginSuccess()}};const _r=new class{init(e){this.core=e}},mr="AVChatRoom",fr="AV_HISTORY_MSG",vr=["Type","Name","Introduction","Notification","FaceUrl","Owner_Account","CreateTime","InfoSeq","LastInfoTime","LastMsgTime","MemberNum","MaxMemberNum","ApplyJoinOption","NextMsgSeq","ShutUpAllMember","InviteJoinOption","LastRecallTime"],Ir=["Type","Name","Introduction","Notification","FaceUrl","CreateTime","Owner_Account","LastInfoTime","LastMsgTime","NextMsgSeq","MemberNum","MaxMemberNum","ApplyJoinOption","InviteJoinOption"],Sr=["Role","JoinTime","MsgFlag","MsgSeq"],Er=["Role","JoinTime","MsgSeq","MsgFlag","NameCard"],Cr=0,yr=1,Mr="notStart",Ar="resolved",Or="rejected",Tr=10018,Dr=11e3,Rr=2,Lr=["Owner","Admin","Member"],Nr=["Role","JoinTime","NameCard","ShutUpUntil","OnlineStatus"],br=0,wr=1,Pr=2,Ur=4,Gr=1,kr=2,Fr=3,$r=4,qr=5,xr=1,Vr=0,Br=4,jr=6,Wr=1,Kr=2,Hr=3,Yr=4,zr=5,Jr=6,Zr=400,Xr=300,Qr={from:!0,groupID:!0,groupName:!0,to:!0},ea={from:!0,groupID:!0,groupName:!0,to:!0,type:!0},ta=2,sa=4,oa=5,na=7,ia=8,ra=15,aa=20,ca=21,la=2600,ua=2602,da=2603,ha=2620,pa=2621,ga=2623,_a=2660,ma=2661,fa=2681,va=2683,Ia=2684,Sa=2685,Ea=2687,Ca=e=>e===_r.core.OuterConstant.GRP_PUBLIC,ya=e=>e===_r.core.OuterConstant.GRP_AVCHATROOM,Ma=(e,t)=>{const{isArray:s}=_r.core.utils;if(!s(e)||!s(t))return!1;let o=!1;return t.forEach((({key:t,value:s})=>{const n=e.find((e=>e.key===t));n?n.value!==s&&(n.value=s,o=!0):(e.push({key:t,value:s}),o=!0)})),o},Aa=e=>{const t=[];if(!e)return t;for(let s=0,o=e.length;s<o;s++){const{Key:o,Value:n}=e[s];t.push({key:o,value:n})}return t},Oa=e=>{const t=[];for(let s=0,o=e.length;s<o;s++){const{key:o,value:n}=e[s];t.push({Key:o,Value:n})}return t},Ta=["groupID","name","avatar","type","introduction","notification","ownerID","selfInfo","createTime","infoSequence","lastInfoTime","lastMessage","nextMessageSeq","memberCount","maxMemberCount","memberList","joinOption","groupCustomField","muteAllMembers","isSupportTopic","inviteOption","_lastRevokedTime"];class Da{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._initGroup(e)}_initGroup(e){const{utils:{isString:t}}=_r.core;for(const s in e)Ta.indexOf(s)<0||("selfInfo"!==s?"isSupportTopic"!==s?"muteAllMembers"===s&&t(e[s])?this.muteAllMembers="On"===e[s]:this[s]=e[s]:this.isSupportTopic=1===e[s]:this.updateSelfInfo(e[s]))}updateGroup(e){const{utils:{isArray:t,isUndefined:s,isNumber:o,isString:n},common:{deepMerge:i}}=_r.core;e.appid=void 0,e.grossTopicNextMsgSeq=void 0,e.selfInfo&&(e.selfInfo.grossTopicReadSeq=void 0);const r=JSON.parse(JSON.stringify(e));r.lastMsgTime&&(this.lastMessage.lastTime=r.lastMsgTime),n(r.muteAllMembers)&&(r.muteAllMembers="On"===r.muteAllMembers),r.groupCustomField&&Ma(this.groupCustomField,r.groupCustomField),s(r.isSupportTopic)||(this.isSupportTopic=o(r.isSupportTopic)?1===r.isSupportTopic:r.isSupportTopic),i(this,r,["members","errorCode","lastMsgTime","groupCustomField","isSupportTopic"]),t(r.members)&&r.members.length>0&&r.members.forEach((e=>{e.userID===this.selfInfo.userID&&i(this.selfInfo,e,["sequence"])}))}updateSelfInfo(e){const{nameCard:t,joinTime:s,role:o,messageRemindType:n,readedSequence:i,excludedUnreadSequenceList:r}=e,{common:{deepMerge:a}}=_r.core;a(this.selfInfo,{nameCard:t,joinTime:s,role:o,messageRemindType:n,readedSequence:i,excludedUnreadSequenceList:r},[],["",null,void 0,0,NaN])}setSelfNameCard(e){this.selfInfo.nameCard=e}}var Ra=new class{constructor(){this._name="GroupDataHandler"}init(e){this._core=e;const{appStore:{groupStore:t}}=e;this._groupMap=t.getGroupMap(),console.log(`${this._name}.init`)}hasLocalGroup(e){return this._groupMap.has(e)}getLocalGroup(e){return this._groupMap.get(e)}updateLocalGroup(e){const{common:{getCurrentUserID:t}}=this._core;let s;e.forEach((e=>{var t;s=e.groupID,this.hasLocalGroup(s)?null===(t=this.getLocalGroup(s))||void 0===t||t.updateGroup(e):this._groupMap.set(s,new Da(e))}));const o=t();for(const[,e]of this._groupMap)e.selfInfo.userID=o,"Owner"===e.selfInfo.role&&(e.ownerID=o)}deleteLocalGroup(e){this._groupMap.delete(e)}getLocalGroupList(){return[...this._groupMap.values()]}clearLocalGroup(){this._groupMap.clear()}emitGroupListUpdate(){const e=this.getLocalGroupList(),{OuterEvent:{GROUP_LIST_UPDATED:t},notificationCenter:s}=this._core;s.emitOuterEvent(t,{name:t,data:e})}updateConversationGroupProfile(e){const{appStore:{conversationStore:t},OuterConstant:{CONV_GROUP:s}}=this._core,o=`${s}${e}`;if(t.getConversation(o)){const s=this.getLocalGroup(e);t.updateConversation(o,{groupProfile:s})}}reset(){this.clearLocalGroup()}};function La(e,t,s){return a(this,void 0,void 0,(function*(){const{helper:o,channel:n}=s,i=o.generateProtocolData({servcmd:e,data:t}),r=`${i.head.seq}${e}`;return yield n.sendPacket(i,{requestId:r})}))}const Na=function(e){return{code:0,data:e||{}}};var ba=new class{constructor(){this._name="GetGroupList",this._pagingStatus=Mr,this.PAGING_GRP_COUNT_LIMIT=200}init(e){this._core=e;const{helper:t,constants:{WORKFLOW_NAME:s,WORKFLOW_STEP:o}}=e;t.registerApi({apiName:"getGroupList",context:this}),t.registerWorkflowStep(s.SYNC_SERVER_INFO_AFTER_LOGIN,o.GROUP_LIST_SYNC,this._syncGroupList,this)}getGroupList(){return a(this,void 0,void 0,(function*(){if(console.log(`${this._name}.getGroupList pagingStatus:${this._pagingStatus}`),this._pagingStatus===Or||this._pagingStatus===Mr)return this._syncGroupList().then((()=>{const e=Ra.getLocalGroupList();return Na({groupList:e,isSyncCompleted:this._isSyncCompleted()})})).catch((e=>{throw console.error(`${this._name}.getGroupList fail:`,e),e}));const e=Ra.getLocalGroupList();return console.log(`${this._name}.getGroupList return group count:${e.length}`),Na({groupList:e,isSyncCompleted:this._isSyncCompleted()})}))}_syncGroupList(){return a(this,void 0,void 0,(function*(){this._pagingStatus===Mr&&Ra.clearLocalGroup();const e=this.PAGING_GRP_COUNT_LIMIT,t=[];try{yield this._pagingGetGroupList({limit:e,offset:0,groupList:t}),this._pagingStatus=Ar,this._groupListTreeShaking(t),Ra.updateLocalGroup(t);const s=Ra.getLocalGroupList();return console.log(`${this._name}._syncGroupList ok, count:${s.length}`),Ra.emitGroupListUpdate(),s}catch(e){throw this._pagingStatus=Or,console.error(`${this._name}._syncGroupList fail:`,e),e}}))}_pagingGetGroupList(e){return a(this,void 0,void 0,(function*(){const{isCommunityRelay:t=!1,groupList:s}=e;let o,{limit:n,offset:i}=e;const r=[...vr];t&&(o=this._core.OuterConstant.GRP_COMMUNITY,r.push("AtInfoList"));try{const e=yield function(e,t){return a(this,void 0,void 0,(function*(){const{type:s,limit:o,offset:n,memberAccount:i,responseFilter:r}=e;return La(s?"million_group_open_http_svc.get_joined_group_list":"group_open_http_svc.get_joined_group_list",{Limit:o,Offset:n,Member_Account:i,ResponseFilter:r,SupportTopic:0,NeedAppDefineData:1},t)}))}({type:o,limit:n,offset:i,memberAccount:this._core.store.get("login").userId,responseFilter:{GroupBaseInfoFilter:r,SelfInfoFilter:[...Sr]}},this._core),{GroupIdList:c=[],TotalCount:l=0}=e||{},u=this._convertGroupKey(c);s.push(...u);const d=i+n,h=!(l>d),p=`offset:${i} limit:${n} total:${l} isCompleted:${h} current:${s.length} isCommunityRelay:${t}`;return console.log(`${this._name}._pagingGetGroupList ok. ${p}`),t?h?s:(i=d,this._pagingGetGroupList({isCommunityRelay:!0,limit:n,offset:i,groupList:s})):h?(console.log(`${this._name}._pagingGetGroupList start to get community list`),i=0,this._pagingGetGroupList({isCommunityRelay:!0,limit:n,offset:i,groupList:s})):(i=d,this._pagingGetGroupList({limit:n,offset:i,groupList:s}))}catch(e){if(e.ErrorCode===Tr)return console.warn(`${this._name}._pagingGetGroupList response size exceeds the limit, request count:${n}`),n=50,this._pagingGetGroupList({isCommunityRelay:t,limit:n,offset:i,groupList:s});if(t)return e.code===Dr&&console.log(`${this._name}._pagingGetGroupList ok. community unavailable`),s;throw e}}))}_groupListTreeShaking(e){const t=new Map([...Ra.getLocalGroupList()]);for(let s=0,o=e.length;s<o;s++)t.delete(e[s].groupID);const s=[...t.keys()];for(let e=0,t=s.length;e<t;e++)Ra.deleteLocalGroup(s[e])}_isSyncCompleted(){return this._pagingStatus===Ar}_convertGroupKey(e){const t=[];for(let s=0,o=e.length;s<o;s++){const{AppDefinedData:o,ApplyJoinOption:n,CreateTime:i,FaceUrl:r,GroupId:a,Introduction:c,InviteJoinOption:l,LastInfoTime:u,LastMsgTime:d,MemberNum:h,MaxMemberNum:p,MuteAllMember:g,Name:_,NextMsgSeq:m,Notification:f,Owner_Account:v,Type:I,LastRecallTime:S,SelfInfo:E}=e[s],C=Aa(o),y=this._convertSelfInfo(E);t.push({groupCustomField:C,joinOption:n,createTime:i,avatar:r,groupID:a,introduction:c,inviteOption:l,lastInfoTime:u,lastMsgTime:d,memberCount:h,maxMemberCount:p,muteAllMembers:g,name:_,nextMessageSeq:m,notification:f,ownerID:v,type:I,_lastRevokedTime:S,selfInfo:y})}return t}_convertSelfInfo(e){const{JoinTime:t,MsgFlag:s,MsgSeq:o,NoUnreadSeqList:n,Role:i}=e;return{joinTime:t,messageRemindType:s,readedSequence:o,excludedUnreadSequenceList:n,role:i}}};var wa=new class{constructor(){this._name="CreateGroup"}init(e){this._core=e;const{helper:t}=e;t.registerApi({apiName:"createGroup",context:this})}createGroup(e){return a(this,void 0,void 0,(function*(){var t;this._preCheckParams(e),console.log(`${this._name}.createGroup options:`,e);try{const{utils:{isEmpty:s},common:{getCurrentUserID:o}}=this._core,n=yield function(e,t){return a(this,void 0,void 0,(function*(){const{name:s,type:o,groupID:n,introduction:i,notification:r,avatar:a,maxMemberNum:c,joinOption:l,inviteOption:u,memberList:d,groupCustomField:h,isSupportTopic:p}=e;let g;return d&&(g=d.map((e=>{const{userID:t,memberCustomField:s}=e;return{Member_Account:t,AppMemberDefinedData:s?Oa(s):void 0}}))),La("group_open_http_svc.create_group",{Name:s,Type:o,GroupId:n,Introduction:i,Notification:r,FaceUrl:a,MaxMemberCount:c,ApplyJoinOption:l,InviteJoinOption:u,MemberList:g,AppDefinedData:h,SupportTopic:p,webPushFlag:1},t)}))}(Object.assign(Object.assign({},e),{ownerID:o()}),this._core),{GroupId:i,OverJoinedGroupLimit_Account:r=[]}=n||{};if(console.log(`${this._name}.createGroup ok, groupType:${e.type} groupID:${i} overLimitUserIDList:${r}`),s(e.memberList)||s(r)||(e.memberList=null===(t=e.memberList)||void 0===t?void 0:t.filter((e=>r.includes(e.userID)))),this._notNeedUpdateLocalGroup(e))return Na({group:new Da(e)});Ra.updateLocalGroup([Object.assign(Object.assign({},e),{groupID:i})]),this._sendCustomMessage(i,e.type);const c=Ra.getLocalGroup(i);return Ra.emitGroupListUpdate(),Na({group:c})}catch(e){throw console.error(`${this._name}.createGroup fail:`,e),e}}))}_preCheckParams(e){const{type:t,groupID:s}=e,{utils:{isEmpty:o,isUndefined:n},common:{isCommunity:i}}=this._core,r=!o(s);if(!(()=>{const{GRP_PUBLIC:e,GRP_WORK:t,GRP_MEETING:s,GRP_AVCHATROOM:o,GRP_COMMUNITY:n}=_r.core.OuterConstant;return[e,t,s,o,n]})().includes(t))throw new this._core.helper.ChatError({code:la});if(!i({type:t})){if(r&&i({groupID:s}))throw new this._core.helper.ChatError({code:ua});n(e.isSupportTopic)||(e.isSupportTopic=void 0)}if(this._canIUseMemberList(t)||n(e.memberList)||(e.memberList=void 0),this._canIUseJoinOption(t)||n(e.joinOption)||(e.joinOption=void 0),this._canIUseTopic(e)&&(e.isSupportTopic=!0===e.isSupportTopic?1:0),i({type:t})&&r&&!i({groupID:s}))throw new this._core.helper.ChatError({code:ua})}_canIUseMemberList(e){return!ya(e)}_canIUseJoinOption(e){return Ca(e)||this._core.common.isCommunity({type:e})}_canIUseTopic(e){const{type:t,isSupportTopic:s}=e,{utils:{isUndefined:o},common:{isCommunity:n}}=this._core;return n({type:t})&&o(s)}_notNeedUpdateLocalGroup(e){const{type:t,isSupportTopic:s}=e,{OuterConstant:o}=this._core;return t===o.GRP_AVCHATROOM||t===o.GRP_COMMUNITY&&1===s}_sendCustomMessage(e,t){var s,o,n,i,r,a;const{OuterConstant:c}=this._core;let l="Create Group",u=Cr;t===c.GRP_COMMUNITY&&(l="Create Community",u=yr);const d={to:e,conversationType:"GROUP",payload:{data:JSON.stringify({businessID:"group_create",content:l,cmd:u,opUser:this._core.store.get("login").userId,version:4})}},h=null===(n=null===(o=null===(s=this._core)||void 0===s?void 0:s.message)||void 0===o?void 0:o.messageFactory)||void 0===n?void 0:n.createCustomMessage(d);null===(a=null===(r=null===(i=this._core)||void 0===i?void 0:i.message)||void 0===r?void 0:r.messageSender)||void 0===a||a.sendMessage(h,{})}};var Pa=new class{constructor(){this._name="AttributesDataHandler",this._groupAttributesCache=new Map,this._groupAttributesCacheValuesCopy={}}init(e){this._core=e;const{helper:t,constants:s}=e;t.registerWorkflowStep(s.WORKFLOW_NAME.SYNC_SERVER_INFO_AFTER_RE_ONLINE,s.WORKFLOW_STEP.GROUP_ATTRIBUTE_CACHE_CLEAR,this.clearLocalMainSequence,this)}clearLocalMainSequence(){this._groupAttributesCache.forEach((e=>{e.localMainSequence=0}))}isGroupAttributesUpdated(e){const{elements:{newGroupProfile:t}}=e,{utils:{isEmpty:s,isUndefined:o}}=this._core;return!o(t)&&!s(t.groupAttributeOption)}handleGroupAttributesUpdated(e){const{groupID:t,groupAttributeOption:s}=e,{serverMainSequence:o,groupAttributeList:n=[],operation:i}=s;console.log(`${this._name}.handleGroupAttributesUpdated groupID:${t} operation:${i}`);const{utils:{isUndefined:r}}=this._core;r(i)||(this.refreshGroupAttributesCache({groupID:t,serverMainSequence:o,groupAttributeList:n,operation:i}),this.emitGroupAttributesUpdated(t))}initGroupAttributesCache(e){const{groupID:t,avChatRoomKey:s}=e;this._groupAttributesCache.set(t,{lastUpdateTime:0,localMainSequence:0,serverMainSequence:0,avChatRoomKey:s,values:new Map}),console.log(`${this._name}.initGroupAttributesCache. groupID:${t} avChatRoomKey:${s}`)}hasGroupAttributesCache(e){return this._groupAttributesCache.has(e)}getGroupAttributesCache(e){return this.hasGroupAttributesCache(e)||this.initGroupAttributesCache({groupID:e}),this._groupAttributesCache.get(e)}deleteGroupAttributesCache(e){this.hasGroupAttributesCache(e)&&this._groupAttributesCache.delete(e)}refreshGroupAttributesCache(e){const{groupID:t,serverMainSequence:s,groupAttributeList:o,operation:n}=e;if(this.hasGroupAttributesCache(t)){const e=this.getGroupAttributesCache(t),{localMainSequence:i}=e;n!==qr&&s-i!=1||(e.serverMainSequence=s,e.localMainSequence=s,e.lastUpdateTime=Date.now(),this._updateGroupAttributesCacheValues({groupAttributes:e,groupAttributeList:o,operation:n})),s-i>1&&(e.serverMainSequence=s),this._groupAttributesCache.set(t,e),console.log(`${this._name}.refreshGroupAttributesCache. operation:${n} localMainSequence:${i} serverMainSequence:${s}`)}}_updateGroupAttributesCacheValues(e){const{groupAttributes:t,groupAttributeList:s=[],operation:o}=e;o!==Fr?o!==$r?(o===Gr&&t.values.clear(),s.forEach((e=>{const{key:s,value:o,sequence:n}=e;t.values.set(s,{value:o,sequence:n})}))):s.forEach((e=>{t.values.delete(e.key)})):t.values.clear()}getGroupAttributesCacheValues(e){var t;const{groupID:s,keyList:o=[]}=e,n={};if(this.hasGroupAttributesCache(s)){const{values:e}=this.getGroupAttributesCache(s);if(0===o.length){for(const s of e.keys())n[s]=(null===(t=e.get(s))||void 0===t?void 0:t.value)||"";return n}return o.forEach((t=>{var s;e.has(t)&&(n[t]=(null===(s=e.get(t))||void 0===s?void 0:s.value)||"")})),n}return n}saveGroupAttributesCacheValuesCopy(e){this._groupAttributesCacheValuesCopy=this.getGroupAttributesCacheValues({groupID:e})}emitGroupAttributesUpdated(e){var t;const s=this.getGroupAttributesCacheValues({groupID:e}),{updatedKeyList:o,deletedKeyList:n}=this._computeValuesChangedData(s);console.log(`${this._name}.emitGroupAttributesUpdated update count:${o.length}, delete count:${n.length}`),0===o.length&&0===n.length||this._emitEvent({name:null===(t=this._core)||void 0===t?void 0:t.OuterEvent.GROUP_ATTRIBUTES_UPDATED,data:{groupID:e,groupAttributes:s,updatedKeyList:o,deletedKeyList:n}})}_computeValuesChangedData(e){const{utils:{isUndefined:t}}=this._core,s=[],o=[];return Object.keys(e).forEach((t=>{e[t]!==this._groupAttributesCacheValuesCopy[t]&&s.push(t)})),Object.keys(this._groupAttributesCacheValuesCopy).forEach((s=>{t(e[s])&&o.push(s)})),this._groupAttributesCacheValuesCopy={},{updatedKeyList:s,deletedKeyList:o}}_emitEvent(e){var t;null===(t=this._core)||void 0===t||t.notificationCenter.emitOuterEvent(e.name,e)}convertKeyValueMapToList(e){const t=[];return Object.keys(e).forEach((s=>{t.push({key:s,value:e[s]})})),t}};var Ua=new class{constructor(){this._name="DismissGroup"}init(e,t){this._core=e;const{helper:s}=e;s.registerApi({apiName:"dismissGroup",context:this,matcher:()=>!t.getInstalledSubPlugins().includes(mr)})}dismissGroup(e){return a(this,void 0,void 0,(function*(){console.log(`${this._name}.dismissGroup groupID:${e}`);try{yield function(e,t){return a(this,void 0,void 0,(function*(){return La("group_open_http_svc.destroy_group",{GroupId:e},t)}))}(e,this._core),console.log(`${this._name}.dismissGroup ok.`);const{type:t}=Ra.getLocalGroup(e);return Ra.deleteLocalGroup(e),Ra.emitGroupListUpdate(),Pa.deleteGroupAttributesCache(e),Na({groupID:e,type:t})}catch(e){throw console.error(`${this._name}.dismissGroup fail:`,e),e}}))}};var Ga=new class{constructor(){this._name="GetGroupProfile"}init(e){this._core=e;const{helper:t}=e;t.registerApi({apiName:"getGroupProfile",context:this})}getGroupProfile(e){return a(this,void 0,void 0,(function*(){const{groupID:t,groupCustomFieldFilter:s}=e,o={groupIDList:[t],responseFilter:{GroupBaseInfoFilter:[...vr],AppDefinedDataFilter_Group:s,MemberInfoFilter:[...Er]}};try{const e=yield this.getGroupProfileAdvance(o),{successGroupList:s,failureGroupList:n}=e;if(n.length>0)throw n[0];let i;return!Ra.hasLocalGroup(t)&&ya(s[0].type)?i=new Da(s[0]):(Ra.updateLocalGroup(s),i=Ra.getLocalGroup(t)),i.isSupportTopic||Ra.updateConversationGroupProfile(t),console.log(`${this._name}.getGroupProfile ok.`),Na({group:i})}catch(e){throw console.error(`${this._name}.getGroupProfile fail:`,e),e}}))}getGroupProfileAdvance(e){return a(this,void 0,void 0,(function*(){const{groupIDList:t}=e,{common:{isCommunity:s}}=this._core,o=t.filter((e=>!s({groupID:e}))),n=t.filter((e=>s({groupID:e})));o.length>50&&(o.length=50),n.length>50&&(n.length=50);const i=yield Promise.all([this._getGroupProfileAdvance(Object.assign(Object.assign({},e),{groupIDList:o})),this._getGroupProfileAdvance(Object.assign(Object.assign({},e),{groupIDList:n,isCommunityProfile:!0}))]),r=[],a=[];return i.forEach((e=>{r.push(...e.successGroupList),a.push(...e.failureGroupList)})),{successGroupList:r,failureGroupList:a}}))}_getGroupProfileAdvance(e){return a(this,void 0,void 0,(function*(){const{isCommunityProfile:t=!1}=e,s=r(e,["isCommunityProfile"]);if(0===s.groupIDList.length)return{successGroupList:[],failureGroupList:[]};try{const e=yield function(e,t){return a(this,void 0,void 0,(function*(){const{groupIDList:s,responseFilter:o}=e;return La("group_open_http_svc.get_group_self_member_info",{GroupIdList:s,ResponseFilter:o},t)}))}(s,this._core),{GroupInfo:t=[]}=e||{},o=this._convertGroupProfileKey(t),{utils:{isUndefined:n}}=this._core,i=o.filter((e=>n(e.errorCode)||0===e.errorCode)),r=o.filter((e=>e.errorCode&&0!==e.errorCode)).map((e=>({code:e.errorCode,message:e.errorInfo,data:{groupID:e.groupID}})));return console.log(`${this._name}._getGroupProfileAdvance ok, groupID:${s.groupIDList.join(",")}`),{successGroupList:i,failureGroupList:r}}catch(e){if(t)return{successGroupList:[],failureGroupList:[]};throw e}}))}_convertGroupProfileKey(e){const t=[];for(let s=0,o=e.length;s<o;s++){const{AppDefinedData:o,ApplyJoinOption:n,CreateTime:i,FaceUrl:r,GroupId:a,InfoSeq:c,Introduction:l,InviteJoinOption:u,LastInfoTime:d,LastMsgTime:h,MaxMemberNum:p,MemberNum:g,MuteAllMember:_,Name:m,NextMsgSeq:f,Notification:v,Owner_Account:I,ShutUpAllMember:S,ShutUpUntil:E,Type:C,MemberList:y,ErrorCode:M,ErrorInfo:A}=e[s],O=Aa(o),T=this._convertMembers(y);t.push({groupCustomField:O,joinOption:n,createTime:i,avatar:r,groupID:a,infoSequence:c,introduction:l,inviteOption:u,lastInfoTime:d,lastMsgTime:h,maxMemberCount:p,memberCount:g,muteAllMembers:_,name:m,nextMessageSeq:f,notification:v,ownerID:I,shutUpAllMember:S,muteUntil:E,type:C,members:T,errorCode:M,errorInfo:A})}return t}_convertMembers(e){if(!e)return[];const t=[];for(let s=0,o=e.length;s<o;s++){const{AppMemberDefinedData:o,JoinTime:n,Member_Account:i,MsgFlag:r,MsgSeq:a,NameCard:c,Role:l}=e[s],u=Aa(o);t.push({memberCustomField:u,joinTime:n,userID:i,messageRemindType:r,sequence:a,nameCard:c,role:l})}return t}};var ka=new class{constructor(){this._name="JoinGroup"}init(e,t){this._core=e;const{helper:s}=e;s.registerApi({apiName:"joinGroup",context:this,matcher:()=>!t.getInstalledSubPlugins().includes(mr)})}joinGroup(e){return a(this,void 0,void 0,(function*(){const{groupID:t}=e;try{if(Ra.hasLocalGroup(t))try{return yield Ga.getGroupProfile({groupID:t}),Na({status:this._core.OuterConstant.JOIN_STATUS_SUCCESS})}catch(s){console.warn(`${this._name}.joinGroup ${t} was unjoined, start to join!`),Ra.deleteLocalGroup(t);return yield this._applyJoinGroup(e)}return yield this._applyJoinGroup(e)}catch(e){throw console.error(`${this._name}.joinGroup fail:`,e),e}}))}_applyJoinGroup(e){return a(this,void 0,void 0,(function*(){const{OuterConstant:t,helper:s}=this._core,{groupID:o}=e,n=Object.assign({},e),i=s.checkBusinessCapabilityBits(fr);i&&(n.historyMessageFlag=1);const r=yield function(e,t){return a(this,void 0,void 0,(function*(){const{groupID:s,applyMessage:o,historyMessageFlag:n}=e;return La("group_open_http_svc.apply_join_group",{GroupId:s,ApplyMsg:o,HugeGroupHistoryMsgFlag:n},t)}))}(n,this._core),{JoinedStatus:c,LongPollingKey:l,StartSeq:u,HugeGroupFlag:d,AVChatRoomKey:h,RspMsgList:p=[]}=r||{},g=`groupID:${o} joinedStatus:${c} longPollingKey:${l} startSeq:${u} avChatRoomFlag:${d} canGetAVChatRoomHistoryMsg:${i}, historyMessageCount:${p.length}`;if(console.log(`${this._name}._applyJoinGroup ok, ${g}`),c===t.JOIN_STATUS_WAIT_APPROVAL)return{code:0,data:{status:t.JOIN_STATUS_WAIT_APPROVAL}};if(c===t.JOIN_STATUS_SUCCESS){let e=null;try{e=(yield Ga.getGroupProfile({groupID:o})).data.group}catch(t){e=new Da({groupID:o}),console.warn(`${this._name}._applyJoinGroup getGroupProfile failed, groupID: ${o}, errorCode:`,null==t?void 0:t.code)}return this._handleJoinResult({group:e,avChatRoomFlag:d,longPollingKey:l,startSequence:u,avChatRoomKey:h,historyMessageList:p})}throw new this._core.helper.ChatError({code:_a})}))}_handleJoinResult(e){const{group:t,avChatRoomFlag:s,avChatRoomKey:o}=e;return 1===s?(Pa.initGroupAttributesCache({groupID:t.groupID,avChatRoomKey:o}),Na(e)):(Ra.updateLocalGroup([t]),Ra.emitGroupListUpdate(),Na({status:this._core.OuterConstant.JOIN_STATUS_SUCCESS,group:t}))}};var Fa=new class{constructor(){this._name="QuitGroup"}init(e,t){this._core=e;const{helper:s}=e;s.registerApi({apiName:"quitGroup",context:this,matcher:()=>!t.getInstalledSubPlugins().includes(mr)})}quitGroup(e){return a(this,void 0,void 0,(function*(){if(!Ra.hasLocalGroup(e))throw new this._core.helper.ChatError({code:ga});try{yield function(e,t){return a(this,void 0,void 0,(function*(){return La("group_open_http_svc.quit_group",{GroupId:e},t)}))}(e,this._core),console.log(`${this._name}.quitGroup ok, groupID:${e}`);const{type:t}=Ra.getLocalGroup(e);return Ra.deleteLocalGroup(e),Ra.emitGroupListUpdate(),Pa.deleteGroupAttributesCache(e),Na({groupID:e,type:t})}catch(e){throw console.error(`${this._name}.quitGroup fail:`,e),e}}))}};var $a=new class{constructor(){this._name="SearchGroup"}init(e){this._core=e;const{helper:t}=e;t.registerApi({apiName:"searchGroupByID",context:this})}searchGroupByID(e){return a(this,void 0,void 0,(function*(){console.log(`${this._name}.searchGroupByID groupID:${e}`);try{const t=yield function(e,t){return a(this,void 0,void 0,(function*(){return La("group_open_http_svc.get_group_public_info",{GroupIdList:[e],GroupBasePublicInfoFilter:[...Ir]},t)}))}(e,this._core),{GroupInfo:s=[]}=t||{},{AppDefinedData:o=[],ApplyJoinOption:n,CreateTime:i,FaceUrl:r,Introduction:c,InviteJoinOption:l,MaxMemberNum:u,MemberNum:d,Name:h,Owner_Account:p,Type:g,ErrorCode:_,ErrorInfo:m}=s[0];if(0!==_)throw new this._core.helper.ChatError({code:_,message:m});console.log(`${this._name}.searchGroupByID ok.`);const f=Aa(o),v=new Da({groupID:e,name:h,avatar:r,introduction:c,joinOption:n,inviteOption:l,maxMemberCount:u,memberCount:d,type:g,ownerID:p,createTime:i,groupCustomField:f});return Na({group:v})}catch(e){throw console.error(`${this._name}.searchGroupByID fail:`,e),e}}))}};var qa=new class{constructor(){this._name="UpdateGroupProfile"}init(e){this._core=e;const{helper:t}=e;t.registerApi({apiName:"updateGroupProfile",context:this})}updateGroupProfile(e){return a(this,void 0,void 0,(function*(){const{groupID:t}=e,{utils:{isUndefined:s}}=this._core;let o=Ra.getLocalGroup(t);if(o){const{type:t}=o;this._canIUseJoinOption(t)||s(e.joinOption)||(console.warn(`${this._name}.updateGroupProfile joinOption is unavailable for Work/Meeting/AVChatRoom`),e.joinOption=void 0)}s(e.muteAllMembers)||(e.muteAllMembers=!0===e.muteAllMembers?"On":"Off");try{return yield function(e,t){return a(this,void 0,void 0,(function*(){const{groupID:s,name:o,avatar:n,introduction:i,notification:r,muteAllMembers:a,joinOption:c,inviteOption:l,groupCustomField:u}=e;return La("group_open_http_svc.modify_group_base_info",{GroupId:s,Name:o,FaceUrl:n,Introduction:i,Notification:r,ShutUpAllMember:a,ApplyJoinOption:c,InviteJoinOption:l,AppDefinedData:u?Oa(u):void 0},t)}))}(e,this._core),console.log(`${this._name}.updateGroupProfile groupID:${t} ok.`),o?(o.updateGroup(e),Ra.emitGroupListUpdate()):o=new Da(e),Na({group:o})}catch(e){throw console.error(`${this._name}.updateGroupProfile groupID:${t} fail:`,e),e}}))}_canIUseJoinOption(e){return Ca(e)||this._core.common.isCommunity({type:e})}};var xa=new class{constructor(){this._name="ChangeGroupOwner"}init(e){this._core=e;const{helper:t}=e;t.registerApi({apiName:"changeGroupOwner",context:this})}changeGroupOwner(e){return a(this,void 0,void 0,(function*(){const t="changeGroupOwner",{groupID:s,newOwnerID:o}=e,n=Ra.getLocalGroup(s),{helper:i,OuterConstant:r,common:{getCurrentUserID:c}}=this._core;if((null==n?void 0:n.type)===r.GRP_AVCHATROOM)throw new i.ChatError({functionName:t,code:ha});if(o===c())throw new i.ChatError({functionName:t,code:pa});console.log(`${this._name}.${t} groupID:${s} newOwnerID:${o}`);try{return yield function(e,t){return a(this,void 0,void 0,(function*(){const{groupID:s,newOwnerID:o}=e;return La("group_open_http_svc.change_group_owner",{GroupId:s,NewOwner_Account:o},t)}))}(e,this._core),console.log(`${this._name}.${t} ok.`),n.ownerID=o,Ra.emitGroupListUpdate(),Na({group:n})}catch(e){const s=new i.ChatError({functionName:t,code:null==e?void 0:e.errorCode,message:null==e?void 0:e.errorInfo});throw console.error(`${this._name}.${t} fail:`,s),s}}))}};var Va=new class{constructor(){this._name="GetGroupOnlineMemberCount",this._onlineMemberCountMap=new Map}init(e,t){this._core=e;const{helper:s}=e;s.registerApi({apiName:"getGroupOnlineMemberCount",context:this,matcher:()=>!t.getInstalledSubPlugins().includes(mr)})}getGroupOnlineMemberCount(e){return a(this,void 0,void 0,(function*(){const t="getGroupOnlineMemberCount",s=Ra.hasLocalGroup(e);if(console.log(`${this._name}.${t} groupID:${e} hasLocalGroup:${s}`),!s)return Na({memberCount:0});const o=Date.now();if(this._onlineMemberCountMap.has(e)){const t=this._onlineMemberCountMap.get(e),{lastReqTime:s=0,memberCount:n=0}=t||{};if(o-s<=6e4)return Na({memberCount:n})}try{const s=yield function(e,t){return a(this,void 0,void 0,(function*(){return La("group_open_http_svc.get_online_member_num",{GroupId:e},t)}))}(e,this._core),{OnlineMemberNum:o=0}=s||{};return this._onlineMemberCountMap.set(e,{lastReqTime:Date.now(),memberCount:o}),console.log(`${this._name}.${t} ok. groupID:${e} memberCount:${o}`),Na({memberCount:o})}catch(e){const s=new this._core.helper.ChatError({functionName:t,code:null==e?void 0:e.errorCode,message:null==e?void 0:e.errorInfo});throw console.error(`${this._name}.${t} fail:`,s),s}}))}};var Ba=new class{init(e,t){console.log("GroupAction.init"),ba.init(e),wa.init(e),Ua.init(e,t),ka.init(e,t),Fa.init(e,t),$a.init(e),Ga.init(e),qa.init(e),xa.init(e),Va.init(e,t)}dismissGroup(e){return Ua.dismissGroup(e)}joinGroup(e){return ka.joinGroup(e)}quitGroup(e){return Fa.quitGroup(e)}getGroupOnlineMemberCount(e){return Va.getGroupOnlineMemberCount(e)}};function ja(e,t,s){return a(this,void 0,void 0,(function*(){const{helper:o,channel:n}=s,i=o.generateProtocolData({servcmd:e,data:t}),r=`${i.head.seq}${e}`;return yield n.sendPacket(i,{requestId:r})}))}var Wa=new class{constructor(){this._name="GetGroupApplicationList"}init(e){this._core=e;const{helper:t}=e;t.registerApi({apiName:"getGroupApplicationList",context:this})}getGroupApplicationList(){return a(this,void 0,void 0,(function*(){const e="getGroupApplicationList";try{const t=yield Promise.all([this._getGroupApplicationList(),this._getGroupApplicationList({type:this._core.OuterConstant.GRP_COMMUNITY})]);console.log(`${this._name}.${e} ok.`);const s=this._handleGroupApplicationResult([...t[0],...t[1]]);return Na({applicationList:s})}catch(t){const s=new this._core.helper.ChatError({functionName:e,code:null==t?void 0:t.errorCode,message:null==t?void 0:t.errorInfo});throw console.error(`${this._name}.${e} fail:`,s),s}}))}_getGroupApplicationList(e){return a(this,void 0,void 0,(function*(){const{type:t,startTime:s=0,limit:o=20}=e||{},{common:n}=this._core;let i;try{i=yield function(e,t){return a(this,void 0,void 0,(function*(){const{type:s,startTime:o,limit:n,handleAccount:i}=e;return ja(_r.core.common.isCommunity({type:s})?"million_group_open_http_svc.get_pendency":"group_open_http_svc.get_pendency",{StartTime:o,Limit:n,Handle_Account:i},t)}))}({type:t,startTime:s,limit:o,handleAccount:n.getCurrentUserID()},this._core)}catch(e){if(11e3!==(null==e?void 0:e.errorCode))throw e;i={}}const{NextStartTime:r=0,PendencyList:c=[]}=i||{};if(0===r)return c;const l=yield this._getGroupApplicationList(Object.assign(Object.assign({},e),{startTime:r}));return[...c,...l]}))}_handleGroupApplicationResult(e){const t=[];return e.forEach((e=>{const s=this._convertApplicationData(e),{handled:o}=s,n=r(s,["handled"]);0===o&&t.push(n)})),t}_convertApplicationData(e){const{Handled:t,AddTime:s,ApplyInviteMsg:o,Authentication:n,FromUserNickName:i,From_Account:r,GroupId:a,GroupName:c,PendencyType:l,To_Account:u}=e;return{handled:t,messageKey:s,applicant:r,applicantNick:i,groupID:a,groupName:c,authentication:n,applicationType:l,userID:u,note:o}}};var Ka=new class{constructor(){this._name="HandleGroupApplication"}init(e){this._core=e;const{helper:t}=e;t.registerApi({apiName:"handleGroupApplication",context:this})}handleGroupApplication(e){return a(this,void 0,void 0,(function*(){const t="handleGroupApplication",{application:s}=e,o=this._handleParams(e);try{(null==s?void 0:s.applicationType)===Rr?yield function(e,t){return a(this,void 0,void 0,(function*(){const{groupID:s,handleAction:o,handleMessage:n,applicant:i,authentication:r,invitee:a}=e;return ja(_r.core.common.isCommunity({groupID:s})?"million_group_open_http_svc.handle_invite_join_permission_group":"group_open_http_svc.handle_invite_join_permission_group",{GroupId:s,HandleMsg:o,ApprovalMsg:n,Applicant_Account:i,Authentication:r,Invited_Account:a},t)}))}(o,this._core):yield function(e,t){return a(this,void 0,void 0,(function*(){const{groupID:s,handleAction:o,handleMessage:n,applicant:i,authentication:r,messageKey:a}=e;return ja(_r.core.common.isCommunity({groupID:s})?"million_group_open_http_svc.handle_apply_join_group":"group_open_http_svc.handle_apply_join_group",{GroupId:s,HandleMsg:o,ApprovalMsg:n,Applicant_Account:i,Authentication:r,MsgKey:a},t)}))}(o,this._core),console.log(`${this._name}.${t} ok.`);const e=Ra.getLocalGroup(o.groupID);return Na({group:e})}catch(e){const s=new this._core.helper.ChatError({functionName:t,code:null==e?void 0:e.errorCode,message:null==e?void 0:e.errorInfo});throw console.error(`${this._name}.${t} fail:`,s),s}}))}_handleParams(e){var t;const{handleAction:s,handleMessage:o,message:n,application:i}=e;let r,a,c,l,u;if(n){const{payload:e}=n||{};r=e.operatorID,a=null===(t=e.groupProfile)||void 0===t?void 0:t.groupID,c=e.authentication,l=e.messageKey}else r=(null==i?void 0:i.applicant)||"",a=(null==i?void 0:i.groupID)||"",c=(null==i?void 0:i.authentication)||"",l=(null==i?void 0:i.messageKey)||0;return(null==i?void 0:i.applicationType)===Rr&&(u=i.userID),{handleAction:s,handleMessage:o,applicant:r,invitee:u,groupID:a,authentication:c,messageKey:l}}};var Ha=new class{init(e){console.log("GroupApplication.init"),Wa.init(e),Ka.init(e)}};let Ya=class{constructor(e){this.userID="",this.avatar="",this.nick="",this.role="",this.joinTime="",this.nameCard="",this.muteUntil=0,this.memberCustomField=[],this.isOnline=!1,this.updateMember(e)}updateMember(e){const{core:{utils:{isUndefined:t},common:{deepMerge:s}}}=_r;t(e.muteTime)||(this.muteUntil=Math.floor((Date.now()+1e3*e.muteTime)/1e3)),t(e.onlineStatus)||(this.isOnline="Online"===e.onlineStatus);const o=[null,void 0,"",0,NaN];e.memberCustomField&&Ma(this.memberCustomField,e.memberCustomField),s(this,e,["memberCustomField","marks","onlineStatus","muteTime"],o)}};function za(e,t,s){return a(this,void 0,void 0,(function*(){const{helper:o,channel:n}=s,i=o.generateProtocolData({servcmd:e,data:t}),r=`${i.head.seq}${e}`;return yield n.sendPacket(i,{requestId:r})}))}function Ja(e,t){return a(this,void 0,void 0,(function*(){const{groupID:s,userID:o,muteTime:n,role:i,nameCard:r,memberCustomField:a}=e;let c;a&&(c=Oa(a));return za("group_open_http_svc.modify_group_member_info",{GroupId:s,Member_Account:o,ShutUpTime:n,Role:i,NameCard:r,AppMemberDefinedData:c},t)}))}var Za=new class{constructor(){this._name="GetGroupMemberList"}init(e,t){this._core=e;const{helper:s}=e;s.registerApi({apiName:"getGroupMemberList",context:this,matcher:()=>!t.getInstalledSubPlugins().includes(mr)})}getGroupMemberList(e){return a(this,void 0,void 0,(function*(){const t="getGroupMemberList",{groupID:s,offset:o=0,count:n=100,role:i="",filter:r=""}=e;console.log(`${this._name}.${t} groupID:${s} offset:${o} count:${n} role:${i} filter:${r}`);const c=Ra.getLocalGroup(s),l=n>100?100:n,u={groupID:s,offset:o,limit:l,memberRoleFilter:Lr.includes(i)?[i]:void 0,memberInfoFilter:Nr};try{const e=yield function(e,t){return a(this,void 0,void 0,(function*(){const{groupID:s,offset:o,limit:n,memberRoleFilter:i,memberInfoFilter:r}=e;return za("group_open_http_svc.get_group_member_info",{GroupId:s,Offset:o,Limit:n,MemberRoleFilter:i,MemberInfoFilter:r},t)}))}(u,this._core),{MemberList:n,MemberNum:i,Next:r}=e||{};console.log(`${this._name}.${t} ok, totalMemberCount:${i} next:${r}`);const{utils:{isArray:d,isEmpty:h},common:{isCommunity:p}}=this._core;if(c&&(c.memberCount=i),!d(n)||0===n.length)return Na({memberList:[],offset:0});let g=o+l;p({groupID:s})&&(g=h(r)?0:r),n.length<l&&(g=0);let _=this._convertMemberInfo(n);_=yield this._patchAvatarAndNick(_);const m=this._generateGroupMember(_);return Na({memberList:m,offset:g})}catch(e){const s=new this._core.helper.ChatError({functionName:t,code:null==e?void 0:e.errorCode,message:null==e?void 0:e.errorInfo});throw console.error(`${this._name}.${t} fail:`,s),s}}))}_convertMemberInfo(e){const t=[];for(let s=0,o=e.length;s<o;s++){const{AppMemberDefinedData:o,JoinTime:n,Member_Account:i,OnlineStatus:r,Role:a,ShutUpUntil:c}=e[s],l=Aa(o);t.push({userID:i,joinTime:n,onlineStatus:r,role:a,muteUntil:c,memberCustomField:l})}return t}_patchAvatarAndNick(e){return a(this,void 0,void 0,(function*(){var t;const s=e.map((e=>e.userID)),o=yield null===(t=this._core.user.userProfile)||void 0===t?void 0:t.getUserProfile({userIDList:s}),n=(null==o?void 0:o.data)||[],i=new Map(n.map((e=>[e.userID,e])));return e.forEach((e=>{if(i.has(e.userID)){const{nick:t="",avatar:s=""}=i.get(e.userID);e.nick=t,e.avatar=s}})),e}))}_generateGroupMember(e){const t=[];for(let s=0,o=e.length;s<o;s++){const o=new Ya(e[s]);t.push(o)}return t}};var Xa=new class{constructor(){this._name="GetGroupMemberProfile"}init(e){this._core=e;const{helper:t}=e;t.registerApi({apiName:"getGroupMemberProfile",context:this})}getGroupMemberProfile(e){return a(this,void 0,void 0,(function*(){const t="getGroupMemberProfile",{groupID:s,userIDList:o,memberCustomFieldFilter:n}=e,i=Ra.getLocalGroup(s),{helper:r,utils:{isArray:c}}=this._core;if(i&&ya(i.type))throw new r.ChatError({functionName:t,replacement1:t,code:Ea});o.length>50&&(console.warn(`${this._name}.${t} userIDList length:${o.length} exceeds limit 50`),o.splice(50));try{const e=yield function(e,t){return a(this,void 0,void 0,(function*(){const{groupID:s,userIDList:o,memberInfoFilter:n,memberCustomFieldFilter:i}=e;return za("group_open_http_svc.get_specified_group_member_info",{GroupId:s,Member_List_Account:o,MemberInfoFilter:n,AppDefinedDataFilter_GroupMember:i},t)}))}({groupID:s,userIDList:o,memberCustomFieldFilter:n,memberInfoFilter:[...Nr]},this._core);console.log(`${this._name}.${t} ok.`);const{MemberList:i}=e||{};if(!c(i)||0===i.length)return Na({memberList:[]});let r=this._convertMemberInfo(i);r=yield this._getMemberAvatarAndNick(r);const l=this._generateGroupMember(r);return Na({memberList:l})}catch(e){const s=new r.ChatError({functionName:t,code:null==e?void 0:e.errorCode,message:null==e?void 0:e.errorInfo});throw console.error(`${this._name}.${t} fail:`,s),s}}))}_convertMemberInfo(e){const t=[];for(let s=0,o=e.length;s<o;s++){const{AppMemberDefinedData:o,JoinTime:n,Member_Account:i,OnlineStatus:r,Role:a,ShutUpUntil:c}=e[s],l=Aa(o);t.push({userID:i,joinTime:n,onlineStatus:r,role:a,muteUntil:c,memberCustomField:l})}return t}_getMemberAvatarAndNick(e){return a(this,void 0,void 0,(function*(){var t;const s=e.map((e=>e.userID)),o=yield null===(t=this._core.user.userProfile)||void 0===t?void 0:t.getUserProfile({userIDList:s}),n=(null==o?void 0:o.data)||[],i=new Map(n.map((e=>[e.userID,e])));return e.forEach((e=>{if(i.has(e.userID)){const{nick:t="",avatar:s=""}=i.get(e.userID);e.nick=t,e.avatar=s}})),e}))}_generateGroupMember(e){const t=[];for(let s=0,o=e.length;s<o;s++){const o=new Ya(e[s]);t.push(o)}return t}};var Qa=new class{constructor(){this._name="AddGroupMember"}init(e){this._core=e;const{helper:t}=e;t.registerApi({apiName:"addGroupMember",context:this})}addGroupMember(e){return a(this,void 0,void 0,(function*(){const t="addGroupMember",{groupID:s,userIDList:o}=e,n=Ra.getLocalGroup(s),{helper:i}=this._core;if(n&&ya(n.type))throw new i.ChatError({functionName:t,code:ma});const r=o.map((e=>({Member_Account:e})));try{const e=yield function(e,t){return a(this,void 0,void 0,(function*(){const{groupID:s,userIDList:o}=e;return za("group_open_http_svc.add_group_member",{GroupId:s,MemberList:o},t)}))}({groupID:s,userIDList:r},this._core),{MemberList:o=[]}=e||{},{failureUserIDList:i,successUserIDList:c,existedUserIDList:l,overLimitUserIDList:u}=this._handleResult(o);return console.log(`${this._name}.${t} groupID:${s} ok, successUserIDList:${c} failureUserIDList:${i} existedUserIDList:${l} overLimitUserIDList:${u}`),Na({failureUserIDList:i,successUserIDList:c,existedUserIDList:l,overLimitUserIDList:u,group:n})}catch(e){const s=new i.ChatError({functionName:t,code:null==e?void 0:e.errorCode,message:null==e?void 0:e.errorInfo});throw console.error(`${this._name}.${t} fail:`,s),s}}))}_handleResult(e){const t=[],s=[],o=[],n=[];return e.forEach((e=>{const{Result:i,Member_Account:r}=e;i===br?t.push(r):i===wr?s.push(r):i===Pr?o.push(r):i===Ur&&n.push(r)})),{failureUserIDList:t,successUserIDList:s,existedUserIDList:o,overLimitUserIDList:n}}};var ec=new class{constructor(){this._name="DeleteGroupMember"}init(e,t){this._core=e;const{helper:s}=e;s.registerApi({apiName:"deleteGroupMember",context:this,matcher:()=>!t.getInstalledSubPlugins().includes(mr)})}deleteGroupMember(e){return a(this,void 0,void 0,(function*(){const t="deleteGroupMember",{groupID:s,userIDList:o}=e,n=Ra.getLocalGroup(s),{helper:i,utils:{isUndefined:r}}=this._core;if(r(n))throw new i.ChatError({functionName:t,code:da});o.length>20&&(console.warn(`${this._name}.${t} userIDList length:${o.length} exceeds limit 20`),o.splice(20));try{return yield function(e,t){return a(this,void 0,void 0,(function*(){const{groupID:s,userIDList:o,reason:n}=e;return za("group_open_http_svc.delete_group_member",{GroupId:s,MemberToDel_Account:o,Reason:n},t)}))}({groupID:s,userIDList:o},this._core),console.log(`${this._name}.${t} ok, groupID:${s} userIDList length:${o.length}`),Na({group:n,userIDList:o})}catch(e){const s=new i.ChatError({functionName:t,code:null==e?void 0:e.errorCode,message:null==e?void 0:e.errorInfo});throw console.error(`${this._name}.${t} fail:`,s),s}}))}};var tc=new class{constructor(){this._name="SetGroupMemberMuteTime"}init(e){this._core=e;const{helper:t}=e;t.registerApi({apiName:"setGroupMemberMuteTime",context:this})}setGroupMemberMuteTime(e){return a(this,void 0,void 0,(function*(){const t="setGroupMemberMuteTime",{helper:s}=this._core;this._preCheckSettingMuteParams(e);try{yield Ja(e,this._core);const{groupID:s,userID:o,muteTime:n}=e;console.log(`${this._name}.${t} ok, groupID:${s} userID:${o} muteTime:${n}`);const i=Ra.getLocalGroup(s),r=new Ya({userID:o,muteTime:n});return Na({group:i,member:r})}catch(e){const o=new s.ChatError({functionName:t,code:null==e?void 0:e.errorCode,message:null==e?void 0:e.errorInfo});throw console.error(`${this._name}.${t} fail:`,o),o}}))}_preCheckSettingMuteParams(e){const{userID:t}=e,{store:s,helper:o}=this._core;if(t===s.get("login").userId)throw new o.ChatError({functionName:"setGroupMemberMuteTime",code:Sa})}};var sc=new class{constructor(){this._name="SetGroupMemberRole"}init(e){this._core=e;const{helper:t}=e;t.registerApi({apiName:"setGroupMemberRole",context:this})}setGroupMemberRole(e){return a(this,void 0,void 0,(function*(){const t="setGroupMemberRole",{helper:s}=this._core;this._preCheckSettingRoleParams(e);try{yield Ja(e,this._core);const{groupID:s,userID:o,role:n}=e;console.log(`${this._name}.${t} ok, groupID:${s} userID:${o} role:${n}`);const i=Ra.getLocalGroup(s),r=new Ya({userID:o,role:n});return Na({group:i,member:r})}catch(e){const o=new s.ChatError({functionName:t,code:null==e?void 0:e.errorCode,message:null==e?void 0:e.errorInfo});throw console.error(`${this._name}.${t} fail:`,o),o}}))}_preCheckSettingRoleParams(e){var t;const{groupID:s,userID:o,role:n}=e,{store:i,helper:r,OuterConstant:a,common:{isCommunity:c}}=this._core,l=Ra.getLocalGroup(s);if((null===(t=null==l?void 0:l.selfInfo)||void 0===t?void 0:t.role)!==a.GRP_MBR_ROLE_OWNER)throw new r.ChatError({functionName:"setGroupMemberRole",code:fa});if(o===i.get("login").userId)throw new r.ChatError({functionName:"setGroupMemberRole",code:Ia});const u=[...Lr];if(c({groupID:s})&&u.push(a.GRP_MBR_ROLE_CUSTOM),!u.includes(n))throw new r.ChatError({functionName:"setGroupMemberRole",code:va})}};var oc=new class{constructor(){this._name="SetGroupMemberNameCard"}init(e){this._core=e;const{helper:t}=e;t.registerApi({apiName:"setGroupMemberNameCard",context:this})}setGroupMemberNameCard(e){return a(this,void 0,void 0,(function*(){const t="setGroupMemberNameCard",{helper:s}=this._core;this._preCheckSettingNameCardParams(e);try{yield Ja(e,this._core);const{groupID:s,userID:o,nameCard:n}=e;console.log(`${this._name}.${t} ok, groupID:${s} userID:${o} nameCard:${n}`);const i=Ra.getLocalGroup(s),r=new Ya({userID:o,nameCard:n});return Na({group:i,member:r})}catch(e){const o=new s.ChatError({functionName:t,code:null==e?void 0:e.errorCode,message:null==e?void 0:e.errorInfo});throw console.error(`${this._name}.${t} fail:`,o),o}}))}_preCheckSettingNameCardParams(e){const{groupID:t}=e,{helper:s}=this._core,o=Ra.getLocalGroup(t);if(ya(null==o?void 0:o.type))throw new s.ChatError({functionName:"setGroupMemberNameCard",code:Ea})}};var nc=new class{constructor(){this._name="SetGroupMemberCustomField"}init(e){this._core=e;const{helper:t}=e;t.registerApi({apiName:"setGroupMemberCustomField",context:this})}setGroupMemberCustomField(e){return a(this,void 0,void 0,(function*(){const t="setGroupMemberCustomField",{helper:s}=this._core;this._preCheckSettingCustomFiledParams(e);try{yield Ja(e,this._core);const{groupID:s,userID:o,memberCustomField:n}=e;console.log(`${this._name}.${t} ok, groupID:${s} userID:${o} memberCustomField:${JSON.stringify(n)}`);const i=Ra.getLocalGroup(s),r=new Ya({userID:o,memberCustomField:n});return Na({group:i,member:r})}catch(e){const o=new s.ChatError({functionName:t,code:null==e?void 0:e.errorCode,message:null==e?void 0:e.errorInfo});throw console.error(`${this._name}.${t} fail:`,o),o}}))}_preCheckSettingCustomFiledParams(e){const{groupID:t}=e,{helper:s}=this._core,o=Ra.getLocalGroup(t);if(ya(null==o?void 0:o.type))throw new s.ChatError({functionName:"setGroupMemberCustomField",code:Ea})}};var ic=new class{init(e,t){console.log("GroupMember.init"),Za.init(e,t),Xa.init(e),Qa.init(e),ec.init(e,t),tc.init(e),sc.init(e),oc.init(e),nc.init(e)}getGroupMemberList(e){return Za.getGroupMemberList(e)}deleteGroupMember(e){return ec.deleteGroupMember(e)}};var rc=new class{init(e){this._core=e}};function ac(e,t,s){return a(this,void 0,void 0,(function*(){const{helper:o,channel:n}=s,i=o.generateProtocolData({servcmd:e,data:t}),r=`${i.head.seq}${e}`;return yield n.sendPacket(i,{requestId:r})}))}var cc=new class{constructor(){this._name="InitGroupAttributes"}init(e){this._core=e;const{helper:t}=e;t.registerApi({apiName:"initGroupAttributes",context:this})}initGroupAttributes(e){return a(this,void 0,void 0,(function*(){const t="initGroupAttributes",{groupID:s,groupAttributes:o}=e,{serverMainSequence:n,avChatRoomKey:i}=Pa.getGroupAttributesCache(s),r=Pa.convertKeyValueMapToList(o);try{const e=yield function(e,t){return a(this,void 0,void 0,(function*(){const{groupID:s,mainSequence:o,groupAttributeList:n,avChatRoomKey:i}=e;return ac("group_open_http_svc.set_group_attr",{GroupId:s,AttrMainSeq:o,GroupAttr:n,BytesKey:i,AttrControl:["RaceConflict"]},t)}))}({groupID:s,avChatRoomKey:i,groupAttributeList:r,mainSequence:n},this._core),{AttrMainSeq:c,GroupAttr:l}=e||{};console.log(`${this._name}.${t} ok. groupID:${s} serverMainSequence:${c}`);const u=l.map((e=>{const{Key:t,seq:s}=e;return{key:t,value:o[t],sequence:s}}));return Pa.saveGroupAttributesCacheValuesCopy(s),Pa.refreshGroupAttributesCache({groupID:s,serverMainSequence:c,groupAttributeList:u,operation:Gr}),Pa.emitGroupAttributesUpdated(s),Na({groupAttributes:o})}catch(e){const s=new this._core.helper.ChatError({functionName:t,code:null==e?void 0:e.errorCode,message:null==e?void 0:e.errorInfo});throw console.error(`${this._name}.${t} fail:`,s),s}}))}};var lc=new class{constructor(){this._name="SetGroupAttributes"}init(e){this._core=e;const{helper:t}=e;t.registerApi({apiName:"setGroupAttributes",context:this})}setGroupAttributes(e){return a(this,void 0,void 0,(function*(){const t="setGroupAttributes",{groupID:s,groupAttributes:o}=e,{serverMainSequence:n,avChatRoomKey:i,values:r}=Pa.getGroupAttributesCache(s),c=Pa.convertKeyValueMapToList(o).map((e=>{var t;const{key:s,value:o}=e;return{key:s,value:o,seq:(null===(t=r.get(e.key))||void 0===t?void 0:t.sequence)||0}}));try{const e=yield function(e,t){return a(this,void 0,void 0,(function*(){const{groupID:s,mainSequence:o,groupAttributeList:n,avChatRoomKey:i}=e;return ac("group_open_http_svc.modify_group_attr",{GroupId:s,AttrMainSeq:o,GroupAttr:n,BytesKey:i,AttrControl:["RaceConflict"]},t)}))}({groupID:s,avChatRoomKey:i,groupAttributeList:c,mainSequence:n},this._core),{AttrMainSeq:r,GroupAttr:l}=e||{};console.log(`${this._name}.${t} ok. groupID:${s} serverMainSequence:${r}`);const u=l.map((e=>{const{Key:t,seq:s}=e;return{key:t,value:o[t],sequence:s}}));return Pa.saveGroupAttributesCacheValuesCopy(s),Pa.refreshGroupAttributesCache({groupID:s,serverMainSequence:r,groupAttributeList:u,operation:kr}),Pa.emitGroupAttributesUpdated(s),Na({groupAttributes:o})}catch(e){const s=new this._core.helper.ChatError({functionName:t,code:null==e?void 0:e.errorCode,message:null==e?void 0:e.errorInfo});throw console.error(`${this._name}.${t} fail:`,s),s}}))}};var uc=new class{constructor(){this._name="DeleteGroupAttributes"}init(e){this._core=e;const{helper:t}=e;t.registerApi({apiName:"deleteGroupAttributes",context:this})}deleteGroupAttributes(e){return a(this,void 0,void 0,(function*(){const t="deleteGroupAttributes",{groupID:s,keyList:o=[]}=e;try{let e;e=0===o.length?yield this._clearGroupAttributes(s):yield this._deleteGroupAttributes(s,o);const{resultList:n,serverMainSequence:i,operation:r,groupAttributeList:a}=e||{};return console.log(`${this._name}.${t} ok. groupID:${s} operation: ${r}`),Pa.saveGroupAttributesCacheValuesCopy(s),Pa.refreshGroupAttributesCache({groupID:s,serverMainSequence:i,groupAttributeList:a,operation:r}),Pa.emitGroupAttributesUpdated(s),Na({keyList:n})}catch(e){const s=new this._core.helper.ChatError({functionName:t,code:null==e?void 0:e.errorCode,message:null==e?void 0:e.errorInfo});throw console.error(`${this._name}.${t} fail:`,s),s}}))}_deleteGroupAttributes(e,t){return a(this,void 0,void 0,(function*(){const{serverMainSequence:s,avChatRoomKey:o,values:n}=Pa.getGroupAttributesCache(e),i=[],r=[];t.forEach((e=>{if(n.has(e)){const{sequence:t=0}=n.get(e)||{};r.push({key:e,seq:t}),i.push(e)}}));const c=yield function(e,t){return a(this,void 0,void 0,(function*(){const{groupID:s,mainSequence:o,groupAttributeList:n,avChatRoomKey:i}=e;return ac("group_open_http_svc.delete_group_attr",{GroupId:s,AttrMainSeq:o,GroupAttr:n,BytesKey:i,AttrControl:["RaceConflict"]},t)}))}({groupID:e,avChatRoomKey:o,groupAttributeList:r,mainSequence:s},this._core),{AttrMainSeq:l}=c||{};return{resultList:i,serverMainSequence:l,groupAttributeList:r,operation:$r}}))}_clearGroupAttributes(e){return a(this,void 0,void 0,(function*(){const{serverMainSequence:t,avChatRoomKey:s,values:o}=Pa.getGroupAttributesCache(e),n=[...o.keys()],i=yield function(e,t){return a(this,void 0,void 0,(function*(){const{groupID:s,mainSequence:o,avChatRoomKey:n}=e;return ac("group_open_http_svc.clear_group_attr",{GroupId:s,AttrMainSeq:o,BytesKey:n,AttrControl:["RaceConflict"]},t)}))}({groupID:e,avChatRoomKey:s,mainSequence:t},this._core),{AttrMainSeq:r}=i||{};return{resultList:n,serverMainSequence:r,operation:Fr}}))}};var dc=new class{constructor(){this._name="GetGroupAttributes"}init(e){this._core=e;const{helper:t}=e;t.registerApi({apiName:"getGroupAttributes",context:this})}getGroupAttributes(e){return a(this,void 0,void 0,(function*(){const t="getGroupAttributes",{groupID:s}=e,{avChatRoomKey:o,lastUpdateTime:n,localMainSequence:i,serverMainSequence:r}=Pa.getGroupAttributesCache(s);if(Date.now()-n>=3e4||i<r)try{yield this.getGroupAttributesFromServer({groupID:s,avChatRoomKey:o});const n=Pa.getGroupAttributesCacheValues(e);return console.log(`${this._name}.${t} from server. groupID:${s}`),Na({groupAttributes:n})}catch(e){const s=new this._core.helper.ChatError({functionName:t,code:null==e?void 0:e.errorCode,message:null==e?void 0:e.errorInfo});throw console.error(`${this._name}.${t} fail:`,s),s}const a=Pa.getGroupAttributesCacheValues(e);return console.log(`${this._name}.${t} from cache. groupID:${s}`),Na({groupAttributes:a})}))}getGroupAttributesFromServer(e){return a(this,void 0,void 0,(function*(){const{utils:{isUndefined:t}}=this._core,{groupID:s,avChatRoomKey:o}=e,n=t(o)?Vr:xr,i=yield function(e,t){return a(this,void 0,void 0,(function*(){const{groupID:s,groupType:o,avChatRoomKey:n}=e;return ac("group_open_attr_http_svc.get_group_attr",{GroupId:s,GroupType:o,Key:n},t)}))}({groupID:s,avChatRoomKey:o,groupType:n},this._core),{AttrMainSeq:r,GroupAttrAry:c}=i||{};if(console.log(`${this._name}._getGroupAttributesFromServer ok. groupID:${s} serverMainSequence:${r}`),!t(r)){const e=c.map((e=>{const{key:t,value:s,seq:o}=e;return{key:t,value:s,sequence:o}}));Pa.refreshGroupAttributesCache({groupID:s,serverMainSequence:r,groupAttributeList:e,operation:qr})}}))}};var hc=new class{init(e){console.log("GroupAttribute.init"),cc.init(e),lc.init(e),uc.init(e),dc.init(e),Pa.init(e)}isGroupAttributesUpdated(e){return Pa.isGroupAttributesUpdated(e)}handleGroupAttributesUpdated(e){const{to:t,elements:{newGroupProfile:s}}=e,{groupAttributeOption:o}=s,{serverMainSequence:n,withChangedAttributeInfo:i}=o,{localMainSequence:r}=Pa.getGroupAttributesCache(t),a=n-r;if(console.log(`GroupAttribute.handleGroupAttributesUpdated groupID:${t} withChangedAttributeInfo:${i} diffSequence:${a}`),0!==a)if(Pa.saveGroupAttributesCacheValuesCopy(t),1!==i||1!==a){if(Pa.hasGroupAttributesCache(t)){const{avChatRoomKey:e}=Pa.getGroupAttributesCache(t);dc.getGroupAttributesFromServer({groupID:t,avChatRoomKey:e}).then((()=>{Pa.emitGroupAttributesUpdated(t)})).catch((()=>{}))}}else Pa.handleGroupAttributesUpdated({groupID:t,groupAttributeOption:o})}};function pc(e,t="tips"){const{ClientSeq:s,From_Account:o,MsgClientTime:n,MsgPriority:i,MsgRandom:r,MsgSeq:a,MsgTimeStamp:c,TinyId:l,ToGroupId:u,GroupInfo:d,MsgBody:h}=e,p=function(e){const{GroupCode:t,GroupId:s,GroupName:o,GroupType:n,MsgFrom_AccountExtraInfo:i,From_Account:r,To_Account:a}=e;return{groupCode:t,groupID:s,groupName:o,type:n,messageFromAccountExtraInformation:i,from:r,to:a}}(d);return{clientSequence:s,from:o,clientTime:n,priority:i,random:r,sequence:a,time:c,tinyID:l,to:u,groupProfile:p,elements:"tips"===t?gc(h):function(e){const t={};return Object.keys(e).forEach((s=>{switch(s){case"MsgKey":t.messageKey=e[s];break;case"Operator_Account":t.operatorID=e[s];break;case"ReportType":t.operationType=e[s];break;case"Authentication":t.authentication=e[s];break;case"MsgFlag":t.messageRemindType=e[s];break;case"UserDefinedField":t.userDefinedField=e[s];break;case"RemarkInfo":t.remarkInfo=e[s];break;case"BanDuration":t.duration=e[s]}})),t}(h)}}function gc(e){const t={};return Object.keys(e).forEach((s=>{switch(s){case"MemberNum":t.memberCount=e[s];break;case"OpType":t.operationType=e[s];break;case"Operator_Account":t.operatorID=e[s];break;case"List_Account":t.userIDList=e[s];break;case"MsgMemberExtraInfo":t.memberInfoList=e[s].map((e=>_c(e)));break;case"MsgOperatorMemberExtraInfo":t.operatorInfo=_c(e[s]);break;case"MsgGroupNewInfo":t.newGroupProfile=function(e){const t={};return Object.keys(e).forEach((s=>{switch(s){case"GroupIntroduction":t.introduction=e[s];break;case"GroupName":t.groupName=e[s];break;case"GroupFaceUrl":t.avatar=e[s];break;case"GroupNotification":t.notification=e[s];break;case"ApplyJoinOption":t.joinOption=e[s];break;case"InviteJoinOption":t.inviteOption=e[s];break;case"ShutupAll":t.muteAllMembers=e[s];break;case"Owner_Account":t.ownerID=e[s];break;case"GroupAttrOption":t.groupAttributeOption=function(e){const{BytesChangedKeys:t,GroupAttrSeq:s,OpType:o,PushChangedAttrValFlag:n,GroupAttrInfo:i}=e,r=i.map((e=>{const{Key:t,Val:s,SubKeySeq:o}=e;return{key:t,value:s,sequence:o}}));return{changedKeyList:t,groupAttributeList:r,serverMainSequence:s,operation:o,withChangedAttributeInfo:n}}(e[s])}})),t}(e[s]);break;case"MsgMemberInfo":t.msgMemberInfo=e[s].map((e=>function(e){const{ShutupTime:t,User_Account:s}=e;return{muteTime:t,userID:s}}(e)));break;case"OnlineMemberInfo":t.onlineMemberInfo=function(e){const{ExpireTime:t,OnlineMemberNum:s}=e;return{expireTime:t,onlineMemberNum:s}}(e[s])}})),t}function _c(e){const{ImageUrl:t,NickName:s,Role:o,UserId:n}=e;return{avatar:t,nick:s,role:o,userID:n}}class mc{constructor(e){this.type=_r.core.OuterConstant.MSG_GRP_TIP,this.content={},this._initContent(e)}static parseServerPushElement(e){const t=gc(e);return new mc(t)}_initContent(e){Object.keys(e).forEach((t=>{switch(t){case"groupProfile":this._initGroupProfile(e[t]);break;case"operatorInfo":this._initOperatorInfo(e[t]);break;case"memberInfoList":case"msgMemberInfo":this._updateMemberList(e[t]);break;case"newGroupProfile":this._initNewGroupProfile(e[t]);break;case"memberExtraInfo":case"remarkInfo":case"onlineMemberInfo":break;default:this.content[t]=e[t]}})),this.content.userIDList||(this.content.userIDList=[this.content.operatorID])}_initGroupProfile(e){this.content.groupProfile={};const t=Object.keys(e);for(let s=0;s<t.length;s++){const o=t[s];Qr[o]&&(this.content.groupProfile[o]=e[o])}}_initOperatorInfo(e){this.content.operatorInfo={};const t=Object.keys(e);for(let s=0;s<t.length;s++){const o=t[s];this.content.operatorInfo[o]=e[o]}}_updateMemberList(e){this.content.memberList?this.content.memberList.forEach((t=>{e.forEach((e=>{t.userID===e.userID&&Object.assign(t,e)}))})):this.content.memberList=e}_initNewGroupProfile(e){this.content.newGroupProfile={};const t=Object.keys(e);for(let s=0;s<t.length;s++){const o=t[s];"muteAllMembers"!==o?this.content.newGroupProfile[o]=e[o]:this.content.newGroupProfile.muteAllMembers=1===e.muteAllMembers}}}var fc=new class{constructor(){this._name="GroupTipsNotification"}init(e){this._core=e;const{message:{messageFactory:t},OuterConstant:s}=e;null==t||t.registerElementClass(s.MSG_GRP_TIP,mc)}onNewGroupTips(e){console.log(`${this._name}.onNewGroupTips options:${JSON.stringify(e)}`);const{messageList:t}=this._handleGroupTips(e),{notificationCenter:s,OuterEvent:o}=this._core;t.length>0&&(s.emitOuterEvent(o.MESSAGE_RECEIVED,{name:o.MESSAGE_RECEIVED,data:t}),this._handleGroupTipMessage(t))}_handleGroupTips(e){const{Event:t,GroupTips:s}=e,o=new Map,n=[],i=[];for(let e=0,n=s.length;e<n;e++){const n=pc(s[e],"tips");if(t===jr&&hc.isGroupAttributesUpdated(n)){hc.handleGroupAttributesUpdated(n);continue}const{groupProfile:{groupID:r}}=n;if(!Ra.hasLocalGroup(r))continue;const a=this._assembleMessage(n);if(t===jr&&(a._onlineOnlyFlag=!0,i.push(a)),t===Br){if(!this._core.message.messageDataHandler.storeConversationMessage(a))continue;i.push(a)}this._handleConversationOptions(o,a)}return n.push(...o.values()),{conversationUpdateFieldList:n,messageList:i}}_assembleMessage(e){const{OuterConstant:t,message:{messageFactory:s}}=this._core;e.flow="in",e.conversationType=t.CONV_GROUP;const o=s.createMessage(e);this._patchNickAndAvatar(e.elements,o);const n=new mc(Object.assign(Object.assign({},e.elements),{groupProfile:Object.assign({},e.groupProfile)}));return o.setElement(n),o.isSystemMessage=!1,o}_patchNickAndAvatar(e,t){const{utils:{isEmpty:s}}=this._core,{operationType:o,memberInfoList:n,operatorInfo:i}=e;let r={};if(s(n)?s(i)||(r=i):o!==Wr&&o!==Hr&&o!==Yr&&o!==zr||(r=Object.assign({},n[0])),!s(r)){const{nick:e="",avatar:s=""}=r;t.nick=e,t.avatar=s}}_handleConversationOptions(e,t){const{conversationID:s,conversationType:o}=t;let n;if(e.has(s))n=e.get(s),"in"===t.flow&&(t._isExcludedFromUnreadCount||t._onlineOnlyFlag||n.unreadCount++),n.type=o,n.lastMessage=t._isExcludedFromLastMessage?"":t;else{let e=0;"in"===t.flow&&(t._isExcludedFromUnreadCount||t._onlineOnlyFlag||(e=1)),n={conversationID:s,unreadCount:e,type:o,lastMessage:t._isExcludedFromLastMessage?"":t}}e.set(s,n)}_handleGroupTipMessage(e){e.forEach((e=>{const{operationType:t}=e.payload;switch(t){case Wr:this._handleNewMemberJoined(e);break;case Kr:this._handleMemberQuitted(e);break;case Hr:this._handleMemberKicked(e);break;case Jr:this._handleGroupProfileUpdated(e)}}))}_handleNewMemberJoined(e){this._handleGroupMemberCountUpdated(e)}_handleMemberQuitted(e){this._handleGroupMemberCountUpdated(e)}_handleMemberKicked(e){this._handleGroupMemberCountUpdated(e)}_handleGroupProfileUpdated(e){var t;const{newGroupProfile:s,groupProfile:o,operatorInfo:n}=e.payload,{groupID:i}=o,r=Ra.getLocalGroup(i);Object.keys(s).forEach((e=>{switch(e){case"ownerID":this._handleGroupOwnerChanged(i,s);break;case"groupName":r.name=s[e];break;default:r[e]=s[e]}}));const{utils:{isUndefined:a}}=this._core;a(n)||(null===(t=null==r?void 0:r.selfInfo)||void 0===t?void 0:t.userID)!==n.userID||Object.keys(n).forEach((e=>{"nameCard"===e&&r.updateSelfInfo({nameCard:n[e]}),"role"===e&&this._updateSelfRole(r,n[e])})),Ra.emitGroupListUpdate(),Ra.updateConversationGroupProfile(i)}_handleGroupOwnerChanged(e,t){const{common:s,OuterConstant:o}=this._core,n=Ra.getLocalGroup(e),i=s.getCurrentUserID(),{ownerID:r}=t;i===r&&n.updateGroup({ownerID:r,selfInfo:{role:o.GRP_MBR_ROLE_OWNER}})}_updateSelfRole(e,t){const{OuterConstant:s}=this._core;let o=s.GRP_MBR_ROLE_MEMBER;t===Zr?o=s.GRP_MBR_ROLE_OWNER:t===Xr&&(o=s.GRP_MBR_ROLE_ADMIN),e.updateSelfInfo({role:o})}_handleGroupMemberCountUpdated(e){const{memberCount:t,groupProfile:{groupID:s}}=e.payload,o=Ra.getLocalGroup(s),{utils:{isNumber:n}}=this._core;o&&n(t)&&o.memberCount!==t&&(o.memberCount=t,Ra.emitGroupListUpdate(),Ra.updateConversationGroupProfile(s))}};class vc{constructor(e){this.type=_r.core.OuterConstant.MSG_GRP_SYS_NOTICE,this.content={},this._initContent(e)}_initContent(e){Object.keys(e).forEach((t=>{switch(t){case"remarkInfo":this.content.handleMessage=e[t];break;case"groupProfile":this._initGroupProfile(e[t]);break;case"memberInfoList":break;default:this.content[t]=e[t]}}))}_initGroupProfile(e){this.content.groupProfile={};const t=Object.keys(e);for(let s=0;s<t.length;s++){const o=t[s];ea[o]&&(this.content.groupProfile[o]=e[o])}}}var Ic=new class{constructor(){this._name="GroupSystemNotification"}init(e){this._core=e;const{message:{messageFactory:t},OuterConstant:{MSG_GRP_SYS_NOTICE:s}}=e;null==t||t.registerElementClass(s,vc)}onNewGroupSystemNotification(e){const{GroupTips:t=[],isInstantMessage:s=!0}=e;console.log(`${this._name}.onNewGroupSystemNotification count:${t.length} isInstantMessage:${s}`);const{conversationUpdateFieldList:o,messageList:n}=this._handleGroupSystemNotification(t,s),{notificationCenter:i,OuterEvent:r}=this._core;o.length>0&&this._handleGroupSysTemMessage(s,n),!0===s&&n.length>0&&i.emitOuterEvent(r.MESSAGE_RECEIVED,{name:r.MESSAGE_RECEIVED,data:n})}_handleGroupSystemNotification(e,t){const s=[];let o={};for(let n=0;n<e.length;n++){const i=pc(e[n],"system"),{elements:{operationType:r}}=i;if(r===ra)continue;const a=this._assembleMessage(i);this._core.message.messageDataHandler.storeConversationMessage(a)&&(s.push(a),o=this._handleConversationOptions(a,t))}return o.lastMessage=s[s.length-1],{conversationUpdateFieldList:s.length>0?[o]:[],messageList:s}}_assembleMessage(e){const{message:{messageFactory:t},OuterConstant:s,utils:{randomInt:o}}=this._core;e.flow="in",e.conversationType=s.CONV_SYSTEM,e.conversationSubType=e.groupProfile.type,e.conversationID=s.CONV_SYSTEM;const n=t.createMessage(e),i=new vc(Object.assign(Object.assign({},e.elements),{groupProfile:Object.assign({},e.groupProfile)}));n.setElement(i),n.isSystemMessage=!0;const r=1===n.sequence&&1===n.random,a=2===n.sequence&&2===n.random;return(r||a)&&(n.sequence=o(),n.random=o(),n.generateMessageID()),n}_handleConversationOptions(e,t){const{OuterConstant:s}=this._core,o={conversationID:s.CONV_SYSTEM,unreadCount:0,type:s.CONV_SYSTEM,subType:e.conversationSubType,lastMessage:null};return t&&o.unreadCount++,o}_handleGroupSysTemMessage(e,t){e&&t.forEach((e=>{const{operationType:t}=e.payload;switch(t){case ta:this._handleGroupJoinResult(e);break;case sa:this._handleMemberKicked(e);break;case oa:this._handleGroupDismissed(e);break;case na:this._handleGroupInvitedResult(e);break;case ia:this._handleGroupQuitResult(e);break;case aa:this._handleMessageRemindTypeSynced(e);break;case ca:this._handleAVChatRoomMemberBanned(e)}}))}_handleGroupJoinResult(e){const{groupProfile:t}=e.payload,{groupID:s,type:o}=t,n=Ra.hasLocalGroup(s);console.log(`${this._name}._handleGroupJoinResult groupID:${s} type:${o} hasLocalGroup:${n}`),n||ya(o)||(Ra.updateLocalGroup([Object.assign({},t)]),Ra.emitGroupListUpdate())}_handleMemberKicked(e){const{groupProfile:{groupID:t,type:s}}=e.payload;Ra.hasLocalGroup(t)&&this._deleteLocalGroup(t,s),this._updateConversationProfile(t,{unreadCount:0})}_handleGroupDismissed(e){const{groupProfile:{groupID:t,type:s}}=e.payload;Ra.hasLocalGroup(t)&&this._deleteLocalGroup(t,s),this._updateConversationProfile(t,{unreadCount:0})}_handleGroupInvitedResult(e){const{groupProfile:t}=e.payload,{groupID:s}=t,o=Ra.hasLocalGroup(s);console.log(`${this._name}._handleGroupInvitedResult groupID:${s} hasLocalGroup:${o}`),o||(Ra.updateLocalGroup([Object.assign({},t)]),Ra.emitGroupListUpdate())}_handleGroupQuitResult(e){const{groupProfile:{groupID:t,type:s}}=e.payload,o=Ra.hasLocalGroup(t);console.log(`${this._name}._handleGroupQuitResult groupID:${t} type:${s} hasLocalGroup:${o}`),o&&this._deleteLocalGroup(t,s),this._updateConversationProfile(t,{unreadCount:0})}_handleMessageRemindTypeSynced(e){const{groupProfile:{groupID:t},messageRemindType:s}=e.payload;this._updateConversationProfile(t,{messageRemindType:s})}_handleAVChatRoomMemberBanned(e){const{groupProfile:{groupID:t,type:s}}=e.payload;this._deleteLocalGroup(t,s)}_deleteLocalGroup(e,t){if(ya(t)){const{appStore:{conversationStore:t},OuterConstant:{CONV_GROUP:s}}=this._core;t.deleteConversation(`${s}${e}`)}Ra.deleteLocalGroup(e),Ra.emitGroupListUpdate()}_updateConversationProfile(e,t){const{appStore:{conversationStore:s},OuterConstant:{CONV_GROUP:o}}=this._core,n=`${o}${e}`;s.getConversation(n)&&s.updateConversation(n,t)}};var Sc=new class{init(e){this._core=e,console.log("GroupNotificationHandler.init"),fc.init(e),Ic.init(e);const{notificationCenter:t,InnerEvent:s}=e,{InnerEventSubType:o}=t;t.subscribeInnerEvent(s.MESSAGE_PUSH,o.GROUP_TIPS_NOTIFICATION,this._onNewGroupTipsNotification,this),t.subscribeInnerEvent(s.MESSAGE_PUSH,o.GROUP_SYSTEM_NOTIFICATION,this._onNewGroupSystemNotification,this),t.subscribeInnerEvent(s.DESTROY,this._dispose,this)}_onNewGroupTipsNotification(e){fc.onNewGroupTips(e)}_onNewGroupSystemNotification(e){Ic.onNewGroupSystemNotification(e)}_dispose(){const{notificationCenter:e,InnerEvent:t}=this._core,{InnerEventSubType:s}=e;e.unSubscribeInnerEvent(t.MESSAGE_PUSH,s.GROUP_TIPS_NOTIFICATION,this._onNewGroupTipsNotification,this),e.unSubscribeInnerEvent(t.MESSAGE_PUSH,s.GROUP_SYSTEM_NOTIFICATION,this._onNewGroupSystemNotification,this)}};const Ec={required:!0,rules:["string"],allowEmpty:!1},Cc={required:!0,rules:["number"],allowEmpty:!1},yc={required:!0,rules:["array"],allowEmpty:!1},Mc={required:!0,rules:["object"],allowEmpty:!1},Ac={createGroup:{name:Ec,type:Ec},dismissGroup:[Object.assign({key:"groupID"},Ec)],joinGroup:{groupID:Ec,applyMessage:{required:!1,rules:["string"],allowEmpty:!0}},quitGroup:[Object.assign({key:"groupID"},Ec)],searchGroupByID:[Object.assign({key:"groupID"},Ec)],getGroupProfile:{groupID:Ec,groupCustomFieldFilter:{required:!1,rules:["array"],allowEmpty:!0}},updateGroupProfile:{groupID:Ec,muteAllMembers:{required:!1,rules:["boolean"],allowEmpty:!1}},changeGroupOwner:{groupID:Ec,newOwnerID:Ec},getGroupOnlineMemberCount:[Object.assign({key:"groupID"},Ec)],handleGroupApplication:{handleAction:Ec},getGroupMemberList:{groupID:Ec},getGroupMemberProfile:{groupID:Ec,userIDList:yc,memberCustomFieldFilter:{required:!1,rules:["array"],allowEmpty:!0}},addGroupMember:{groupID:Ec,userIDList:yc},deleteGroupMember:{groupID:Ec,userIDList:yc},setGroupMemberMuteTime:{groupID:Ec,userID:Ec,muteTime:Object.assign(Object.assign({},Cc),{customValidator:e=>!(e<0)||"muteTime must be a non-negative number."})},setGroupMemberRole:{groupID:Ec,userID:Ec,role:Ec},setGroupMemberNameCard:{groupID:Ec,userID:{required:!1,rules:["string"],allowEmpty:!1},nameCard:Ec},setGroupMemberCustomField:{groupID:Ec,userID:{required:!1,rules:["string"],allowEmpty:!1},memberCustomField:yc},markGroupMemberList:{groupID:Ec,markType:Object.assign(Object.assign({},Cc),{customValidator:e=>!(e<1e3)||"markType must be greater than or equal to 1000."}),enableMark:{required:!0,rules:["boolean"],allowEmpty:!1},userIDList:yc},initGroupAttributes:{groupID:Ec,groupAttributes:Mc},setGroupAttributes:{groupID:Ec,groupAttributes:Mc},deleteGroupAttributes:{groupID:Ec,keyList:Object.assign(Object.assign({},yc),{allowEmpty:!0})},getGroupAttributes:{groupID:Ec,keyList:Object.assign(Object.assign({},yc),{allowEmpty:!0})}},Oc={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};var Tc=new class{constructor(){this._installedSubPlugins=[],this.groupDataHandler=Ra,this.groupAction=Ba,this.groupAttribute=hc,this.groupMember=ic}install(e,t=[]){this._core=e,_r.init(e),Ra.init(e),Ba.init(e,this),ic.init(e,this),Ha.init(e),rc.init(e),hc.init(e),Sc.init(e),e.helper.registerValidateConfig({auth:Oc,params:Ac}),this._installSubPlugins(t);const{notificationCenter:s,InnerEvent:o}=e;s.subscribeInnerEvent(o.LOGOUT,this._reset,this),s.subscribeInnerEvent(o.DESTROY,this._dispose,this)}getInstalledSubPlugins(){return this._installedSubPlugins}_installSubPlugins(e){const{utils:{isArray:t}}=this._core;e&&t(e)&&e.forEach((e=>{var t;null===(t=e.install)||void 0===t||t.call(e,this._core,this),this._installedSubPlugins.push(e.name)}))}_reset(){Ra.reset()}_dispose(){this._reset();const{notificationCenter:e,InnerEvent:t}=this._core;e.unSubscribeInnerEvent(t.LOGOUT,this._reset,this),e.unSubscribeInnerEvent(t.DESTROY,this._dispose,this)}};const Dc="friend",Rc=100,Lc=2700,Nc=2710,bc=2711,wc=2716,Pc=2742,Uc=30539,Gc="Tag_SNS_IM_",kc={GROUP:`${Gc}Group`,REMARK:`${Gc}Remark`,ADDSOURCE:`${Gc}AddSource`,ADDWORDING:`${Gc}Wording`,ADDTIME:`${Gc}AddTime`},Fc="Update_Type_Add",$c="Update_Type_Delete",qc="add",xc="remove",Vc="rename",Bc=e=>void 0===e;function jc(e,t){return a(this,void 0,void 0,(function*(){return function(e){return Kc(e,"ResultItem",(e=>({to:e.To_Account,resultCode:e.ResultCode,resultInfo:e.ResultInfo})))}(yield t.common.buildAndSendPacket({servcmd:"sns.friend_update",data:e}))}))}function Wc(e,t){return a(this,void 0,void 0,(function*(){return function(e){return Kc(e,"InfoItem",(e=>({userID:e.To_Account,relation:e.Relation,resultCode:e.ResultCode,resultInfo:e.ResultInfo})))}(yield t.common.buildAndSendPacket({servcmd:"sns.friend_check",data:e}))}))}function Kc(e,t="ResultItem",s=e=>({userID:e.To_Account,resultCode:e.ResultCode,resultInfo:e.ResultInfo})){const{[t]:o=[],ActionStatus:n,ErrorCode:i,ErrorInfo:r,ErrorDisplay:a}=e;return{resultList:o.map(s),actionStatus:n,errorCode:i,errorInfo:r,errorDisplay:a}}const Hc={[kc.REMARK]:(e,t)=>{e.remark=t},[kc.GROUP]:(e,t)=>{e.groupList=t?JSON.parse(JSON.stringify(t)):[]},[kc.ADDSOURCE]:(e,t)=>{e.source=t},[kc.ADDWORDING]:(e,t)=>{e.wording=t},[kc.ADDTIME]:(e,t)=>{e.addTime=t}};let Yc=class{constructor(e){var t;this.userID="",this.source="",this.wording="",this.remark="",this.addTime=0,this.groupList=[],this.friendCustomField=[];const{userID:s,tagValueList:o=[],core:n}=e,i=null===(t=n.user.userProfile)||void 0===t?void 0:t.createProfile(s,o);this.userID=s,this.profile=i,o.forEach((e=>{const{tag:t,value:s}=e;t.indexOf("Tag_Profile_Custom")>-1&&this.friendCustomField.push({key:t,value:s});const o=Hc[t];null==o||o(this,s)}))}update(e){const t=[];this.friendCustomField.forEach((e=>{t.push(e.key)})),e.forEach((e=>{const{tag:s,value:o}=e;s.indexOf("Tag_Profile_Custom")>-1&&(t.indexOf(s)>-1?this.friendCustomField.forEach((e=>{e.key===s&&(e.value=o)})):this.friendCustomField.push({key:s,value:o}));const n=Hc[s];null==n||n(this,o)}))}};var zc=new class{constructor(){this._startIndex=0,this._standardSequence=0,this._customSequence=0}init(e){this._core=e;const{helper:t,constants:s}=e;t.registerApi({apiName:"getFriendList",context:this,methodName:"getFriendListFromCache"}),t.registerApi({apiName:"getFriendProfile",context:this}),t.registerApi({apiName:"addFriend",context:this}),t.registerApi({apiName:"deleteFriend",context:this}),t.registerApi({apiName:"updateFriend",context:this}),t.registerApi({apiName:"checkFriend",context:this}),t.registerWorkflowStep(s.WORKFLOW_NAME.SYNC_SERVER_INFO_AFTER_RE_ONLINE,s.WORKFLOW_STEP.FRIEND_RECOVER,this.syncFriendListFromServer,this)}getFriendListFromCache(){return a(this,void 0,void 0,(function*(){const{userStore:e}=this._core.appStore,t=[...e.getFriendMap().values()];return console.log(`${Dc} getFriendListFromCache, data `,t),{code:0,data:t}}))}syncFriendListFromServer(){return a(this,void 0,void 0,(function*(){var e;try{console.log(`${Dc} syncFriendListFromServer`);const t={From_Account:null===(e=this._core.store.get("login"))||void 0===e?void 0:e.userId,StartIndex:this._startIndex,StandardSequence:this._standardSequence,CustomSequence:this._customSequence},s=yield function(e,t){return a(this,void 0,void 0,(function*(){return function(e){const{UserDataItem:t=[],StandardSequence:s,CustomSequence:o,FriendNum:n,CompleteFlag:i,NextStartIndex:r,ActionStatus:a,ErrorCode:c,ErrorInfo:l,ErrorDisplay:u}=e;return{friendList:t.map((e=>{var t;return{userID:e.To_Account,tagValueList:null===(t=e.ValueItem)||void 0===t?void 0:t.map((e=>({tag:e.Tag,value:e.Value})))}})),standardSequence:s,customSequence:o,friendNumber:n,completeFlag:i,nextStartIndex:r,actionStatus:a,errorCode:c,errorInfo:l,errorDisplay:u}}(yield t.common.buildAndSendPacket({servcmd:"sns.friend_get",data:e}))}))}(t,this._core),{friendList:o,nextStartIndex:n,standardSequence:i,customSequence:r,completeFlag:c}=s;this._startIndex=n,this._standardSequence=i,this._customSequence=r,this._processFriendList(o),0===c?yield this.syncFriendListFromServer():(this._emitFriendListUpdated(),this._fetchFriendProfile()),console.log(`${Dc} syncFriendListFromServer ok`)}catch(e){throw console.error(`${Dc} syncFriendListFromServer error:`,e),e}}))}getFriendProfile(e){return a(this,void 0,void 0,(function*(){var t;try{console.log(`${Dc} getFriendProfile params:`,e);let{userIDList:s}=e;s.length>Rc&&(s=s.slice(0,Rc));const{friendUserIdList:o,unFriendUserIdList:n}=this.partitionByIsFriend(s),i=this._createNonFriendErrorList(n);if(0===o.length)return{code:0,data:{friendList:[],failureUserIDList:i}};const r={From_Account:null===(t=this._core.store.get("login"))||void 0===t?void 0:t.userId,To_Account:o},c=(yield function(e,t){return a(this,void 0,void 0,(function*(){return function(e){const{InfoItem:t=[],ActionStatus:s,ErrorCode:o,ErrorInfo:n,ErrorDisplay:i}=e;return{friendProfileList:t.map((e=>{var t;return{userID:e.To_Account,resultCode:e.ResultCode,resultInfo:e.ResultInfo,relation:e.Relation,standardSequence:e.StandardSequence,customSequence:e.CustomSequence,profileItem:(null===(t=e.SnsProfileItem)||void 0===t?void 0:t.map((e=>({tag:e.Tag,value:e.Value}))))||[]}})),actionStatus:s,errorCode:o,errorInfo:n,errorDisplay:i}}(yield t.common.buildAndSendPacket({servcmd:"sns.friend_get_specified",data:e}))}))}(r,this._core))||{},{successProfiles:l,failedProfiles:u}=this._processFriendProfileResponse(c);return{code:0,data:{friendList:l,failureUserIDList:[...u,...i]}}}catch(e){throw console.error(`${Dc} getFriendProfile error:`,e),e}}))}addFriend(e){return a(this,void 0,void 0,(function*(){var t;try{console.log(`${Dc} addFriend options:`,e);const{helper:s,store:o}=this._core,{to:n,source:i,type:r,wording:c,remark:l,groupName:u}=e,d={From_Account:null===(t=o.get("login"))||void 0===t?void 0:t.userId,AddFriendItem:[{To_Account:n,AddSource:i,AddWording:c,GroupName:u,Remark:l}],AddType:r},h=yield function(e,t){return a(this,void 0,void 0,(function*(){return Kc(yield t.common.buildAndSendPacket({servcmd:"sns.friend_add",data:e}))}))}(d,this._core),{resultList:p=[]}=h,{userID:g,resultCode:_}=p[0];if(0===_)return console.log(`${Dc} addFriend ok`),{code:0,data:{userID:g}};if(_===Uc)return console.log(`${Dc} addFriend wait for the other party to agree`),{code:0,data:{userID:g,code:_,message:"wait for the other party to agree"}};throw new s.ChatError({functionName:"addFriend",code:_})}catch(e){throw console.error(`${Dc} addFriend error:`,e),e}}))}deleteFriend(e){return a(this,void 0,void 0,(function*(){var t;try{console.log(`${Dc} deleteFriend options:`,e);const{store:s}=this._core;let{userIDList:o,type:n}=e;const i=null===(t=s.get("login"))||void 0===t?void 0:t.userId;o.length>1e3&&(console.warn(`${Dc} deleteFriend the length of userIDList cannot exceed:`,1e3),o=o.slice(0,Rc));const{friendUserIdList:r,unFriendUserIdList:c}=this.partitionByIsFriend(o);if(0===r.length)return{code:0,data:{friendList:[],failureUserIDList:this._createNonFriendErrorList(c)}};const l={From_Account:i,To_Account:r,DeleteType:n},u=yield function(e,t){return a(this,void 0,void 0,(function*(){return Kc(yield t.common.buildAndSendPacket({servcmd:"sns.friend_delete",data:e}))}))}(l,this._core),{successUserIDList:d,failureUserIDList:h}=this._processOperationResult({resultList:u.resultList,includeRelation:!1});return console.log(`${Dc} deleteFriend ok`),{code:0,data:{successUserIDList:d,failureUserIDList:h}}}catch(e){throw console.error(`${Dc} deleteFriend error:`,e),e}}))}updateFriend(e){return a(this,void 0,void 0,(function*(){var t;try{console.log(`${Dc} updateFriend options:`,e);const{userID:s,remark:o,friendCustomField:n}=e,{helper:i,store:r,appStore:{userStore:a}}=this._core,c=null===(t=r.get("login"))||void 0===t?void 0:t.userId;if(!a.getFriendMap().has(s))throw new i.ChatError({functionName:"updateFriend",code:Lc});const l={From_Account:c,UpdateItem:[{To_Account:s,SnsItem:this._buildSnsItemList(o,n)}]},u=yield jc(l,this._core),{resultList:d}=u,{to:h,resultCode:p,resultInfo:g}=d[0];if(Bc(p)||0===p){return{code:0,data:this._updateLocalFriend({userID:h,remark:o,friendCustomField:n})}}throw new i.ChatError({functionName:"updateFriend",code:p,message:g})}catch(e){throw console.error(`${Dc} updateFriend error:`,e),e}}))}checkFriend(e){return a(this,void 0,void 0,(function*(){var t;try{console.log(`${Dc} checkFriend options:`,e);const{userIDList:s,type:o}=e,{OuterConstant:n,store:i}=this._core,r=null===(t=i.get("login"))||void 0===t?void 0:t.userId,a={From_Account:r,To_Account:s,CheckType:o===n.SNS_CHECK_TYPE_SINGLE?o:n.SNS_CHECK_TYPE_BOTH},c=yield Wc(a,this._core),{successUserIDList:l=[],failureUserIDList:u=[]}=this._processOperationResult({resultList:c.resultList,includeRelation:!0});return{code:0,data:{successUserIDList:l,failureUserIDList:u}}}catch(e){throw console.error(`${Dc} checkFriend error:`,e),e}}))}dispose(){this.reset();const{notificationCenter:e,InnerEvent:t}=this._core;e.unSubscribeInnerEvent(t.LOGOUT,this.reset,this)}reset(){const{userStore:e}=this._core.appStore;e.getFriendMap().clear(),this._startIndex=0,this._standardSequence=0,this._customSequence=0}updateFriendList(e){return a(this,void 0,void 0,(function*(){console.log(`${Dc} updateFriendList data:`,e);const{userStore:t}=this._core.appStore,{addedFriendList:s=[],removedFriendList:o=[]}=e;s.length>0&&(s.forEach((e=>{const s=new Yc({userID:e,core:this._core});t.getFriendMap().set(e,s)})),yield this.getFriendProfile({userIDList:s}),this._emitFriendListUpdated()),o.length>0&&(o.forEach((e=>{t.getFriendMap().delete(e)})),this._emitFriendListUpdated())}))}updateFriendInfo(e){console.log(`${Dc} updateFriendInfo data: `,e);const{appStore:{userStore:t,conversationStore:s},utils:{isEmpty:o}}=this._core,{userID:n,tagValueList:i}=e[0]||{},r=t.getFriend(n);if(o(i)||!r)return;const a=i.map((e=>({tag:e.BytesTag,value:e.BytesValue})));a.forEach((e=>{var t;const{tag:o,value:i}=e,c=null===(t=s.getConversation(`C2C${n}`))||void 0===t?void 0:t.remark;o===kc.REMARK&&i!==c&&s.updateConversation(`C2C${n}`,{remark:i}),r.update(a)})),this._emitFriendListUpdated()}_processFriendList(e){const{utils:{isEmpty:t},appStore:{userStore:s}}=this._core;t(e)||e.forEach((e=>{const{userID:t,tagValueList:o}=e;if(this._isInvalidFriend(t))return;const n=new Yc({userID:t,tagValueList:o,core:this._core});s.getFriendMap().set(t,n)}))}_isInvalidFriend(e){return"@TLS#NOT_FOUND"===e||""===e}_fetchFriendProfile(){return a(this,void 0,void 0,(function*(){try{console.log(`${Dc} _fetchFriendProfile`);const{appStore:{userStore:e},user:{userProfile:t}}=this._core,s=[...e.getFriendMap().keys()],o=100,n=Math.ceil(s.length/o);for(let i=0;i<n;i++){const n=i*o,r=Math.min(n+o,s.length),a=s.slice(n,r),c=yield null==t?void 0:t.getUserProfile({userIDList:a});if(c&&c.data){c.data.forEach((t=>{const s=e.getFriend(t.userID);s&&(s.profile=t)}))}this._emitFriendListUpdated()}}catch(e){throw console.error(`${Dc} _fetchFriendProfile error:`,e),e}}))}_emitFriendListUpdated(){const{notificationCenter:e,OuterEvent:t,appStore:{userStore:s}}=this._core,o=Array.from(s.getFriendMap().values());console.log(`${Dc} _emitFriendListUpdated friendList:`,o),e.emitOuterEvent(t.FRIEND_LIST_UPDATED,{name:t.FRIEND_LIST_UPDATED,data:o})}_updateCustomField(e,t){if(!Array.isArray(e)||!Array.isArray(t))return!1;let s=!1;return t.forEach((({key:t,value:o})=>{const n=e.find((e=>e.key===t));n?n.value!==o&&(n.value=o,s=!0):(e.push({key:t,value:o}),s=!0)})),s}_updateLocalFriend(e){const{userStore:t}=this._core.appStore,{userID:s,remark:o,friendCustomField:n}=e,i=t.getFriend(s);if(i)return Bc(o)||(i.remark=o),Array.isArray(n)&&n.length>0&&this._updateCustomField(i.friendCustomField,n),this._emitFriendListUpdated(),i}_processOperationResult(e){const{resultList:t,includeRelation:s=!1}=e,{isEmpty:o}=this._core.utils,n=[],i=[];return Array.isArray(t)&&!o(t)&&t.forEach((e=>{const{userID:t,relation:o,resultCode:r,resultInfo:a}=e;if(Bc(r)||0===r){const e={userID:t};s&&(e.code=0,e.relation=o),n.push(e)}else i.push({userID:t,code:r,message:a})})),{successUserIDList:n,failureUserIDList:i}}_createNonFriendErrorList(e){return e.map((e=>({userID:e,code:Lc,message:"The specified userID is not my friend"})))}_buildSnsItemList(e,t){const s=[];return Bc(e)||s.push({Tag:kc.REMARK,Value:e}),Array.isArray(t)&&t.length>0&&t.forEach((e=>{s.push({tag:e.key,value:e.value})})),s}_processFriendProfileResponse(e){const{friendProfileList:t=[]}=e,{userStore:s}=this._core.appStore,o=[],n=[];return t.forEach((e=>{const{userID:t,resultCode:i,resultInfo:r,profileItem:a}=e;if(0===i){const e=new Yc({userID:t,tagValueList:a,core:this._core});o.push(e),s.getFriendMap().set(t,e)}else n.push({userID:t,code:i,message:r})})),console.log(`${Dc} _processFriendProfileResponse successProfiles:`,o),{successProfiles:o,failedProfiles:n}}partitionByIsFriend(e){const t=[],s=[];return e.forEach((e=>{const{userStore:o}=this._core.appStore;o.getFriendMap().has(e)?t.push(e):s.push(e)})),console.log(`${Dc} partitionByIsFriend, friendUserIdList: ${t}, unFriendUserIdList: ${s}`),{friendUserIdList:t,unFriendUserIdList:s}}isMyFriend(e){const{userStore:t}=this._core.appStore;return t.getFriendMap().has(e)}};var Jc=new class{init(e){this.core=e}};function Zc(e){return a(this,void 0,void 0,(function*(){var t;const{store:s,common:o}=Jc.core,n={From_Account:null===(t=s.get("login"))||void 0===t?void 0:t.userId,ResponseFriendItem:[{To_Account:e.userID,ResponseAction:e.type,Remark:e.remark}]};return el(yield o.buildAndSendPacket({servcmd:"sns.friend_response",data:n}))}))}function Xc(e){return a(this,void 0,void 0,(function*(){var t;const{store:s,common:o}=Jc.core,n={From_Account:null===(t=s.get("login"))||void 0===t?void 0:t.userId,ResponseFriendItem:[{To_Account:e.userID,ResponseAction:"Response_Action_Reject"}]};return el(yield o.buildAndSendPacket({servcmd:"sns.friend_response",data:n}))}))}function Qc(e){return a(this,void 0,void 0,(function*(){var t;const{store:s,common:o}=Jc.core,n={From_Account:null===(t=s.get("login"))||void 0===t?void 0:t.userId,To_Account:[e.userID],PendencyType:e.type};return el(yield o.buildAndSendPacket({servcmd:"sns.pendency_delete",data:n}))}))}function el(e){const{ResultItem:t=[],ActionStatus:s,ErrorCode:o,ErrorInfo:n,ErrorDisplay:i}=e;return{resultList:t.map((e=>({userID:e.To_Account,resultCode:e.ResultCode,resultInfo:e.ResultInfo}))),actionStatus:s,errorCode:o,errorInfo:n,errorDisplay:i}}var tl=new class{constructor(){this._friendApplicationMap=new Map,this._unreadCount=0,this._startTime=0,this._currentSequence=0}init(e){this._core=e;const{helper:t}=e;t.registerApi({apiName:"getFriendApplicationList",context:this,methodName:"getFriendApplicationListFromCache"}),t.registerApi({apiName:"acceptFriendApplication",context:this}),t.registerApi({apiName:"refuseFriendApplication",context:this}),t.registerApi({apiName:"deleteFriendApplication",context:this}),t.registerApi({apiName:"setFriendApplicationRead",context:this})}getFriendApplicationListFromCache(){return a(this,void 0,void 0,(function*(){const e=[...this._friendApplicationMap.values()];return console.log(`${Dc} getFriendApplicationListFromCache friendApplicationList:`,e),{code:0,data:{friendApplicationList:e,unreadCount:this._unreadCount}}}))}syncFriendApplicationListFromServer(){return a(this,void 0,void 0,(function*(){const e="syncFriendApplicationListFromServer";console.log(`${Dc} ${e}`);try{const e=yield function(e){return a(this,void 0,void 0,(function*(){var t;const{store:s,OuterConstant:o,common:n}=Jc.core,i={From_Account:null===(t=s.get("login"))||void 0===t?void 0:t.userId,PendencyType:o.SNS_APPLICATION_TYPE_BOTH,MaxLimited:Rc,StartTime:e.startTime,LastSequence:e.currentSequence};return function(e){const{PendencyItem:t=[],StartTime:s,UnreadPendencyCount:o,CurrentSequence:n,ActionStatus:i,ErrorCode:r,ErrorInfo:a,ErrorDisplay:c}=e;return{resultList:t.map((e=>({userID:e.To_Account,time:e.AddTime,source:e.AddSource,wording:e.AddWording,nick:e.Nick,type:e.PendencyType,image:e.Image}))),startTime:s,unreadCount:o,currentSequence:n,actionStatus:i,errorCode:r,errorInfo:a,errorDisplay:c}}(yield n.buildAndSendPacket({servcmd:"sns.pendency_get",data:i}))}))}({startTime:this._startTime,currentSequence:this._currentSequence}),{resultList:t,unreadCount:s,startTime:o,currentSequence:n}=e;this._startTime=o,this._currentSequence=n,this._unreadCount=s,this._friendApplicationMap.clear(),Array.isArray(t)&&t.forEach((e=>{const{userID:t,type:s}=e,o=this._createFriendApplication(e);this._friendApplicationMap.set(`${t}_${s}`,o)})),this._emitApplicationListUpdated()}catch(t){const s=new this._core.helper.ChatError({functionName:e,code:null==t?void 0:t.errorCode,message:null==t?void 0:t.errorInfo});throw console.error(`${Dc} ${e} error:`,s),s}}))}acceptFriendApplication(e){return a(this,void 0,void 0,(function*(){return this._operationApplication({functionName:"acceptFriendApplication",options:e,protocolFunction:Zc})}))}refuseFriendApplication(e){return a(this,void 0,void 0,(function*(){return this._operationApplication({functionName:"refuseFriendApplication",options:e,protocolFunction:Xc})}))}deleteFriendApplication(e){return a(this,void 0,void 0,(function*(){const{userID:t,type:s}=e;return this._checkApplicationExists(t,s,"deleteFriendApplication"),this._operationApplication({functionName:"deleteFriendApplication",options:e,protocolFunction:Qc})}))}_checkApplicationExists(e,t,s){if(!this._friendApplicationMap.has(`${e}_${t}`))throw new this._core.helper.ChatError({functionName:s,code:wc})}_operationApplication(e){return a(this,void 0,void 0,(function*(){const{functionName:t,options:s,protocolFunction:o}=e;console.log(`${Dc} ${t} options:`,s);try{const e=yield o(s),{resultList:n=[]}=e,{resultCode:i,resultInfo:r}=n[0];if(0===i)return console.log(`${Dc} ${t} ok`),{code:0,data:{}};throw{errorCode:i,errorInfo:r}}catch(e){const s=new this._core.helper.ChatError({functionName:t,code:null==e?void 0:e.errorCode,message:null==e?void 0:e.errorInfo});throw console.error(`${Dc} ${t} error:`,s),s}}))}setFriendApplicationRead(){return a(this,void 0,void 0,(function*(){const e="setFriendApplicationRead";console.log(`${Dc} ${e}`);try{return yield function(){return a(this,void 0,void 0,(function*(){var e;const{store:t,common:s}=Jc.core,o={From_Account:null===(e=t.get("login"))||void 0===e?void 0:e.userId,LatestPendencyTimeStamp:(n=Math.floor(Date.now()/1e3),i=0,Math.round(Number(n)*Math.pow(10,i))/Math.pow(10,i))};var n,i;return function(e){const{ActionStatus:t,ErrorCode:s,ErrorInfo:o,ErrorDisplay:n}=e;return{actionStatus:t,errorCode:s,errorInfo:o,errorDisplay:n}}(yield s.buildAndSendPacket({servcmd:"sns.pendency_report",data:o}))}))}(),this._unreadCount=0,this._emitApplicationListUpdated(),console.log(`${Dc} ${e} ok`),{code:0,data:{}}}catch(t){const s=new this._core.helper.ChatError({functionName:e,code:null==t?void 0:t.errorCode,message:null==t?void 0:t.errorInfo});throw console.error(`${Dc} ${e} error:`,s),s}}))}updateFriendApplicationList(e){const{from:t,addedApplicationList:s=[],removedApplicationList:o=[]}=e;console.log(`${Dc} updateFriendApplicationList data:`,e);const{isEmpty:n}=this._core.utils;n(s)||this.onApplicationAdded(s,t),n(o)||this.onApplicationDeleted()}onApplicationAdded(e,t){var s;const{store:o,OuterConstant:n}=this._core,i=t===(null===(s=o.get("login"))||void 0===s?void 0:s.userId)?n.SNS_APPLICATION_SENT_BY_ME:n.SNS_APPLICATION_SENT_TO_ME;e.forEach((e=>{const t=`${e.userID}_${i}`;i!==n.SNS_APPLICATION_SENT_TO_ME||this._friendApplicationMap.has(t)||(this._unreadCount+=1),this._friendApplicationMap.set(t,this._createFriendApplication(Object.assign(Object.assign({},e),{type:i})))})),this._emitApplicationListUpdated()}onApplicationDeleted(){this._startTime=0,this._currentSequence=0,this.syncFriendApplicationListFromServer()}onApplicationRead(){this._unreadCount=0,this._emitApplicationListUpdated()}reset(){this._startTime=0,this._currentSequence=0,this._unreadCount=0,this._friendApplicationMap.clear()}dispose(){this.reset()}_createFriendApplication(e){return{userID:e.userID||"",nick:e.nick||"",avatar:e.avatar||"",time:e.time||0,source:e.source||"",wording:e.wording||"",type:e.type||""}}_emitApplicationListUpdated(){console.log(`${Dc} _emitApplicationListUpdated`);const{notificationCenter:e,OuterEvent:t}=this._core;e.emitOuterEvent(t.FRIEND_APPLICATION_LIST_UPDATED,{name:t.FRIEND_APPLICATION_LIST_UPDATED,data:{friendApplicationList:[...this._friendApplicationMap.values()],unreadCount:this._unreadCount}})}};function sl(){return a(this,void 0,void 0,(function*(){const{common:e}=Jc.core,t={From_Account:e.getCurrentUserID(),LastSequence:0,NeedFriend:"Need_Friend_Type_Yes"};return function(e){return ll(e,(e=>({name:e.GroupName,userIDList:e.To_Account||[],count:e.FriendNumber})))}(yield e.buildAndSendPacket({servcmd:"sns.group_get",data:t}))}))}function ol(e){return a(this,void 0,void 0,(function*(){const{name:t,userIDList:s}=e,{common:o}=Jc.core,n={From_Account:o.getCurrentUserID(),GroupName:[t],To_Account:s};return function(e){return ll(e,(e=>({userID:e.To_Account,resultCode:e.ResultCode,resultInfo:e.ResultInfo})))}(yield o.buildAndSendPacket({servcmd:"sns.group_add",data:n}))}))}function nl(e){return a(this,void 0,void 0,(function*(){const{common:t}=Jc.core,s={From_Account:t.getCurrentUserID(),GroupName:[e.name]};return function(e){return ll(e)}(yield t.buildAndSendPacket({servcmd:"sns.group_delete",data:s}))}))}function il(e){return a(this,void 0,void 0,(function*(){const{common:t}=Jc.core,{name:s,userIDList:o}=e,n=cl(o,Fc),i={From_Account:t.getCurrentUserID(),GroupOldName:s,UpdateGroupItem:n};return function(e){return ll(e,(e=>({userID:e.To_Account,updateType:e.UpdateType,resultCode:e.ResultCode,resultInfo:e.ResultInfo})))}(yield t.buildAndSendPacket({servcmd:"sns.group_update",data:i}))}))}function rl(e){return a(this,void 0,void 0,(function*(){const{common:t}=Jc.core,{name:s,userIDList:o}=e,n=cl(o,$c),i={From_Account:t.getCurrentUserID(),GroupOldName:s,UpdateGroupItem:n};return function(e){return ll(e,(e=>({userID:e.To_Account,updateType:e.UpdateType,resultCode:e.ResultCode,resultInfo:e.ResultInfo})))}(yield t.buildAndSendPacket({servcmd:"sns.group_update",data:i}))}))}function al(e){return a(this,void 0,void 0,(function*(){const{common:t}=Jc.core,{oldName:s,newName:o}=e,n={From_Account:t.getCurrentUserID(),GroupOldName:s,GroupNewName:o};return function(e){return ll(e)}(yield t.buildAndSendPacket({servcmd:"sns.group_update",data:n}))}))}function cl(e,t){return e.filter((e=>zc.isMyFriend(e))).map((e=>({To_Account:e,UpdateType:t})))}function ll(e,t){const{CurrentSequence:s,ActionStatus:o,ErrorCode:n,ErrorInfo:i,ErrorDisplay:r,ResultItem:a=[]}=e,c={currentSequence:s,actionStatus:o,errorCode:n,errorInfo:i,errorDisplay:r};return t&&a.length>0?Object.assign(Object.assign({},c),{resultList:a.map(t)}):c}class ul{constructor(e){const{name:t="",userIDList:s=[]}=e;this.name=t,this.userIDList=s,this.count=s.length}addToUserIDList(e){-1===this.userIDList.indexOf(e)&&(this.userIDList.push(e),this.count=this.userIDList.length)}removeFromUserIDList(e){const t=this.userIDList.indexOf(e);t>-1&&(this.userIDList.splice(t,1),this.count=this.userIDList.length)}}var dl=new class{constructor(){this._friendGroupMap=new Map}init(e){this._core=e;const{helper:t}=e;t.registerApi({apiName:"getFriendGroupList",context:this,methodName:"getFriendGroupListFromCache"}),t.registerApi({apiName:"createFriendGroup",context:this}),t.registerApi({apiName:"deleteFriendGroup",context:this}),t.registerApi({apiName:"addToFriendGroup",context:this}),t.registerApi({apiName:"removeFromFriendGroup",context:this}),t.registerApi({apiName:"renameFriendGroup",context:this})}getFriendGroupListFromCache(){return a(this,void 0,void 0,(function*(){const e=[...this._friendGroupMap.values()];return console.log(`${Dc} getFriendGroupListFromCache, data: `,e),{code:0,data:e}}))}syncFriendGroupListFromServer(){return a(this,void 0,void 0,(function*(){const e="syncFriendGroupListFromServer";console.log(`${Dc} ${e}`);try{const t=yield sl(),{resultList:s=[]}=t;this._core.helper.isEmpty(s)&&console.log(`${Dc} ${e} ok. count: 0`),s.forEach((e=>{const t=new ul(e);this._friendGroupMap.set(e.name,t)})),this._emitGroupListUpdated()}catch(t){this._handleError(e,t)}}))}createFriendGroup(e){return a(this,void 0,void 0,(function*(){const t="createFriendGroup";console.log(`${Dc} ${t} params:`,e);try{const{name:s}=e;this._checkGroupExist(t,s);const o=yield ol(e),{successUserIDList:n,failureUserIDList:i}=this._parseCreateGroupResponse(o),r=new ul({name:s,userIDList:n});return this._friendGroupMap.set(s,r),this._emitGroupListUpdated(),{code:0,data:{friendGroup:r,failureUserIDList:i}}}catch(e){this._handleError(t,e)}}))}deleteFriendGroup(e){return a(this,void 0,void 0,(function*(){const t="deleteFriendGroup";console.log(`${Dc} ${t} params:`,e);try{const{name:s}=e;this._checkGroupNotExist(t,s),yield nl(e);const o=this._friendGroupMap.get(s);return o&&(this._updateFriendGroup({name:s,userIDList:o.userIDList,action:xc}),this._friendGroupMap.delete(s)),this._emitGroupListUpdated(),{code:0,data:o}}catch(e){this._handleError(t,e)}}))}addToFriendGroup(e){return a(this,void 0,void 0,(function*(){return this._updateFriendGroupMember({functionName:"addToFriendGroup",params:e,protocolFunction:il})}))}removeFromFriendGroup(e){return a(this,void 0,void 0,(function*(){return this._updateFriendGroupMember({functionName:"removeFromFriendGroup",params:e,protocolFunction:rl})}))}renameFriendGroup(e){return a(this,void 0,void 0,(function*(){const t="renameFriendGroup";console.log(`${Dc} ${t} params:`,e);try{const{oldName:s,newName:o}=e;this._checkGroupNotExist(t,s),this._checkGroupExist(t,o),yield al(e);const n=this._updateGroupNameInCache(s,o);return n&&this._updateFriendGroup({name:s,userIDList:n.userIDList,action:Vc,newName:o}),this._emitGroupListUpdated(),{code:0,data:n}}catch(e){this._handleError(t,e)}}))}_updateFriendGroupMember(e){return a(this,void 0,void 0,(function*(){const{functionName:t,params:s,protocolFunction:o}=e;console.log(`${Dc} ${t} params:`,s);try{const{name:e}=s;this._checkGroupNotExist(t,e);const n=yield o(s),{friendGroup:i,failureUserIDList:r}=this._parseUpdateFriendGroupResponse(e,n);return this._emitGroupListUpdated(),{code:0,data:{friendGroup:i,failureUserIDList:r}}}catch(e){this._handleError(t,e)}}))}_updateGroupNameInCache(e,t){const s=this._friendGroupMap.get(e);return s&&(s.name=t,this._friendGroupMap.delete(e),this._friendGroupMap.set(t,s)),s}_parseCreateGroupResponse(e){const{resultList:t=[]}=e,s=[],o=[];return t.forEach((({userID:e,resultCode:t,resultInfo:n})=>{Bc(t)||0===t?s.push(e):o.push({userID:e,code:t,message:n})})),{successUserIDList:s,failureUserIDList:o}}_parseUpdateFriendGroupResponse(e,t){const{resultList:s=[]}=t,o=this._friendGroupMap.get(e),n=[],i=[],r=[];return s.forEach((t=>{0===t.resultCode?o&&(t.updateType===Fc?this._addFriendToGroup(e,t.userID,o,i):t.updateType===$c&&this._removeFriendFromGroup(e,t.userID,o,r)):n.push({userID:t.userID,code:t.resultCode,message:t.resultInfo})})),{friendGroup:o,failureUserIDList:n}}_addFriendToGroup(e,t,s,o){s.addToUserIDList(t),o.push(t),this._updateFriendGroup({name:e,userIDList:o,action:qc})}_removeFriendFromGroup(e,t,s,o){s.removeFromUserIDList(t),o.push(t),this._updateFriendGroup({name:e,userIDList:o,action:xc})}_emitGroupListUpdated(){const{notificationCenter:e,OuterEvent:t}=this._core,s=[...this._friendGroupMap.values()];console.log(`${Dc} _emitGroupListUpdated friendGroupList:`,s),e.emitOuterEvent(t.FRIEND_GROUP_LIST_UPDATED,{name:t.FRIEND_GROUP_LIST_UPDATED,data:s})}_checkGroupNotExist(e,t){if(!this._friendGroupMap.has(t))throw new this._core.helper.ChatError({functionName:e,code:bc})}_checkGroupExist(e,t){if(this._friendGroupMap.has(t))throw new this._core.helper.ChatError({functionName:e,code:Nc})}_updateFriendGroup(e){const{name:t,userIDList:s,action:o,newName:n}=e,{userStore:i}=this._core.appStore;console.log(`${Dc} updateFriendGroup`,{name:t,userIDList:s,action:o,newName:n}),t&&!this._core.utils.isEmpty(s)&&s.forEach((e=>{const s=i.getFriend(e);if(!s)return;const{groupList:r}=s;switch(o){case qc:-1===r.indexOf(t)&&(r.push(t),s.count=r.length);break;case xc:{const e=r.indexOf(t);e>-1&&(r.splice(e,1),s.count=r.length);break}case Vc:{if(!n)return;const e=r.indexOf(t);-1!==e&&(r[e]=n);break}}}))}_handleError(e,t){const s=new this._core.helper.ChatError({functionName:e,code:null==t?void 0:t.errorCode,message:null==t?void 0:t.errorInfo});throw console.error(`${Dc} ${e} error:`,s),s}reset(){this._friendGroupMap.clear()}dispose(){this.reset()}};function hl(e){return e&&0!==e.length?e.map((e=>({userID:e.To_Account,addBlackTimeStamp:e.AddBlackTimeStamp}))):[]}var pl=new class{constructor(){this._blacklistMap=new Map,this._retryCount=0,this._startIndex=0}init(e){this._core=e;const{helper:t,constants:s}=e;t.registerApi({apiName:"getBlacklist",context:this,methodName:"getBlacklistFromCache"}),t.registerApi({apiName:"addToBlacklist",context:this}),t.registerApi({apiName:"removeFromBlacklist",context:this}),t.registerWorkflowStep(s.WORKFLOW_NAME.SYNC_SERVER_INFO_AFTER_RE_ONLINE,s.WORKFLOW_STEP.BLACKLIST_RECOVER,this.syncBlacklistFromServer,this)}getBlacklistFromCache(){return a(this,void 0,void 0,(function*(){return console.log(`${Dc} getBlacklistFromCache`),{code:0,data:Array.from(this._blacklistMap.keys())}}))}syncBlacklistFromServer(){return a(this,void 0,void 0,(function*(){try{console.log(`${Dc} syncBlacklistFromServer`);const e={From_Account:this._core.common.getCurrentUserID(),MaxLimited:Rc,StartIndex:this._startIndex},t=yield function(e,t){return a(this,void 0,void 0,(function*(){const{helper:s,channel:o}=t,n="sns.black_list_get",i=s.generateProtocolData({servcmd:n,data:e}),r=`${i.head.seq}${n}`,a=yield o.sendPacket(i,{requestId:r}),{BlackListItem:c=[],StartIndex:l=0}=a;return{blackList:hl(c),startIndex:l}}))}(e,this._core),{blackList:s=[],startIndex:o=0}=t;return this._startIndex=o,this._addBlacklistMap(s),this._emitBlackListUpdated(),0!==this._startIndex&&this._retryCount<10?(this._retryCount++,yield this.syncBlacklistFromServer()):this._retryCount=0,{code:0,data:Array.from(this._blacklistMap.keys())}}catch(e){throw this._retryCount=0,console.error(`${Dc} syncBlacklistFromServer error:`,e),e}}))}addToBlacklist(e){return a(this,void 0,void 0,(function*(){try{console.log(`${Dc} addToBlacklist options:`,e);const t=this._preprocessBlacklist(e),s={From_Account:this._core.common.getCurrentUserID(),To_Account:t},o=yield function(e,t){return a(this,void 0,void 0,(function*(){const{helper:s,channel:o}=t,n="sns.black_list_add",i=s.generateProtocolData({servcmd:n,data:e}),r=`${i.head.seq}${n}`,a=yield o.sendPacket(i,{requestId:r}),{ResultItem:c=[]}=a;return{blackList:hl(c)}}))}(s,this._core),{blackList:n=[]}=o;return this._addBlacklistMap(n),this._emitBlackListUpdated(),{code:0,data:Array.from(this._blacklistMap.keys())}}catch(e){throw console.error(`${Dc} addToBlacklist error:`,e),e}}))}removeFromBlacklist(e){return a(this,void 0,void 0,(function*(){try{console.log(`${Dc} removeFromBlacklist options:`,e);const t={From_Account:this._core.common.getCurrentUserID(),To_Account:e.userIDList},s=yield function(e,t){return a(this,void 0,void 0,(function*(){const{helper:s,channel:o}=t,n="sns.black_list_delete",i=s.generateProtocolData({servcmd:n,data:e}),r=`${i.head.seq}${n}`,a=yield o.sendPacket(i,{requestId:r}),{ResultItem:c=[]}=a;return{blackList:hl(c)}}))}(t,this._core),{blackList:o=[]}=s;return this._deleteBlacklistMap(o),this._emitBlackListUpdated(),{code:0,data:Array.from(this._blacklistMap.keys())}}catch(e){throw console.error(`${Dc} removeFromBlacklist error:`,e),e}}))}dispose(){this.reset()}reset(){this._retryCount=0,this._startIndex=0,this._blacklistMap.clear()}updateBlacklist(e){console.log(`${Dc} updateBlacklist data:`,e);const{addedBlacklist:t=[],removedBlacklist:s=[]}=e;let o=!1;if(t.length>0){t.some((e=>!this._blacklistMap.has(e)))&&(o=!0,this._addBlacklistMap(t.map((e=>({userID:e})))))}if(s.length>0){s.some((e=>this._blacklistMap.has(e)))&&(o=!0,this._deleteBlacklistMap(s.map((e=>({userID:e})))))}o&&this._emitBlackListUpdated()}_addBlacklistMap(e){console.log(`${Dc} _addBlacklistMap blackList:`,e),e.forEach((e=>{const{userID:t,addBlackTimeStamp:s=Date.now()}=e;t&&!this._blacklistMap.has(t)&&this._blacklistMap.set(t,{userID:t,addBlackTimeStamp:s})}))}_deleteBlacklistMap(e){console.log(`${Dc} _deleteBlacklistMap blackList:`,e),e.forEach((e=>{const{userID:t}=e;t&&this._blacklistMap.has(t)&&this._blacklistMap.delete(t)}))}_preprocessBlacklist(e){let{userIDList:t}=e;const s=this._core.common.getCurrentUserID();if(1===t.length&&t[0]===s)throw new this._core.helper.ChatError({functionName:"addToBlacklist",code:Pc});return t.includes(s)&&(t=e.userIDList.filter((e=>e!==s))),t}_emitBlackListUpdated(){const{notificationCenter:e,OuterEvent:t}=this._core,s=Array.from(this._blacklistMap.keys());console.log(`${Dc} _emitBlackListUpdated blackList:`,s),e.emitOuterEvent(t.BLACKLIST_UPDATED,{name:t.BLACKLIST_UPDATED,data:s})}};const gl={addToBlacklist:{userIDList:{required:!0,rules:["array"],allowEmpty:!1}},removeFromBlacklist:{userIDList:{required:!0,rules:["array"],allowEmpty:!1}},getFriendProfile:{userIDList:{required:!0,rules:["array"],allowEmpty:!1}},addFriend:{to:{required:!0,rules:["string"],allowEmpty:!1},source:{required:!0,rules:["string"],allowEmpty:!1},wording:{required:!1,rules:["string"],allowEmpty:!0},type:{required:!1,rules:["string"],allowEmpty:!0,customValidator:e=>{const{OuterConstant:t}=Jc.core;return e===t.SNS_ADD_TYPE_SINGLE||e===t.SNS_ADD_TYPE_BOTH||"type should be SNS_ADD_TYPE_SINGLE or SNS_ADD_TYPE_BOTH"}},remark:{required:!1,rules:["string"],allowEmpty:!0},groupName:{required:!1,rules:["string"],allowEmpty:!0}},deleteFriend:{userIDList:{required:!0,rules:["array"],allowEmpty:!1},type:{required:!1,rules:["string"],allowEmpty:!0,customValidator:e=>{const{OuterConstant:t}=Jc.core;return e===t.SNS_DELETE_TYPE_SINGLE||e===t.SNS_DELETE_TYPE_BOTH||"type should be SNS_DELETE_TYPE_SINGLE or SNS_DELETE_TYPE_BOTH"}}},checkFriend:{userIDList:{required:!0,rules:["array"],allowEmpty:!1},type:{required:!1,rules:["string"],allowEmpty:!0}},updateFriend:{userID:{required:!0,rules:["string"],allowEmpty:!1},remark:{required:!1,rules:["string"],allowEmpty:!0},friendCustomField:{required:!1,rules:["array"],allowEmpty:!0}},acceptFriendApplication:{userID:{required:!0,rules:["string"],allowEmpty:!1},remark:{required:!1,rules:["string"],allowEmpty:!0},type:{required:!0,rules:["string"],allowEmpty:!1,customValidator:e=>{const{OuterConstant:t}=Jc.core;return e===t.SNS_APPLICATION_AGREE||e===t.SNS_APPLICATION_AGREE_AND_ADD||"type should be SNS_APPLICATION_AGREE or SNS_APPLICATION_AGREE_AND_ADD"}}},refuseFriendApplication:{userID:{required:!0,rules:["string"],allowEmpty:!1}},deleteFriendApplication:{userID:{required:!0,rules:["string"],allowEmpty:!1},type:{required:!0,rules:["string"],allowEmpty:!1,customValidator:e=>{const{OuterConstant:t}=Jc.core;return e===t.SNS_APPLICATION_SENT_TO_ME||e===t.SNS_APPLICATION_SENT_BY_ME||"type should be SNS_APPLICATION_SENT_TO_ME or SNS_APPLICATION_SENT_BY_ME"}}},createFriendGroup:{name:{required:!0,rules:["string"],allowEmpty:!1},userIDList:{required:!0,rules:["array"],allowEmpty:!1}},deleteFriendGroup:{name:{required:!0,rules:["string"],allowEmpty:!1}},addToFriendGroup:{name:{required:!0,rules:["string"],allowEmpty:!1},userIDList:{required:!0,rules:["array"],allowEmpty:!1}},removeFromFriendGroup:{name:{required:!0,rules:["string"],allowEmpty:!1},userIDList:{required:!0,rules:["array"],allowEmpty:!1}},renameFriendGroup:{oldName:{required:!0,rules:["string"],allowEmpty:!1},newName:{required:!0,rules:["string"],allowEmpty:!1}}},_l={getBlacklist:!0,addToBlacklist:!0,removeFromBlacklist:!0,getFriendList:!0,addFriend:!0,deleteFriend:!0,updateFriend:!0,checkFriend:!0,getFriendProfile:!0,getFriendApplicationList:!0,acceptFriendApplication:!0,refuseFriendApplication:!0,deleteFriendApplication:!0,setFriendApplicationRead:!0,getFriendGroupList:!0,createFriendGroup:!0,deleteFriendGroup:!0,addToFriendGroup:!0,removeFromFriendGroup:!0,renameFriendGroup:!0};var ml=new class{install(e){console.log(`${Dc} install`),this._core=e;const{helper:t,notificationCenter:s,InnerEvent:o,constants:{WORKFLOW_NAME:n,WORKFLOW_STEP:i}}=e;Jc.init(e),zc.init(e),tl.init(e),dl.init(e),pl.init(e),t.registerValidateConfig({auth:_l,params:gl}),t.registerWorkflowStep(n.SYNC_SERVER_INFO_AFTER_LOGIN,i.FRIEND_AND_BLACKLIST_SYNC,this.handleLoginSuccess,this),s.subscribeInnerEvent(o.LOGOUT,this.reset,this),s.subscribeInnerEvent(o.MESSAGE_PUSH,s.InnerEventSubType.FRIEND_LIST_MODIFIED,this.onFriendModified,this)}handleLoginSuccess(){console.log(`${Dc} handleLoginSuccess`),pl.syncBlacklistFromServer(),zc.syncFriendListFromServer(),tl.syncFriendApplicationListFromServer(),dl.syncFriendGroupListFromServer()}onFriendModified(e){const{from:t,addedBlacklist:s,removedBlacklist:o,addedFriendList:n,removedFriendList:i,addedApplicationList:r,removedApplicationList:a,friendUpdateInfo:c,reportTime:l}=this._parseFriendListModification(null==e?void 0:e.FriendListMod[0]),{isEmpty:u}=this._core.utils;u(s)&&u(o)||pl.updateBlacklist({addedBlacklist:s,removedBlacklist:o}),u(n)&&u(i)||(zc.updateFriendList({addedFriendList:n,removedFriendList:i}),tl.updateFriendApplicationList({from:t,removedApplicationList:n})),u(c)||zc.updateFriendInfo(c),u(r)&&u(a)||tl.updateFriendApplicationList({from:t,addedApplicationList:r,removedApplicationList:a}),l&&tl.onApplicationRead()}_parseFriendListModification(e){const{PushType:t,From_Account:s,To_Account:o,ReportTime:n,BlackListAdd_Account:i=[],BlackListDel_Account:r=[],FriendAdd_Account:a=[],FriendDel_Account:c=[],PendencyAdd:l=[],FrienPencydDel_Account:u=[],FriendUpInfo:d=[]}=e,h=d.map((e=>({userID:e.Friend_Account,tagValueList:[...e.SNS]})));return{pushType:t,from:s,to:o,reportTime:n,addedBlacklist:i,removedBlacklist:r,addedFriendList:a,removedFriendList:c,addedApplicationList:l.map((e=>({userID:e.PendencyAdd_Account,source:e.AddSource,time:e.AddTime,wording:e.AddWording,nick:e.ProfileImNick}))),friendUpdateInfo:h,removedApplicationList:u}}reset(){console.log(`${Dc} reset`),pl.reset(),zc.reset(),tl.reset(),dl.reset()}dispose(){console.log(`${Dc} dispose`);const{notificationCenter:e,InnerEvent:t}=this._core;e.unSubscribeInnerEvent(t.LOGOUT,this.reset,this),e.unSubscribeInnerEvent(t.MESSAGE_PUSH,e.InnerEventSubType.FRIEND_LIST_MODIFIED,this.onFriendModified,this),pl.dispose(),zc.dispose(),tl.dispose(),dl.dispose()}};const fl=new class{init(e){this.core=e}},vl="Follow",Il="FOLLOW",Sl=3122,El={NONE:0,FOLLOWERS:1,FOLLOWING:2,MUTUAL:3};function Cl(e,t){return a(this,void 0,void 0,(function*(){var s;const{common:o,store:n}=fl.core,i={FollowType:e,From_Account:null===(s=n.get("login"))||void 0===s?void 0:s.userId,StartCursor:t,WantNum:Dl()};return function(e){const{FollowItem:t=[],NextCursor:s,ActionStatus:o,ErrorCode:n,ErrorInfo:i,ErrorDisplay:r}=e;return{resultList:t.map((e=>({userID:e.To_Account,followTime:e.FollowTime,profileItem:e.ProfileItem,profileSequence:e.ProfileSequence}))),nextPageToken:s,actionStatus:o,errorCode:n,errorInfo:i,errorDisplay:r}}(yield o.buildAndSendPacket({servcmd:"follow.follow_get",data:i}))}))}function yl(e){return a(this,void 0,void 0,(function*(){return Cl(El.FOLLOWERS,e)}))}function Ml(e){return a(this,void 0,void 0,(function*(){return Cl(El.MUTUAL,e)}))}function Al(e){return a(this,void 0,void 0,(function*(){return Cl(El.FOLLOWING,e)}))}function Ol(e){return a(this,void 0,void 0,(function*(){var t;const{common:s,store:o}=fl.core,n={From_Account:null===(t=o.get("login"))||void 0===t?void 0:t.userId,FollowItem:e.map((e=>({To_Account:e})))};return function(e){const{ResultItem:t=[],ActionStatus:s,ErrorCode:o,ErrorInfo:n,ErrorDisplay:i}=e;return{resultList:t.map((e=>({userID:e.To_Account,resultCode:e.ResultCode,resultInfo:e.ResultInfo}))),actionStatus:s,errorCode:o,errorInfo:n,errorDisplay:i}}(yield s.buildAndSendPacket({servcmd:"follow.follow_add",data:n}))}))}function Tl(e){return a(this,void 0,void 0,(function*(){var t;const{common:s,store:o}=fl.core,n={From_Account:null===(t=o.get("login"))||void 0===t?void 0:t.userId,To_Account:e};return function(e){const{ResultItem:t=[],ActionStatus:s,ErrorCode:o,ErrorInfo:n,ErrorDisplay:i}=e;return{resultList:t.map((e=>({userID:e.To_Account,resultCode:e.ResultCode,resultInfo:e.ResultInfo}))),actionStatus:s,errorCode:o,errorInfo:n,errorDisplay:i}}(yield s.buildAndSendPacket({servcmd:"follow.follow_delete",data:n}))}))}function Dl(){const e=fl.core.store.get("cloudConfig")||{},t=null==e?void 0:e.follow_req_count;if(void 0!==t){const e=Number(t);return e>1e3?1e3:e}return 500}const Rl={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}]},Ll={getMyFollowersList:!0,getMyFollowingsList:!0,getMutualFollowersList:!0,followUser:!0,unfollowUser:!0,checkFollow:!0,getUserFollowInfo:!0};var Nl=new class{install(e){this._core=e;const{helper:t,notificationCenter:s,InnerEvent:o}=e;fl.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:Ll,params:Rl}),s.subscribeInnerEvent(o.MESSAGE_PUSH,s.InnerEventSubType.FOLLOW_LIST_UPDATED,this.onFollowListUpdated,this)}getMyFollowingList(){return a(this,arguments,void 0,(function*(e=""){return this._getFollowList({functionName:"getMyFollowingList",protocolFunction:Al,nextCursor:e})}))}getMyFollowersList(){return a(this,arguments,void 0,(function*(e=""){return this._getFollowList({functionName:"getMyFollowersList",protocolFunction:yl,nextCursor:e})}))}getMutualFollowersList(){return a(this,arguments,void 0,(function*(e=""){return this._getFollowList({functionName:"getMutualFollowersList",protocolFunction:Ml,nextCursor:e})}))}_getFollowList(e){return a(this,void 0,void 0,(function*(){const{functionName:t,protocolFunction:s,nextCursor:o=""}=e;console.log(`${vl} ${t} nextCursor:`,o);try{this._checkBusinessCapabilityBits(t);const e=yield s(o),{resultList:n=[],nextPageToken:i=""}=e,r=this._parseFollowItems(n);return console.log(`${vl}.${t} nextCursor: ${o} from remote.`),{code:0,data:{resultList:r,nextCursor:i}}}catch(e){console.error(`${vl}.${t} fail:`,e),this._handleError(t,e)}}))}followUser(e){return a(this,void 0,void 0,(function*(){return this._handleUserFollowRelation({functionName:"followUser",userIDList:e,protocolFunction:Ol})}))}unfollowUser(e){return a(this,void 0,void 0,(function*(){return this._handleUserFollowRelation({functionName:"unfollowUser",userIDList:e,protocolFunction:Tl})}))}_handleUserFollowRelation(e){return a(this,void 0,void 0,(function*(){const{functionName:t,userIDList:s,protocolFunction:o}=e;try{const e=this._sliceUserIDList(s,20);this._checkBusinessCapabilityBits(t);const{resultList:n=[]}=yield o(e);return{code:0,data:n}}catch(e){this._handleError(t,e)}}))}getUserFollowInfo(e){return a(this,void 0,void 0,(function*(){const t="getUserFollowInfo";console.log(`${vl} ${t} userIDList:`,e);try{this._checkBusinessCapabilityBits(t);const s=e||[this._core.common.getCurrentUserID()];console.log(`${vl} ${t} userIDList: ${s}`);const o=yield function(e){return a(this,void 0,void 0,(function*(){var t;const{common:s,store:o}=fl.core,n={From_Account:null===(t=o.get("login"))||void 0===t?void 0:t.userId,To_Account:e};return function(e){const{FollowInfo:t=[],ActionStatus:s,ErrorCode:o,ErrorInfo:n,ErrorDisplay:i}=e;return{followInfoList:t.map((e=>({userID:e.To_Account,resultCode:e.ResultCode,resultInfo:e.ResultInfo,followerCount:e.FollowerCount,followingCount:e.FollowingCount,mutualFollowingCount:e.MutualFollowingCount}))),actionStatus:s,errorCode:o,errorInfo:n,errorDisplay:i}}(yield s.buildAndSendPacket({servcmd:"follow.follow_get_info",data:n}))}))}(e),{followInfoList:n=[]}=o,i=[];return n.forEach((e=>{const{followerCount:t,followingCount:s,mutualFollowingCount:o}=e;i.push({followerCount:t,followingCount:s,mutualFollowingCount:o})})),{code:0,data:i}}catch(e){this._handleError(t,e)}}))}checkFollowType(e){return a(this,void 0,void 0,(function*(){const t="checkFollowType";console.log(`${vl} ${t} userIDList:`,e);try{this._checkBusinessCapabilityBits(t),e.length>100&&(e=e.slice(0,100),console.warn(`${vl} ${t} the length of userIDList cannot exceed 100`));const s=yield function(e){return a(this,void 0,void 0,(function*(){var t;const{common:s,store:o}=fl.core,n={From_Account:null===(t=o.get("login"))||void 0===t?void 0:t.userId,To_Account:e};return function(e){const{ResultItem:t=[],ActionStatus:s,ErrorCode:o,ErrorInfo:n,ErrorDisplay:i}=e;return{resultList:t.map((e=>({userID:e.To_Account,followType:e.FollowType,resultCode:e.ResultCode,resultInfo:e.ResultInfo}))),actionStatus:s,errorCode:o,errorInfo:n,errorDisplay:i}}(yield s.buildAndSendPacket({servcmd:"follow.follow_check",data:n}))}))}(e),{resultList:o=[]}=s;return{code:0,data:o.map((({userID:e,followType:t})=>({userID:e,followType:t})))}}catch(e){this._handleError(t,e)}}))}onFollowListUpdated(e){console.log(`${vl} onFollowListUpdated`,e);const{FollowChangeList:t=[]}=e;t.forEach((e=>this._processFollowChangeItem(e)))}_processFollowChangeItem(e){const{From_Account:t,FollowDiffList:s=[]}=e,o=r(e,["From_Account","FollowDiffList"]),n={userID:t,avatar:o.FaceUrl,nick:o.NickName};s.forEach((e=>{const t=this._updateFollowRelation(e,n);this._notifyFollowChanges(t)}))}_updateFollowRelation(e,t){const{IsAdd:s,FollowType:o=0}=e,n=this._initFollowInfo(),i=n[o];return i.isAdd=1===s,i.userInfoList.push(i.isAdd?t:t.userID),n}_notifyFollowChanges(e){const{OuterEvent:t}=this._core,s={[El.FOLLOWERS]:t.MY_FOLLOWERS_LIST_UPDATED,[El.FOLLOWING]:t.MY_FOLLOWING_LIST_UPDATED,[El.MUTUAL]:t.MUTUAL_FOLLOWERS_LIST_UPDATED};Object.entries(e).forEach((([e,t])=>{const o=Number(e);t.userInfoList.length>0&&s[o]&&this._emitFollowUpdated(s[o],t)}))}_initFollowInfo(){const e={};return Object.values(El).forEach((t=>{t!==El.NONE&&(e[t]={userInfoList:[],isAdd:!1})})),e}_emitFollowUpdated(e,t){console.log(`${vl} _emitFollowUpdated`);const{notificationCenter:s}=this._core;s.emitOuterEvent(e,{name:e,data:t})}_sliceUserIDList(e,t){return e.slice(0,t)}_checkBusinessCapabilityBits(e){const{helper:t,store:s}=this._core;if(!(s.get("commercialConfig")||new Map).get(Il))throw new t.ChatError({functionName:e,code:Sl,replacement1:e})}_handleError(e,t){const s=new this._core.helper.ChatError({functionName:e,code:null==t?void 0:t.errorCode,message:null==t?void 0:t.errorInfo});throw console.error(`${vl} ${e} fail:`,s),s}_parseFollowItems(e){return e.map((e=>{var t;const{userID:s,followTime:o,profileItem:n=[]}=e,i=[];n.forEach((e=>{i.push({tag:e.Tag,value:e.Value})}));const r=null===(t=this._core.user.userProfile)||void 0===t?void 0:t.createProfile(s,i);return{userID:s,followTime:o,nick:null==r?void 0:r.nick,avatar:null==r?void 0:r.avatar,allowType:null==r?void 0:r.allowType,adminForbidType:null==r?void 0:r.adminForbidType}}))}};const bl=new class{init(e){this.core=e}};const wl="message",Pl="user",Ul={OR:"or",AND:"and"},Gl=20,kl=20,Fl=20,$l={required:!1,rules:["array"],allowEmpty:!0,customValidator:e=>!e||(!!(Array.isArray(e)&&e.length<=5)||"keywordList should be an array and length <= 5")},ql={required:!1,rules:["string"],allowEmpty:!0,customValidator:e=>!e||(!![Ul.OR,Ul.AND].includes(e)||"keywordListMatchType should be OR or AND")},xl={required:!1,rules:["number"],allowEmpty:!0,customValidator:e=>"number"==typeof e&&e>=1&&e<=100||"count must be a number between 1 and 100"},Vl={required:!1,rules:["string"],allowEmpty:!0},Bl={required:!1,rules:["array"],allowEmpty:!0,customValidator:e=>{const{OuterConstant:t}=bl.core;if(!Array.isArray(e))return"groupTypeList should be an array";const s=[t.GRP_PUBLIC,t.GRP_COMMUNITY,t.GRP_WORK,t.GRP_MEETING];let o=!1;for(let t=0;t<e.length;t++)if(-1===s.indexOf(e[t])){o=!0;break}return!o||"groupTypeList should be supported group type"}},jl={required:!1,rules:["array"],allowEmpty:!0,customValidator:e=>{const{OuterConstant:t}=bl.core,s=[t.MSG_TEXT,t.MSG_IMAGE,t.MSG_AUDIO,t.MSG_FILE,t.MSG_VIDEO,t.MSG_LOCATION,t.MSG_CUSTOM,t.MSG_MERGER];let o=!1;for(let t=0;t<e.length;t++)if(-1===s.indexOf(e[t])){o=!0;break}return!o||"messageTypeList should be supported message type"}},Wl={required:!1,rules:["string"],allowEmpty:!0,customValidator:e=>{const{OuterConstant:t}=bl.core;return!(!(null==e?void 0:e.startsWith(t.CONV_C2C))&&!(null==e?void 0:e.startsWith(t.CONV_GROUP))&&e!==t.CONV_SYSTEM)||"conversationID is invalid"}},Kl=e=>({required:!1,rules:["number"],allowEmpty:!0,customValidator:t=>"number"==typeof t&&t>=0||`${e} should be a number >= 0';`}),Hl={required:!1,rules:["string"],allowEmpty:!0,customValidator:e=>{const{OuterConstant:t}=bl.core;return!![t.GENDER_FEMALE,t.GENDER_MALE].includes(e)||"gender is invalid"}},Yl={searchCloudMessages:{keywordList:$l,keywordListMatchType:ql,cursor:Vl,senderUserIDList:{required:!1,rules:["array"],allowEmpty:!0,customValidator:e=>!!(Array.isArray(e)&&e.length<=5)||"senderUserIDList should be an array and length <= 5"},messageTypeList:jl,conversationID:Wl,timePosition:Kl("timePosition"),timePeriod:Kl("timePeriod")},searchCloudUsers:{keywordList:$l,keywordListMatchType:ql,cursor:Vl,count:xl,miniBirthday:Kl("miniBirthday"),maxBirthday:Kl("maxBirthday"),gender:Hl},searchCloudGroupMembers:{keywordList:$l,keywordListMatchType:ql,cursor:Vl,count:xl,groupTypeList:Bl,groupIDList:{required:!1,rules:["array"],allowEmpty:!0}},searchCloudGroups:{keywordList:$l,keywordListMatchType:ql,cursor:Vl,count:xl,groupTypeList:Bl}},zl={searchCloudMessages:!0,searchCloudUsers:!0,searchCloudGroupMembers:!0,searchCloudGroups:!0};var Jl=new class{install(e){this._core=e,bl.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:zl,params:Yl})}searchCloudMessages(e){return a(this,void 0,void 0,(function*(){try{const{OuterConstant:t,helper:s,ssoLog:o}=this._core,n=o.createSSOLogData({method:"searchCloudMessages"}),{conversationID:i,timePeriod:c,timePosition:l}=e,u=r(e,["conversationID","timePeriod","timePosition"]),d=Object.assign({count:100},u);i&&(i.startsWith(t.CONV_C2C)?d.account=i.replace(t.CONV_C2C,""):i.startsWith(t.CONV_GROUP)&&(d.groupID=i.replace(t.CONV_GROUP,""))),this._setTimeRangeParams(d,{timePeriod:c,timePosition:l});const h=yield function(e){return a(this,void 0,void 0,(function*(){const{count:t,keywordList:s,keywordListMatchType:o,senderUserIDList:n,messageTypeList:i,endTime:r,startTime:a,cursor:c,account:l,groupID:u}=e,d={Count:t,KeywordList:s,MatchType:o,SendUserIDList:n,MsgTypeList:i,EndTime:r,StartTime:a,Cursor:c,PeerAccount:l,GroupID:u};return bl.core.common.buildAndSendPacket({servcmd:"message_search.query",data:d})}))}(d);if(!h)return{code:0,data:{}};const{ErrorCode:p,ErrorInfo:g,TotalCount:_,Cursor:m="",ConversationMsgs:f=[]}=h;if(0!==p)throw{errorCode:p,errorInfo:g};const v=`keywordList:${e.keywordList} keywordListMatchType:${e.keywordListMatchType} cursor:${e.cursor} res: totalCount:${_}`;n.setLogInfo({message:v}).end();const I=f.map((o=>{const{MsgList:n,Count:i,GroupID:r,UserID:a}=o,c=r?`${t.CONV_GROUP}${r}`:`${t.CONV_C2C}${a}`;if(this._isSearchingAllConversations(e)&&i>1)return{conversationID:c,messageCount:i,messageList:[]};const l=n.map((e=>s.isEmpty(r)?function(e,t){const s=t.OuterConstant.CONV_C2C,o=t.message.messageHelper.parseServerPushMessage(e),n=t.message.messageFactory.createMessage(Object.assign(Object.assign({},o),{conversationType:s,flow:"in"}));return n.setElement(o.elements),n}(e,this._core):function(e,t){const s=t.OuterConstant.CONV_GROUP,o=t.message.messageHelper.parseServerGroupMessage(e),n=t.message.messageFactory.createMessage(Object.assign(Object.assign({},o),{conversationType:s,flow:"in"}));return n.setElement(o.elements),n}(e,this._core)));return{conversationID:c,messageCount:i,messageList:l}}));return{code:0,data:{searchResultList:I,cursor:m,totalCount:_}}}catch(e){const{errorCode:t,errorInfo:s}=e||{};this._handleError({errorCode:t,errorInfo:s,searchType:wl,functionName:"searchCloudMessages"})}}))}searchCloudUsers(e){return a(this,void 0,void 0,(function*(){var t;try{const s=this._core.ssoLog.createSSOLogData({method:"searchCloudUsers"}),{keywordListMatchType:o,count:n=kl}=e,i=r(e,["keywordListMatchType","count"]),c=Object.assign({count:n,keywordListMatchType:o===Ul.AND?1:0},i);this._setBirthdayRangeParams(c,e);const l=yield function(e){return a(this,void 0,void 0,(function*(){const{count:t,keywordList:s,keywordListMatchType:o,miniBirthday:n,maxBirthday:i,cursor:r,gender:a}=e,c={Count:t,Keywords:s,KeywordMatchType:o,Cursor:r,UserBirthStart:n,UserBirthEnd:i,Gender:a};return bl.core.common.buildAndSendPacket({servcmd:"user_search.query",data:c})}))}(c);if(!l)return{error:0,data:{}};const{ErrorCode:u,ErrorInfo:d,TotalCount:h,Cursor:p="",Users:g=[]}=l;if(0!==u)throw{errorCode:u,errorInfo:d};const _=`keywordList:${e.keywordList} keywordListMatchType:${e.keywordListMatchType} cursor:${e.cursor} count:${e.count} res: totalCount:${h}`;s.setLogInfo({message:_}).end();const m=[];for(let e=0,s=g.length;e<s;e++){const{UserID:s,ProfileItems:o}=g[e];if(s===this._core.OuterConstant.USER_NOT_FOUND||""===s)continue;const n=o.map((e=>({tag:e.Tag,value:e.StrValue}))),i=null===(t=this._core.user.userProfile)||void 0===t?void 0:t.createProfile(s,n);m.push(i)}return{code:0,data:{searchResultList:m,cursor:p,totalCount:h}}}catch(e){const{errorCode:t,errorInfo:s}=e||{};this._handleError({errorCode:t,errorInfo:s,searchType:Pl,functionName:"searchCloudUsers"})}}))}searchCloudGroupMembers(e){return a(this,void 0,void 0,(function*(){try{const t=this._core.ssoLog.createSSOLogData({method:"searchCloudGroupMembers"}),{count:s=Fl,keywordListMatchType:o}=e,n=r(e,["count","keywordListMatchType"]),i=Object.assign({count:s,keywordListMatchType:o===Ul.AND?1:0},n),c=yield function(e){return a(this,void 0,void 0,(function*(){const{count:t,keywordList:s,keywordListMatchType:o,groupTypeList:n,cursor:i,groupIDList:r}=e,a={Count:t,Keywords:s,KeywordMatchType:o,Cursor:i,GroupType:n,GroupIdList:r};return bl.core.common.buildAndSendPacket({servcmd:"group_member_search.query",data:a})}))}(i);if(!c)return{code:0,data:{}};const{ErrorCode:l,ErrorInfo:u,GroupMembers:d,Cursor:h,TotalCount:p}=c;if(0!==l)throw{errorCode:l,errorInfo:u};const g=`keywordList:${e.keywordList} keywordListMatchType:${e.keywordListMatchType} cursor:${e.cursor} count:${e.count} res: totalCount:${p}`;t.setLogInfo({message:g}).end();const _=new Map;return d.forEach((e=>{const{GroupID:t,GroupName:s,GroupType:o,GroupFaceUrl:n,GroupMemberUserName:i,GroupMemberUserID:r,GroupMemberNameCard:a}=e,c={groupID:t,name:s,type:o,avatar:n},l={userID:r,nick:i,nameCard:a};if(_.has(t)){const e=_.get(t);e.memberList.push(l),_.set(t,e)}else _.set(t,{groupInfo:c,memberList:[l]})})),{code:0,data:{searchResultList:[..._.values()],cursor:h,totalCount:p}}}catch(e){const{errorCode:t,errorInfo:s}=e||{};this._handleError({errorCode:t,errorInfo:s,searchType:Pl,functionName:"searchCloudGroupMembers"})}}))}searchCloudGroups(e){return a(this,void 0,void 0,(function*(){try{const t=this._core.ssoLog.createSSOLogData({method:"searchCloudGroups"}),{count:s=Gl,keywordListMatchType:o}=e,n=r(e,["count","keywordListMatchType"]),i=Object.assign({count:s,keywordListMatchType:o===Ul.AND?1:0},n),c=yield function(e){return a(this,void 0,void 0,(function*(){const{count:t,keywordList:s,keywordListMatchType:o,groupTypeList:n,cursor:i}=e,r={Count:t,Keywords:s,KeywordMatchType:o,Cursor:i,GroupType:n};return bl.core.common.buildAndSendPacket({servcmd:"group_search.query",data:r})}))}(i);if(!c)return{code:0,data:{}};const{ErrorCode:l,ErrorInfo:u,Groups:d,Cursor:h,TotalCount:p}=c;if(0!==l)throw{errorCode:l,errorInfo:u};const g=`keywordList:${e.keywordList} keywordListMatchType:${e.keywordListMatchType} cursor:${e.cursor} count:${e.count} res: totalCount:${p}`;t.setLogInfo({message:g}).end();return{code:0,data:{searchResultList:(null==d?void 0:d.map((e=>function(e){const{GroupFaceUrl:t,GroupID:s,GroupIntroduction:o,GroupMemberNum:n,GroupName:i,GroupOwnerTinyID:r,GroupOwnerUserID:a,GroupOwnerUserName:c,GroupType:l}=e;return{avatar:t,groupID:s,introduction:o,memberCount:n,name:i,ownerTinyID:r,ownerID:a,ownerNick:c,type:l}}(e))))||[],cursor:h,totalCount:p}}}catch(e){const{errorCode:t,errorInfo:s}=e||{};this._handleError({errorCode:t,errorInfo:s,searchType:Pl,functionName:"searchCloudGroups"})}}))}_setTimeRangeParams(e,{timePeriod:t,timePosition:s}){t&&t>0&&(e.startTime=s&&s>0?s-t:this._core.helper.timeManager.getServerTimeSeconds()-t),e.startTime&&e.startTime<0&&(e.startTime=void 0),s&&s>0&&(e.endTime=s)}_handleError({errorCode:e,errorMessage:t,searchType:s,functionName:o}){const{ssoLog:n,helper:i}=this._core;let r=e;60020===e?r="SearchUnable":s!==wl&&27003===e?r="SearchParamsError":s!==wl&&60018===e&&(r="SearchOverLimit");const a=new i.ChatError({code:r,message:t});throw n.getSSOLogData(o).setError(a).end(),a}_isSearchingAllConversations(e){return this._core.helper.isEmpty(e.conversationID)}_setBirthdayRangeParams(e,t){const{miniBirthday:s,maxBirthday:o}=t;void 0!==s&&(e.miniBirthday=s,void 0===o&&(e.maxBirthday=4294967295)),void 0!==o&&(e.maxBirthday=o)}};let Zl=[];const Xl=[xs,function(e){Ps.install(e),$s.install(e),qs.install(e)},Ws,eo,oo,Rn,Ni,gr,Tc,Jl,bo,ml,Nl];Zl=Xl;var Ql=Object.freeze({__proto__:null,ChatError:cs,buildAndSendPacket:function(e){return a(this,void 0,void 0,(function*(){const{servcmd:t,data:s}=e,o=kt.common.generateProtocolData({servcmd:t,data:s}),n=`${o.head.seq}${t}`;return kt.channel.sendPacket(o,{requestId:n})}))},get builtInPlugins(){return Zl},checkBusinessCapabilityBits:Es,deepMerge:Os,destroy:pu,exposeApiForClient:gu,exposeApiForPlugin:_u,getCurrentUserID:Ms,getErrorMessage:as,getMessagePreviewText:Ds,isCommunity:({type:e,groupID:t})=>e===ts.GRP_COMMUNITY||`${t}`.startsWith(Qt.COMMUNITY)&&!`${t}`.includes(Qt.TOPIC),isTopic:Ts,isUnlimitedAVChatRoom:function(){var e;return!!(null===(e=kt.store.get("instance"))||void 0===e?void 0:e.unlimitedAVChatRoom)},liteChatInstanceMap:Cs,registerApi:du,registerExperimentalAPI:hu,registerInterceptor:vs,registerPlugin:cu,registerValidateConfig:Is,requireAuth:ls,setLogLevel:uu,statKeyFeatureUsage:lu,validateAndExecute:fs,validateParameters:hs,workflowManager:ys});var eu=new class{constructor(){this._conversationMap=new Map}getConversationMap(){return this._conversationMap}getConversation(e){return this._conversationMap.get(e)}updateConversation(e,t){const s=this._conversationMap.get(e);s&&!he(t)&&(Object.keys(t).forEach((e=>{s[e]=t[e]})),kt.notificationCenter.emitInnerEvent(Vt.CONVERSATION_UPDATED))}deleteConversation(e){this._conversationMap.has(e)&&(this._conversationMap.delete(e),kt.notificationCenter.emitInnerEvent(Vt.CONVERSATION_UPDATED))}};var tu=new class{constructor(){this._groupMap=new Map}getGroupMap(){return this._groupMap}getGroup(e){return this._groupMap.get(e)}updateGroup(e,t){const s=this._groupMap.get(e);s&&!he(t)&&Object.keys(t).forEach((e=>{s[e]=t[e]}))}};var su=new class{constructor(){this._messagesByConversation=new Map}updateMessage(e,t,s){var o;const{operation:n,updateUnreadCount:i=!0}=s,a=r(s,["operation","updateUnreadCount"]),c=[];for(const s of t){const t=null===(o=this._messagesByConversation.get(e))||void 0===o?void 0:o.get(s);if(!t)return!1;Object.keys(a).forEach((e=>{t[e]=a[e]})),c.push(t)}return this._emitMessageStoreOperationEvent(n,{conversationID:e,messageList:c,updateUnreadCount:i}),c}getMessagesByConversation(e){var t;return[...(null===(t=this._messagesByConversation.get(e))||void 0===t?void 0:t.values())||[]]}getMessages(){return this._messagesByConversation}_emitMessageStoreOperationEvent(e,t){kt.notificationCenter.emitInnerEvent(e,t)}};var ou=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)}},nu=Object.freeze({__proto__:null,conversationStore:eu,groupStore:tu,messageStore:su,userStore:ou});const iu={on:kt.notificationCenter.subscribeOuterEvent.bind(kt.notificationCenter),off:kt.notificationCenter.unSubscribeOuterEvent.bind(kt.notificationCenter),destroy:pu,callExperimentalAPI:function(e,t){if(ru[e])return ru[e](t);return Promise.reject(new Error(`API ${e} is not found`))},use:Ss.installExternalPlugin.bind(Ss),registerPlugin:cu,setLogLevel:uu},ru={},au={};function cu(e){console.log("registerPlugin",e)}function lu(e){console.log("statTUIKeyFeatures",e)}function uu(e){console.log("setLogLevel",e),kt&&"function"==typeof kt.setLogLevel&&(null==kt||kt.setLogLevel(e))}function du(e){const{apiName:t,context:s,methodName:o=t,matcher:n}=e;au[t]||(au[t]=[]),au[t].push({context:s,methodName:o,matcher:n}),iu[t]&&1!==au[t].length||(iu[t]=(...e)=>{fs(o,e);const s=au[t];for(const t of s)if(!t.matcher||t.matcher(e))return t.context[t.methodName].bind(t.context)(...e)})}function hu(e,t,s){const o=s||e;ru[e]=t[o].bind(t)}function pu(){return a(this,void 0,void 0,(function*(){var e,t;try{(null===(e=kt.store.get("login"))||void 0===e?void 0:e.isLogin)&&(yield iu.logout()),kt.notificationCenter.emitInnerEvent(Vt.DESTROY)}catch(e){console.debug("destroy error: ",e)}finally{kt.notificationCenter.emitOuterEvent(qt.SDK_DESTROY,{SDKAppID:null===(t=kt.store.get("instance"))||void 0===t?void 0:t.sdkAppId}),Cs.clear(),Ss.clear(),ys.destroy(),kt.destroy()}}))}function gu(){return iu}function _u(){return Object.assign(Object.assign({InnerEvent:Vt,InnerEventSubType:kt.notificationCenter.InnerEventSubType,OuterEvent:qt,OuterConstant:ts,SignalingEvent:Bt,helper:Object.assign(Object.assign(Object.assign({},kt.utils),kt.common),{registerApi:du,registerExperimentalAPI:hu,registerInterceptor:vs,registerValidateConfig:Is,checkBusinessCapabilityBits:Es,registerWorkflowStep:ys.registerWorkflowStep.bind(ys),ChatError:cs}),apiMap:iu},kt),{constants:Object.assign(Object.assign({},rs),kt.constants),common:Object.assign(Object.assign({},Ql),kt.common),utils:kt.utils,appStore:nu})}ru.statTUIKeyFeatures=lu;var mu,fu,vu;!function(e){e[e.USER_INITIATED=0]="USER_INITIATED",e[e.KICKED_OUT=1]="KICKED_OUT"}(mu||(mu={})),function(e){e[e.multipleAccount=1]="multipleAccount",e[e.multipleDevice=2]="multipleDevice",e[e.restApi=3]="restApi"}(fu||(fu={})),function(e){e[e.multipleDevice=3002]="multipleDevice",e[e.multipleAccount=3003]="multipleAccount",e[e.usersigExpired=70001]="usersigExpired",e[e.restApi=20002]="restApi"}(vu||(vu={}));const Iu={[fu.multipleAccount]:"multipleAccount",[fu.multipleDevice]:"multipleDevice",[fu.restApi]:"REST_API_Kick",[vu.multipleAccount]:"multipleAccount",[vu.multipleDevice]:"multipleDevice",[vu.restApi]:"REST_API_Kick",[vu.usersigExpired]:"userSigExpired"},Su="login_online_presence_task",{ERROR:Eu,DESTROY:Cu,FORCE_OFFLINE:yu}=Vt,{KICKED_OUT_MULT_ACCOUNT:Mu,KICKED_OUT_MULT_DEVICE:Au,KICKED_OUT_REST_API:Ou,ACCOUNT_A2KEY_EXPIRED:Tu,MSG_A2KEY_EXPIRED:Du}=ss;class Ru{init(){const{notificationCenter:e}=kt;e.subscribeInnerEvent(yu,this._handleForceOfflineFromServerPush,this),e.subscribeInnerEvent(Eu,Du,this._handleForceOfflineFromResponse,this),e.subscribeInnerEvent(Eu,Tu,this._handleForceOfflineFromResponse,this),e.subscribeInnerEvent(Eu,Mu,this._handleForceOfflineFromResponse,this),e.subscribeInnerEvent(Eu,Au,this._handleForceOfflineFromResponse,this),e.subscribeInnerEvent(Eu,Ou,this._handleForceOfflineFromResponse,this),e.subscribeInnerEvent(Cu,this._dispose,this)}_handleForceOfflineFromServerPush(e){const{EventArray:t=[]}=(null==e?void 0:e.body)||{};this._extractKickedOutMessages(t).forEach((e=>{const{KickoutMsgNotify:{KickType:t,NewInstInfo:s}}=e;this._processKickedOutReasonInfo({kickedOutReasonCode:t,newInstanceInfo:s})}))}_extractKickedOutMessages(e){return e.reduce(((e,t)=>[...e,...t.C2cNotifyMsgArray||[]]),[]).filter((e=>{var t;return this._isKickedOut(null===(t=null==e?void 0:e.KickoutMsgNotify)||void 0===t?void 0:t.KickType)}))}_handleForceOfflineFromResponse(e){const{errorCode:t}=e;this._processKickedOutReasonInfo({kickedOutReasonCode:t})}_processKickedOutReasonInfo(e){return a(this,void 0,void 0,(function*(){const{kickedOutReasonCode:t}=e;try{yield kt.login.loginAction.logout(mu.KICKED_OUT)}catch(e){console.debug(e)}finally{this._logKickedOutEvent(e),kt.notificationCenter.emitOuterEvent(qt.KICKED_OUT,{data:{type:Iu[t]},name:qt.KICKED_OUT}),[fu.restApi,Tu,Du].includes(t)&&kt.channel.reconnect()}}))}_logKickedOutEvent(e){const{kickedOutReasonCode:t,newInstanceInfo:s={}}=e,o=kt.ssoLog.createSSOLogData({method:"kickedOut"}),n=`type:${Iu[t]} newInstanceInfo: ${JSON.stringify(s)}`;o.setLogInfo({message:n}).end(!0),console.warn(`loginModule.${n}`)}_isKickedOut(e){return[fu.multipleAccount,fu.multipleDevice,fu.restApi].includes(e)}_dispose(){const{notificationCenter:e}=kt;e.unSubscribeInnerEvent(yu,this._handleForceOfflineFromServerPush,this),e.unSubscribeInnerEvent(Eu,Tu,this._handleForceOfflineFromResponse,this),e.unSubscribeInnerEvent(Eu,Du,this._handleForceOfflineFromResponse,this),e.unSubscribeInnerEvent(Eu,Mu,this._handleForceOfflineFromResponse,this),e.unSubscribeInnerEvent(Eu,Au,this._handleForceOfflineFromResponse,this),e.unSubscribeInnerEvent(Eu,Ou,this._handleForceOfflineFromResponse,this),e.unSubscribeInnerEvent(Cu,this._dispose,this)}}function Lu(){return a(this,void 0,void 0,(function*(){const e="im_open_status.wslogin",t=kt.common.generateProtocolData({servcmd:e,data:{state:"Online",isWebUniapp:0,InstType:0,customInfo:""}}),s=`${t.head.seq}${e}`;try{const e=yield kt.channel.sendPacket(t,{timeout:9e4,requestId:s});if(e){const{HelloInterval:t,InstId:s,TinyId:o,TimeStamp:n,CustomStatus:i,PurchaseBits:r,A2Key:a,RichMsgAuthKey:c,ErrorCode:l,ErrorInfo:u,ActionStatus:d}=e;return{helloInterval:t,instanceID:s,tinyID:o,timeStamp:n,customStatus:i,purchaseBits:r,a2Key:a,authKey:c,errorCode:l,errorInfo:u,actionStatus:d}}}catch(e){throw console.warn(e),e}}))}class Nu{constructor(){this._latestLoginAt=0,this._latestSendOnlinePresenceRequestTime=0,this._helloInterval=120}init(){const{notificationCenter:e,store:t}=kt;t.set("login",{isReady:!1}),du({apiName:"login",context:this}),du({apiName:"logout",context:this}),du({apiName:"getLoginUser",context:this}),du({apiName:"isReady",context:this}),e.subscribeInnerEvent(Vt.RECONNECTED,this._reLogin,this),kt.notificationCenter.subscribeInnerEvent(Vt.DESTROY,this._dispose,this)}login(e){return a(this,void 0,void 0,(function*(){const t=kt.ssoLog.createSSOLogData({method:"login",eventType:4});try{if(this._isLoginIn())return this._createRepeatLoginResponse();if(this._isLoginFrequencyExceeded())throw new cs({functionName:"login",code:ss.REPEAT_LOGIN});const t=yield this._performLogin(e);return this._validateAfterLogin(t),this._handleLoginSuccess(t),yield this._ensureAsyncComplete(),this._updateAndEmitSDKReady(),{code:0,data:t}}catch(e){const{errorCode:s}=e,o=new cs({functionName:"login",code:s});throw t.setError(o).end(!0),o}finally{this._latestLoginAt=0}}))}_reLogin(){return a(this,void 0,void 0,(function*(){var e;try{if(!this._isLoginIn())return;const t=kt.ssoLog.createSSOLogData({method:"reLogin"}),s=yield Lu();if(s){const{instanceID:o,customStatus:n}=s;kt.store.set("login",{statusInstanceId:o}),ys.executeWorkflow(os.SYNC_SERVER_INFO_AFTER_RE_ONLINE,{customStatus:n,statusType:zt.USER_STATUS_ONLINE});const i=`socketId:${null===(e=kt.channel.getSocketAdapter())||void 0===e?void 0:e.getId()} instanceId:${o}`;t.setLogInfo({message:i}).end(!0)}}catch(e){console.warn(e)}}))}logout(){return a(this,arguments,void 0,(function*(e=mu.USER_INITIATED){kt.ssoLog.createSSOLogData({method:"logout"}).setLogInfo({moreMessage:`identifier:${Ms()}`}).end(!0);try{yield this._performLogout(e)}catch(e){const{errorCode:t}=e,s=new cs({functionName:"logout",code:t});this._handleLogoutError(s)}finally{this._handleLogoutCompleted()}return{code:0,data:{}}}))}getLoginUser(){return this._isLoginIn()?Ms():""}isReady(){var e;return null===(e=kt.store.get("login"))||void 0===e?void 0:e.isReady}_updateAndEmitSDKReady(){kt.store.set("login",{isReady:!0}),setTimeout((()=>{kt.notificationCenter.emitOuterEvent(qt.SDK_READY,{name:qt.SDK_READY})}),1)}_updateAndEmitSDKNotReady(){kt.store.set("login",{isReady:!1}),kt.notificationCenter.emitOuterEvent(qt.SDK_NOT_READY,{name:qt.SDK_NOT_READY})}_validateAfterLogin(e){var t,s;const o="login";if(!e)throw new cs({functionName:o,message:"login response is empty"});const{tinyID:n,a2Key:i}=e||{},r=kt.ssoLog.getSSOLogData(o);if(!n){const e=new cs({functionName:o,code:ss.NO_TINYID});throw null===(t=null==r?void 0:r.setError)||void 0===t||t.call(r,e).end(),e}if(!i){const e=new cs({functionName:o,code:ss.NO_A2KEY});throw null===(s=null==r?void 0:r.setError)||void 0===s||s.call(r,e).end(),e}}_createRepeatLoginResponse(){var e;return{code:0,data:{actionStatus:"OK",errorCode:0,errorInfo:as({code:"RepeatLogin",replacement1:null===(e=kt.store.get("login"))||void 0===e?void 0:e.userId}),repeatLogin:!0}}}_performLogin(e){return a(this,void 0,void 0,(function*(){const{userID:t,userSig:s}=e;return kt.store.set("login",{userId:t,userSig:s}),this._latestLoginAt=Date.now(),Lu()}))}_ensureAsyncComplete(){return a(this,void 0,void 0,(function*(){yield new Promise((e=>{setTimeout((()=>e(null)),1)}))}))}_handleLoginSuccess(e){const{timeManager:t}=kt.common,{helloInterval:s,timeStamp:o,customStatus:n,purchaseBits:i}=e,r=1e3*o;t.calculateTimeOffsetWithServer(this._latestLoginAt,r),this._helloInterval=s||120,this._updateLoginStore(e),kt.user.userStatus.setCustomStatus(n),ys.executeWorkflow(os.SYNC_SERVER_INFO_AFTER_LOGIN,{purchaseBits:i}),kt.common.taskScheduler.addTask({id:Su,intervalMs:1e3*this._helloInterval,callback:this._sendOnlinePresenceRequest,context:this}),this._logLoginSuccess(e)}_performLogout(e){return function(e){return a(this,void 0,void 0,(function*(){const{logoutReason:t}=e,s="im_open_status.wslogout",o=kt.common.generateProtocolData({servcmd:s,data:{wslogout_type:t,isWebUniapp:0}}),n=`${o.head.seq}${s}`;return yield kt.channel.sendPacket(o,{requestId:n})}))}({logoutReason:e})}_handleLogoutError(e){kt.ssoLog.getSSOLogData("logout").setError(e).end(),console.error(`logout ${e}`)}_handleLogoutCompleted(){this._updateAndEmitSDKNotReady(),this._reset(),ys.reset(),kt.notificationCenter.emitInnerEvent("logout")}_updateLoginStore(e){const{a2Key:t,tinyID:s,instanceID:o,authKey:n}=e;kt.store.set("login",{a2Key:t,tinyID:s,statusInstanceId:o,authKey:n,isLoggedIn:!0})}_logLoginSuccess(e){var t;const s=kt.ssoLog.getSSOLogData("login"),{helloInterval:o,instanceID:n,timeStamp:i,customStatus:r}=e,a=null===(t=kt.channel.getSocketAdapter())||void 0===t?void 0:t.getId(),c=kt.common.timeManager.getTimeOffsetWithServer(),{appId:l,href:u}=kt.store.get("instance")||{},d=`login._logLoginSuccess socketID:${a} scene: helloInterval:${o} instanceID:${n}\n timeStamp:${i} offset:${c} customStatus:${r} href: ${u} appId: ${l}`;console.log(`login ok. ${d}`),s.updateLogCreatedAtByTimeOffset(),s.setLogInfo({moreMessage:d}).end()}_sendOnlinePresenceRequest(){return a(this,void 0,void 0,(function*(){this._latestSendOnlinePresenceRequestTime=Date.now();try{yield function(){const e="im_open_status.wshello",t=kt.common.generateProtocolData({servcmd:e,data:{isWebUniapp:0}}),s=`${t.head.seq}${e}`;return kt.channel.sendPacket(t,{requestId:s})}()}catch(e){console.warn("Login._sendOnlinePresenceRequest error:",e)}}))}_isLoginIn(){var e;return!0===(null===(e=kt.store.get("login"))||void 0===e?void 0:e.isLoggedIn)}_isLoginFrequencyExceeded(){return Date.now()-this._latestLoginAt<=15e3}_reset(){console.log("Login reset"),kt.common.taskScheduler.removeTask(Su),this._helloInterval=120,this._latestSendOnlinePresenceRequestTime=0,this._latestLoginAt=0,kt.store.clear("login"),kt.store.set("login",{isReady:!1})}_dispose(){console.log("Login dispose"),this._reset();const{notificationCenter:e}=kt;e.unSubscribeInnerEvent(Vt.RECONNECTED,this._reLogin,this),e.unSubscribeInnerEvent(Vt.DESTROY,this._dispose,this)}}const bu={login:{userID:{required:!0,rules:["string"],allowEmpty:!1},userSig:{required:!0,rules:["string"],allowEmpty:!1}}},wu={logout:!0};class Pu{constructor(){this.loginAction=new Nu,this.kickedOutHandler=new Ru,this.loginAction.init(),this.kickedOutHandler.init(),Is({auth:wu,params:bu})}}var Uu,Gu,ku;!function(e){e.CONV_C2C="C2C",e.CONV_GROUP="GROUP",e.CONV_TOPIC="TOPIC",e.CONV_SYSTEM="@TIM#SYSTEM"}(Uu||(Uu={})),function(e){e.MSG_PRIORITY_HIGH="High",e.MSG_PRIORITY_NORMAL="Normal",e.MSG_PRIORITY_LOW="Low",e.MSG_PRIORITY_LOWEST="Lowest"}(Gu||(Gu={})),function(e){e.MSG_TEXT="TIMTextElem",e.MSG_CUSTOM="TIMCustomElem",e.MSG_LOCATION="TIMLocationElem",e.MSG_FACE="TIMFaceElem",e.MSG_IMAGE="TIMImageElem",e.MSG_AUDIO="TIMSoundElem",e.MSG_FILE="TIMFileElem",e.MSG_VIDEO="TIMVideoFileElem",e.MSG_GRP_TIP="TIMGroupTipElem",e.MSG_GRP_SYS_NOTICE="TIMGroupSystemNoticeElem",e.MSG_MERGER="TIMRelayElem"}(ku||(ku={}));const Fu={1:Gu.MSG_PRIORITY_HIGH,2:Gu.MSG_PRIORITY_NORMAL,3:Gu.MSG_PRIORITY_LOW,4:Gu.MSG_PRIORITY_LOWEST},$u=0,qu=1;var xu;!function(e){e.IN="in",e.OUT="out"}(xu||(xu={}));const Vu={};function Bu(e){if(!e)return 0;if(void 0===Vu[e]){const t=new Date,s=`3${t.getHours()}`.slice(-2),o=`0${t.getMinutes()}`.slice(-2),n=`0${t.getSeconds()}`.slice(-2);Vu[e]=parseInt([s,o,n,"0001"].join(""),10),console.log(`autoIncrementIndex start index:${Vu[e]}`)}else Vu[e]+=1;return Vu[e]}class ju{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=Gu.MSG_PRIORITY_NORMAL,this._relayFlag=!1;const{clientTime:t=kt.common.timeManager.getServerTimeSeconds()||0,senderTinyID:s,currentUser:o,needReadReceipt:n,isSupportExtension:i,customModerationConfigurationId:r,to:a,from:c,nick:l="",avatar:u="",time:d,messageControlInfo:h,tinyID:p,cloudCustomData:g="",messageLifeTime:_,messageVersion:m=0,conversationType:f,sequence:v,checkResult:I=0,isPlaceMessage:S=0,messageFlagBits:E,receiverList:C,isSystemMessage:y=!1,status:M=Kt.SUCCESS,revokeReason:A="",conversationSubType:O,clientSequence:T,protocol:D="JSON",revokerInfo:R={userID:"",nick:"",avatar:""},readReceiptInfo:L={readCount:void 0,unreadCount:void 0,isPeerRead:void 0,timestamp:0},random:N,groupProfile:b,atUserList:w,flow:P,isRead:U=!1}=e;var G;this.clientTime=t,this.senderTinyID=s||p,this.needReadReceipt=!0===n||1===n,this.isSupportExtension=!0===i||1===i,this._cmConfigID=r,this.to=a,this.nick=l,this.avatar=u,this.protocol=D,this.random=void 0===N?(G=G||99999999,Math.round(Math.random()*G)):N,this.time=d||Math.ceil(Date.now()/1e3),this._isExcludedFromLastMessage=!!(null==h?void 0:h.excludedFromLastMessage),this._isExcludedFromUnreadCount=!!(null==h?void 0:h.excludedFromUnreadCount),this.isModified=!!m,this.cloudCustomData=g,this.messageLifeTime=_,this.from=c||null,this.sequence=v||0,this.conversationType=f||Uu.CONV_C2C,this.hasRiskContent=I>1,this.version=m,this.isPlaceMessage=S,this.isRevoked=2===S||8===E,this.isSystemMessage=y,this.readReceiptInfo=L,this.revokeReason=A,this.revokerInfo=R,this._receiverList=C,this.conversationSubType=O,this.revoker=(null==R?void 0:R.revoker)||"",this.clientSequence=T||v||0,this.status=M,this.atUserList=w||[],this.flow=P,this.isRead=U,this.reInitialize(o),this._initC2CReadReceiptInfo(e),this._extractGroupInfo(b)}getElements(){return this._elements}isOnlineMessage(){return 0===this.messageLifeTime}setElement(e){Array.isArray(e)?this._elements=e:this._elements=[e],this._updatePayloadAndType()}transformElementsToServerFormat(){return this._elements?Array.isArray(this._elements)?this._elements.map((e=>e.transformToServerFormat())):this._elements.transformToServerFormat():null}setRelayFlag(e){this._relayFlag=e}validateBeforeSend(){var e,t,s;return this._relayFlag?{isValid:!0}:(null===(e=this._elements)||void 0===e?void 0:e.length)>0?null===(s=null===(t=this._elements[0])||void 0===t?void 0:t.validateBeforeSend)||void 0===s?void 0:s.call(t):{isValid:!1}}_updatePayloadAndType(){this._elements[0]&&(this.payload=this._elements[0].content,this.type=this._elements[0].type)}_initC2CReadReceiptInfo(e){const{readReceiptSentByPeer:t,timestamp:s=0}=e;this.conversationType===Uu.CONV_C2C&&!0===this.needReadReceipt&&(this.readReceiptInfo.isPeerRead=1===t,this.readReceiptInfo.timestamp=s)}_extractGroupInfo(e){if(!e)return;const{From_AccountNick:t,From_AccountHeadurl:s,MsgFrom_AccountExtraInfo:o}=e,{NameCard:n}=o||{};"string"==typeof t&&(this.nick=t),"string"==typeof s&&(this.avatar=s),"string"==typeof n&&(this.nameCard=n)}reInitialize(e){e===this.from&&(this.isRead=!0),this._initSequence(e),this._concatConversationID(e),this.generateMessageID()}_concatConversationID(e){let t="";const s=this.conversationType;s!==Uu.CONV_SYSTEM?(t=s===Uu.CONV_C2C?e===this.from?this.to:this.from:this.to,this.conversationID=t?`${s}${t}`:null):this.conversationID=Uu.CONV_SYSTEM}_initSequence(e){0===this.clientSequence&&e&&(this.clientSequence=Bu(e)),0===this.sequence&&this.conversationType===Uu.CONV_C2C&&(this.sequence=this.clientSequence)}generateMessageID(){this.from===Uu.CONV_SYSTEM&&(this.senderTinyID="144115198244471703"),this.ID=`${this.senderTinyID}-${this.clientTime}-${this.random}`}setIsRead(e){this.isRead=e}}class Wu{static parseServerPushElement(e){const{MsgContent:t={}}=e,{Data:s,Ext:o,Desc:n}=t;return new Wu({data:s,description:n,extension:o})}constructor(e){this.type=ku.MSG_CUSTOM;const{data:t="",description:s="",extension:o=""}=e;this.content={data:t,description:s,extension:o}}transformToServerFormat(e){const{isMergerMessage:t=!1}=e||{},s=t?this.payload:this.content,{data:o,description:n,extension:i}=s;return{MsgType:this.type,MsgContent:{Data:o,Ext:i,Desc:n}}}validateBeforeSend(){const{isEmpty:e}=kt.utils,t=[this.content.data,this.content.description,this.content.extension].some((t=>!e(t)));return{isValid:t,error:t?null:{message:"content can not be empty"}}}}class Ku{static parseServerPushElement(e){const{MsgContent:t={Text:""}}=e,{Text:s}=t;return new Ku({text:s})}constructor(e){this.type=Wt.MSG_TEXT,this.content={text:e.text||""}}validateBeforeSend(){var e,t;return(null===(t=null===(e=this.content)||void 0===e?void 0:e.text)||void 0===t?void 0:t.length)>0?{isValid:!0}:{isValid:!1,error:{message:"content can not be empty"}}}transformToServerFormat(e){const{isMergerMessage:t=!1}=e||{},s=t?this.payload:this.content,{text:o}=s;return{MsgType:this.type,MsgContent:{Text:o}}}}class Hu{constructor(){this._elementClassMap={[ku.MSG_CUSTOM]:Wu,[ku.MSG_TEXT]:Ku}}init(){du({apiName:"createCustomMessage",context:this}),du({apiName:"createTextMessage",context:this})}registerElementClass(e,t){var s;void 0!==(s=t).prototype&&"constructor"in s.prototype&&(this._elementClassMap[e]=t)}getElementClass(e){return this._elementClassMap[e]}createMessage(e){const{from:t,flow:s=xu.OUT}=e,{userId:o}=kt.store.get("login")||{};this._isSendByCurrentInstance({from:t,flow:s,currentUser:o})?this._updateWithSenderInfo(e):this._isMultiEndpointSyncMessage({from:t,flow:s,currentUser:o})&&(e.flow=xu.OUT);const n=Object.assign(Object.assign({},e),{currentUser:o});return new ju(n)}createCustomMessage(e){const t=Ms(),s=this.createMessage(Object.assign(Object.assign({},e),{from:t})),o=this._elementClassMap[ku.MSG_CUSTOM];if(!s)return null;if(o){const t=new o(e.payload);s.setElement(t)}return s}createTextMessage(e){var t;if(!e)return null;const s="string"==typeof e.payload?e.payload:(null===(t=null==e?void 0:e.payload)||void 0===t?void 0:t.text)||"",o=new Ku({text:s}),n=Ms(),i=kt.message.messageFactory.createMessage(Object.assign(Object.assign({},e),{from:n}));return i.setElement(o),i}_updateWithSenderInfo(e){const{nick:t,avatar:s}=e,{userId:o,tinyID:n}=kt.store.get("login")||{},i=ou.getUserProfile(o);return e.nick=t||(null==i?void 0:i.nick)||"",e.avatar=s||(null==i?void 0:i.avatar)||"",e.tinyID=e.tinyID||n||"",e.from=o,e.status=Kt.UNSENT,e.flow=xu.OUT,e}_isMultiEndpointSyncMessage(e){const{from:t,flow:s,currentUser:o}=e;return t===o&&s===xu.IN}_isSendByCurrentInstance(e){const{from:t,flow:s,currentUser:o}=e;return t===o&&s===xu.OUT}}function Yu(e){const t=e.lastIndexOf(".");return-1===t?e:e.slice(0,t)}function zu(e){const{androidInfo:t={},androidOPPOChannelID:s=""}=e,o=t.OPPOChannelID||s;return Object.assign(Object.assign({},t),{Sound:Yu(t.sound||""),OPPOChannelID:o,GoogleChannelID:t.FCMChannelID||""})}function Ju(e){const{apnsInfo:t={},ignoreIOSBadge:s=!1,disableVoipPush:o}=e,n=!0===t.ignoreIOSBadge||!0===s?1:0;let i;return void 0!==o&&(i=!1===o?1:0),void 0!==t.disableVoipPush&&(i=!1===t.disableVoipPush?1:0),Object.assign(Object.assign({},t),{badgeMode:n,isVoipPush:i})}function Zu(e){return kt.utils.isPlainObject(e)?{PushFlag:!0===e.disablePush?1:0,Title:e.title||"",Desc:e.description||"",Ext:e.extension||"",ApnsInfo:Ju(e),AndroidInfo:zu(e)}:null}function Xu(e){const{From_AccountHeadurl:t,From_AccountNick:s,IsNeedReadReceipt:o,IsPeerRead:n,IsSyncMsg:i,MsgBody:r,MsgClientTime:a,MsgLifeTime:c,MsgRandom:l,MsgSeq:u,MsgTimeStamp:d,SendMsgControl:h,SupportMessageExtension:p,TinyId:g,MsgCheckResult:_,CloudCustomData:m,MsgVersion:f,MsgFlagBits:v,RevokerInfo:I}=e;let S,{From_Account:E,To_Account:C}=e;if(1===i){const e=C;C=E,E=e}if(I){const{Reason:e,Revoker_Account:t,Revoker_FromUin:s}=I;S={reason:e,revoker:t,revokerFromUin:s,userID:t}}return{from:E,avatar:t,nick:s,needReadReceipt:1===o,isSyncMessage:i,clientTime:a,messageLifeTime:c,random:l,sequence:u,time:d,messageControlInfo:{excludedFromLastMessage:1===(null==h?void 0:h.NoLastMsg),excludedFromUnreadCount:1===(null==h?void 0:h.NoUnread)},isSupportExtension:p,to:C,tinyID:g,checkResult:_,cloudCustomData:m,revokerInfo:S,messageVersion:f,messageFlagBits:v,readReceiptSentByPeer:n,elements:td(r)}}function Qu(e){const{From_Account:t,MsgBody:s,MsgClientTime:o,MsgRandom:n,MsgSeq:i,MsgTimeStamp:r,To_Account:a,MsgVersion:c,CloudCustomData:l}=e;return{from:t,clientTime:o,random:n,sequence:i,time:r,to:a,elements:td(s),messageVersion:c,cloudCustomData:l}}function ed(e){const{ClientSeq:t,From_Account:s,GroupInfo:o,MsgBody:n,MsgClientTime:i,MsgRandom:r,MsgSeq:a,MsgTimeStamp:c,SendMsgControl:l,SupportMessageExtension:u,TinyId:d,ToGroupId:h,CloudCustomData:p,MsgVersion:g,MsgCheckResult:_,NeedReadReceipt:m,IsPlaceMsg:f,RevokerInfo:v,GroupAtInfo:I}=e;let S,E=Gu.MSG_PRIORITY_NORMAL;if(Object.keys(Fu).includes(String(e.MsgPriority))&&(E=Fu[e.MsgPriority]),v){const{Reason:e,Revoker_Account:t,Revoker_FromUin:s}=v;S={reason:e,revoker:t,revokerFromUin:s,userID:t}}const C=function(e){const t=[];Array.isArray(e)&&e.forEach((e=>{e.GroupAtAllFlag===$u?t.push(e.GroupAt_Account):e.GroupAtAllFlag===qu&&t.push(ts.MSG_AT_ALL)}));return t}(I);return{clientSequence:t,from:s,groupProfile:o,clientTime:i,priority:E,random:r,sequence:a,time:c,messageControlInfo:{excludedFromLastMessage:1===(null==l?void 0:l.NoLastMsg),excludedFromUnreadCount:1===(null==l?void 0:l.NoUnread)},isSupportExtension:u,to:h,tinyID:d,cloudCustomData:p,messageVersion:g,messageCheckResult:_,needReadReceipt:m,isPlaceMessage:f,revokerInfo:S,atUserList:C,elements:td(n)}}function td(e){if(!e)return null;if(Array.isArray(e))return e.map((e=>{const t=kt.message.messageFactory.getElementClass(e.MsgType);return null==t?void 0:t.parseServerPushElement(e)}));const t=kt.message.messageFactory.getElementClass(e.MsgType);return null==t?void 0:t.parseServerPushElement(e)}function sd(e){const{From_Account:t,MsgBody:s,MsgClientTime:o,MsgRandom:n,MsgSeq:i,MsgTimeStamp:r,GroupId:a,TopicId:c,MsgVersion:l,CloudCustomData:u}=e;return{from:t,clientTime:o,random:n,sequence:i,time:r,groupID:a,topicID:c,elements:td(s),messageVersion:l,cloudCustomData:u}}function od({conversationUpdateFields:e,message:t}){const{conversationID:s,conversationType:o,conversationSubType:n,flow:i,_isExcludedFromUnreadCount:r,_isExcludedFromLastMessage:a}=t,c=a?"":t,l=!r&&i===xu.IN;e.has(s)?(e.get(s).lastMessage=c,l&&e.get(s).unreadCount++):e.set(s,{conversationID:s,type:o,subType:n,unreadCount:l?1:0,lastMessage:c})}var nd=Object.freeze({__proto__:null,autoIncrementIndex:Bu,parseServerGroupMessage:ed,parseServerPushC2CModifyMessage:Qu,parseServerPushGroupModifyMessage:sd,parseServerPushMessage:Xu,parseServerPushMessageElement:td,updateConversationFields:od});const{isPlainObject:id}=kt.utils;function rd(e,t={}){const{onlineUserOnly:s,messageControlInfo:o}=t;let{offlinePushInfo:n}=t;e.conversationType===Uu.CONV_C2C&&!0===s&&(n?n.disablePush=!0:n={disablePush:!0});let i="";"string"==typeof e.cloudCustomData&&e.cloudCustomData.length>0&&(i=e.cloudCustomData);const r=[];if(o&&id(o)){const{excludedFromUnreadCount:e,excludedFromLastMessage:t,excludedFromContentModeration:s}=o;!0===e&&r.push("NoUnread"),!0===t&&r.push("NoLastMsg"),!0===s&&r.push("NoMsgCheck")}return{onlineUserOnly:s,cloudCustomData:i,messageControlInfo:r,offlinePushInfo:n}}function ad(e){const{webhookInfo:{disableCloudMessagePreHook:t=!1,disableCloudMessagePostHook:s=!1}={}}=e||{};if(!t&&!s)return;const o=[];return t&&o.push("ForbidBeforeSendMsgCallback"),s&&o.push("ForbidAfterSendMsgCallback"),o}function cd(e,t){return a(this,void 0,void 0,(function*(){const s=e.conversationType===Uu.CONV_GROUP?function(e,t){var s;const o=rd(e,t),{onlineUserOnly:n,cloudCustomData:i,messageControlInfo:r,offlinePushInfo:a}=o,c=JSON.parse(JSON.stringify(e.transformElementsToServerFormat()));return{servcmd:"group_open_http_svc.send_group_msg",data:{From_Account:null===(s=kt.store.get("login"))||void 0===s?void 0:s.userId,GroupId:e.to,MsgBody:c,CloudCustomData:i,Random:e.random,MsgPriority:e.priority,ClientSeq:e.clientSequence,GroupAtInfo:e._groupAtInfoList,OnlineOnlyFlag:n?1:0,MsgClientTime:e.clientTime,OfflinePushInfo:Zu(a),SendMsgControl:n?void 0:r,NeedReadReceipt:!0===e.needReadReceipt?1:0,receiverList:null,SupportMessageExtension:!0===e.isSupportExtension?1:0,IsRelayMsg:!0===e._relayFlag?1:0,CustomModerationConfigID:e._cmConfigID,ForbidCallbackControl:ad(t)}}}(e,t):function(e,t){var s;const o=rd(e,t),{onlineUserOnly:n,cloudCustomData:i,messageControlInfo:r,offlinePushInfo:a}=o,c=!0===n?0:void 0,l=JSON.parse(JSON.stringify(e.transformElementsToServerFormat()));return{servcmd:"openim.sendmsg",data:{From_Account:null===(s=kt.store.get("login"))||void 0===s?void 0:s.userId,To_Account:e.to,MsgBody:l,CloudCustomData:i,MsgSeq:e.sequence,MsgRandom:e.random,MsgLifeTime:c,From_AccountNick:e.nick,From_AccountHeadurl:e.avatar,SendMsgControl:0!==c?r:void 0,MsgClientTime:e.clientTime,IsNeedReadReceipt:!0===e.needReadReceipt?1:0,SupportMessageExtension:!0===e.isSupportExtension?1:0,IsRelayMsg:!0===e._relayFlag?1:0,CustomModerationConfigID:e._cmConfigID,OfflinePushInfo:Zu(a),forbidCallbackControl:ad(t)}}}(e,t),o=kt.common.generateProtocolData(s),n=`${o.head.seq}${o.head.servcmd}`,i=yield kt.channel.sendPacket(o,{requestId:n});return i?{time:i.MsgTime,messageDropReason:i.MsgDropReason,sequence:i.MsgSeq}:null}))}const{isPlainObject:ld}=kt.utils,{MSG_AUDIO:ud,MSG_FILE:dd,MSG_IMAGE:hd,MSG_VIDEO:pd,MSG_MERGER:gd}=ts;class _d{init(){du({apiName:"sendMessage",context:this,matcher:e=>![ud,dd,hd,pd,gd].includes(e[0].type)})}sendMessage(e,t){return a(this,void 0,void 0,(function*(){const s=kt.ssoLog.createSSOLogData({method:"sendMessage"});if(!(e instanceof ju)){const e=new cs({code:ss.MSG_INSTANCE_REQUIRED});throw s.setError(e).end(),e}const o=e.validateBeforeSend();if(!o.isValid){const{code:e,message:t=""}=o.error||{},n=new cs({code:e,message:t});throw s.setError(n).end(),n}let n=!1;const{messageDataHandler:i}=kt.message||{};try{const{messageControlInfo:o}=t||{};let r=null;if(i.addRandomOfSentMessage(e.random),e.conversationType===Uu.CONV_C2C?(n=!0===(null==t?void 0:t.onlineUserOnly),r=yield cd(e,t)):e.conversationType===Uu.CONV_GROUP&&(r=yield cd(e,t)),r){const{messageDropReason:a,sequence:c,time:l}=r;if(this._updateNickAndAvatarOfSentMessageByMe(e),a&&this._logRateLimitInfo(e,c),!0===e.isResend){const t=i.findMessage(e.ID);t&&(console.log(`sendMessage resend ok. ID:${t.ID}`),i.deleteConversationMessage(t))}return e.status=Kt.SUCCESS,e.time=l,e.conversationType===Uu.CONV_GROUP&&(e.sequence=c),n?e._onlineOnlyFlag=!0:(i.storeConversationMessage(e),this._applySentMessageControlInfo(e,o),this._emitOnlineMessageSent(e)),s.setLogInfo({message:`options: ${JSON.stringify(t)}`}).end(),{code:0,data:{message:e}}}}catch(t){e.status=Kt.FAIL,i.removeRandomOfSentMessage(e.random);const{errorCode:s,errorInfo:o=""}=t||{};this._hasRiskContent(s)&&(e.hasRiskContent=!0),n||this._isRejectedByRestApi(s)||i.storeConversationMessage(e);const r=new cs({code:s,message:o,data:{message:e}});throw this._logSendMessageError({message:e,error:r}),r}}))}_hasRiskContent(e){return 80001===e||80004===e}_isRejectedByRestApi(e){return e>=10100&&e<=10200||e>=120001&&e<=13e4}_logSendMessageError({message:e,error:t}){const s=kt.ssoLog.createSSOLogData({method:"sendMessage"});let o=`head.seq: type:${e.type} from:${e.from} to:${e.to}`;if(kt.utils.IN_BROWSER){if("connection"in navigator){const e=navigator.connection;o+=` downlink:${e.downlink} effectiveType:${e.effectiveType} rtt:${e.rtt}`}if("memory"in window.performance){const e=window.performance.memory;o+=` usedJSHeapSize:${e.usedJSHeapSize} totalJSHeapSize:${e.totalJSHeapSize} jsHeapSizeLimit:${e.jsHeapSizeLimit}`}}s.setLogInfo({message:o}).setError(t).end()}_emitOnlineMessageSent(e){const t=e._isExcludedFromLastMessage?"":e,{conversationID:s,conversationType:o}=e;kt.notificationCenter.emitInnerEvent(Vt.NEW_MESSAGE,{result:{conversationUpdateFieldList:[{conversationID:s,type:o,message:e,lastMessage:t,unreadCount:0}]}})}_applySentMessageControlInfo(e,t){t&&ld(t)&&(!0===t.excludedFromLastMessage&&(e._isExcludedFromLastMessage=!0),!0===t.excludedFromUnreadCount&&(e._isExcludedFromUnreadCount=!0))}_logRateLimitInfo(e,t){const s=kt.ssoLog.createSSOLogData({method:"messageDropReason"}),o=`from:${e.from} to:${e.to} sequence:${t} messageDropReason:${messageDropReason}`;s.setLogInfo({message:o}).end(),console.warn(`sendMessage ${o}`)}_updateNickAndAvatarOfSentMessageByMe(e){const{messageDataHandler:t}=kt.message||{};let s=!1;const{conversationID:o}=e,n=t.getLatestMsgSentByMe(o);if(n){const{nick:i,avatar:r}=n;i===e.nick&&r===e.avatar||(s=!0),s&&t.updateNickAndAvatarOfSentMessage({conversationID:o,latestNick:e.nick,latestAvatar:e.avatar,isSentByMe:!0})}}}class md{constructor(e){this.value=e,this.next=null}}class fd{constructor(e){this.head=null,this.tail=null,this.size=0,this.capacity=e}append(e){this.size>=this.capacity&&this.removeHead();const t=new md(e);this.head?(this.tail.next=t,this.tail=t):(this.head=t,this.tail=t),this.size+=1}delete(e){if(!this.head)return;if(this.head.value===e)return void(this.head=this.head.next);let t=this.head;for(;t.next;){if(t.next.value===e)return void(t.next=t.next.next);t=t.next}}has(e){if(!this.head)return!1;let t=this.head,s=!1;for(;t;)t.value===e&&(s=!0),t=t.next;return s}removeHead(){this.head&&(this.head===this.tail?(this.head=null,this.tail=null):this.head=this.head.next,this.size-=1)}peek(){var e;return null===(e=this.head)||void 0===e?void 0:e.value}length(){return this.size}isEmpty(){return 0===this.size}isFull(){return this.size===this.capacity}clear(){this.head=null,this.tail=null,this.size=0}}class vd{constructor(){this._sparseMessagesByConversation=new Map,this._latestMessageSentByPeerMap=new Map,this._latestMessageSentByMeMap=new Map,this._randomOfSentMessageList=new fd(100),kt.notificationCenter.subscribeInnerEvent(Vt.LOGOUT,this._reset,this),kt.notificationCenter.subscribeInnerEvent(Vt.DESTROY,this._dispose,this)}get _messagesByConversation(){return su.getMessages()}storeConversationMessage(e,t=!1){const{conversationID:s}=e;if(!s)return!1;if(this._messagesByConversation.has(s)||this._messagesByConversation.set(s,new Map),this._shouldSkipStoreMessage(e,t))return!1;const o=this._getUniqueIdOfMessage(e);return this._messagesByConversation.get(s).set(o,e),this._updateLatestMessageMap(e),!0}_updateLatestMessageMap(e){const{conversationID:t}=e;"out"===e.flow?this._setLatestMsgSentByMe(t,e):t.startsWith("C2C")&&this._setLatestMsgSentByPeer(t,e)}_shouldSkipStoreMessage(e,t){const s=this._getUniqueIdOfMessage(e),o=this._messagesByConversation.get(e.conversationID);if(null==o?void 0:o.has(s)){const e=null==o?void 0:o.get(s);if(!t||!0===(null==e?void 0:e.isModified))return!0}return!1}deleteConversationMessage(e){var t;const{conversationID:s=""}=e,o=this._getUniqueIdOfMessage(e);this._messagesByConversation.has(s)&&(null===(t=this._messagesByConversation.get(s))||void 0===t||t.delete(o))}modifyConversationMessage(e,t){var s;if(!this._messagesByConversation.has(e)&&!this._sparseMessagesByConversation.has(e))return{isUpdated:!1,message:null};const o=this._getUniqueIdOfMessage(t),n=this._getMessageFromLocalMessage(e,o);if(n){const{messageVersion:o,elements:i,cloudCustomData:r,checkResult:a=0}=t,c=a>1;if(console.log(`conversationToMessageMap modifyConversationMessage localVersion:${n.version} remoteVersion:${o}`),n.version<o){const t=this._getUniqueIdOfMessage(n),a=pe(i);return(null===(s=this._messagesByConversation.get(e))||void 0===s?void 0:s.has(t))?su.updateMessage(e,[t],{isModified:!0,version:o,_elements:a,payload:a[0].content,type:a[0].type,cloudCustomData:r,hasRiskContent:c,operation:Ht.modify}):(n.version=o,n._elements=a,n.payload=n._elements[0].content,n.type=n._elements[0].type,n.cloudCustomData=r,n.isModified=!0,n.hasRiskContent=c),{isUpdated:!0,message:n}}return{isUpdated:!1,message:n}}return{isUpdated:!1,message:null}}_getMessageFromLocalMessage(e,t){var s;if(this._messagesByConversation.has(e))return null===(s=this._messagesByConversation.get(e))||void 0===s?void 0:s.get(t);if(this._sparseMessagesByConversation.has(e)){const s=[...this._sparseMessagesByConversation.get(e).values()];for(let e=0;e<s.length;e++)if(this._getUniqueIdOfMessage(s[e])===t)return s[e]}return null}findMessage(e){let t=null;const s=Array.from(this._messagesByConversation.values());for(const o of s){if(t=Array.from(o.values()).find((t=>t.ID===e))||null,t)break}if(!t){const s=Array.from(this._sparseMessagesByConversation.values());for(const o of s)if(t=o.get(e)||null,t)break}return t}deleteConversationMessageList(e){this._messagesByConversation.has(e)&&(this._messagesByConversation.delete(e),this._latestMessageSentByMeMap.delete(e),this._latestMessageSentByPeerMap.delete(e)),this._sparseMessagesByConversation.has(e)&&this._sparseMessagesByConversation.delete(e)}revokeMessage({conversationID:e,sequence:t,random:s,revoker:o}){const n=this._messagesByConversation.get(e);let i=null;if(n){const r=Array.from(n.values());if(i=this._findMessageBySequenceAndRandom({messageList:r,random:s,sequence:t}),i){const t=this._getUniqueIdOfMessage(i);return su.updateMessage(e,[t],{isRevoked:!0,revoker:o,operation:Ht.revoke}),i}}if(this._sparseMessagesByConversation.has(e)){const n=Array.from(this._sparseMessagesByConversation.get(e).values());if(i=this._findMessageBySequenceAndRandom({messageList:n,random:s,sequence:t}),i)return i.isRevoked=!0,i.revoker=o,i}}_findMessageBySequenceAndRandom({messageList:e,sequence:t,random:s}){for(let o=0;o<e.length;o+=1){const n=e[o];if(n.sequence===t&&(c(s)||n.random===s))return n}return null}prependLocalMessageList(e){const{messageList:t,conversationID:s}=e;if(0===t.length)return[];const o=[],n=[],i=this._messagesByConversation.get(s)||new Map;for(const e of t){const t=this._getUniqueIdOfMessage(e);i.has(t)||(o.push(e),n.push([t,e]))}if(n.length>0){const e=new Map([...n,...i.entries()]);this._messagesByConversation.set(s,e),this._updateLatestMessageSentByMe(s),this._updateLatestMessageSentByPeer(s)}return o}storeSparseMessageList(e){if(0===e.length)return;const{conversationID:t}=e[0],s=e.length;this._sparseMessagesByConversation.has(t)||this._sparseMessagesByConversation.set(t,new Map);const o=this._sparseMessagesByConversation.get(t);for(let t=0;t<s;t++){const s=e[t];o.has(s.ID)||o.set(s.ID,s)}}_updateLatestMessageSentByMe(e){var t;const s=Array.from((null===(t=this._messagesByConversation.get(e))||void 0===t?void 0:t.values())||[]);if(0!==s.length)for(let t=s.length-1;t>=0;t--)if("out"===s[t].flow){this._setLatestMsgSentByMe(e,s[t]);break}}_updateLatestMessageSentByPeer(e){var t;const s=Array.from((null===(t=this._messagesByConversation.get(e))||void 0===t?void 0:t.values())||[]);if(0!==s.length&&e.startsWith("C2C"))for(let t=s.length-1;t>=0;t--)if("in"===s[t].flow){this._setLatestMsgSentByPeer(e,s[t]);break}}_getUniqueIdOfMessage(e){const{from:t,to:s,random:o,sequence:n,time:i}=e;return`${t}-${s}-${o}-${n}-${i}`}_setLatestMsgSentByPeer(e,t){this._latestMessageSentByPeerMap.set(e,t)}_setLatestMsgSentByMe(e,t){this._latestMessageSentByMeMap.set(e,t)}getLatestMsgSentByPeer(e){return this._latestMessageSentByPeerMap.get(e)}getLatestMsgSentByMe(e){return this._latestMessageSentByMeMap.get(e)}addRandomOfSentMessage(e){this._randomOfSentMessageList.append(e)}removeRandomOfSentMessage(e){this._randomOfSentMessageList.delete(e)}updateNickAndAvatarOfSentMessage(e){const{conversationID:t="",latestAvatar:s,latestNick:o,isSentByMe:n=!0}=e,i=this._messagesByConversation.get(t);if(!i)return;const r=Array.from(i.values()),a=n?"out":"in";r.forEach((e=>{const{nick:t,avatar:n,flow:i}=e;i===a&&(t!==o&&(e.nick=o),n!==s&&(e.avatar=s))}))}isInMessageList(e){var t;const{conversationID:s}=e;if(!s)return!1;if(!this._messagesByConversation.has(s))return!1;const o=this._getUniqueIdOfMessage(e);return null===(t=this._messagesByConversation.get(s))||void 0===t?void 0:t.has(o)}isMessageSentByCurrentInstance(e){const{random:t}=e;return this._randomOfSentMessageList.has(t)}getContinuousMessagesByConversation(){return this._messagesByConversation}getLocalMessageList(e){const t=this._messagesByConversation.get(e);return t?[...t.values()]:[]}getSparseMessageList(e){const t=this._sparseMessagesByConversation.get(e);return t?[...t.values()]:[]}_reset(){this._messagesByConversation.clear(),this._latestMessageSentByPeerMap.clear(),this._latestMessageSentByMeMap.clear(),this._randomOfSentMessageList.clear()}_dispose(){this._reset(),kt.notificationCenter.unSubscribeInnerEvent(Vt.LOGOUT,this._reset,this),kt.notificationCenter.unSubscribeInnerEvent(Vt.DESTROY,this._dispose,this)}}function Id(e,t){const s=eu.getConversation(e);if(null==s?void 0:s.lastMessage){const{lastMessage:o}=s,{lastTime:n,lastSequence:i,version:r}=o,{time:a,sequence:c,messageVersion:l,elements:u,cloudCustomData:d}=t;n===a&&i===c&&r!==l&&(o.type=u[0].type,o.payload=u[0].content,o.messageForShow=Ds(o.type,o.payload),o.cloudCustomData=d,o.version=l,eu.updateConversation(e,{lastMessage:o}))}}class Sd{init(){du({apiName:"modifyMessage",context:this})}modifyMessage(e){return a(this,void 0,void 0,(function*(){const t=kt.ssoLog.createSSOLogData({method:"modifyMessage"}),{to:s,payload:o,sequence:n,conversationType:i,random:r,time:c,from:l,type:u}=e;if(!this._canModifyMessageElement(u))return void t.setLogInfo({message:`can not modify message element. message type: ${u}`}).end();const d=e.getElements();d.length>1&&(d[0].type=u,d[0].content=o);try{let o=null,u=null;if(t.setLogInfo({message:`to:${s}`}),i===Uu.CONV_C2C?o=yield function(e){return a(this,void 0,void 0,(function*(){const t="openim.modify_c2c_msg",{from:s,to:o,version:n=0,sequence:i,random:r,time:a,type:c,cloudCustomData:l}=e,u=kt.common.generateProtocolData({servcmd:t,data:{From_Account:s,To_Account:o,MsgVersion:n,MsgSeq:i,MsgRandom:r,MsgTime:a,MsgType:c,MsgBody:e.transformElementsToServerFormat(),CloudCustomData:l}}),d=`${u.head.seq}${t}`,h=yield kt.channel.sendPacket(u,{requestId:d});if(h){const{MsgBody:e,MsgVersion:t,CloudCustomData:s}=h;return{elements:td(e),messageVersion:t,cloudCustomData:s}}}))}(e):i===Uu.CONV_GROUP&&(o=yield function(e){return a(this,void 0,void 0,(function*(){const t="openim.modify_group_msg",{to:s,version:o=0,sequence:n,cloudCustomData:i}=e;let r,a=s;Ts(s)&&(a=s.split(Qt.TOPIC)[0],r=s);const c=kt.common.generateProtocolData({servcmd:t,data:{GroupId:a,TopicId:r,MsgVersion:o,MsgSeq:n,MsgBody:e.transformElementsToServerFormat(),CloudCustomData:i}}),l=`${c.head.seq}${t}`,u=yield kt.channel.sendPacket(c,{requestId:l});if(u){const{MsgBody:e,MsgVersion:t,CloudCustomData:s}=u;return{elements:td(e),messageVersion:t,cloudCustomData:s}}}))}(e)),o){t.end();let a=`${i}${s}`;return s===Ms()&&i===Uu.CONV_C2C&&(a=`${i}${l}`),u={conversationType:i,from:l,to:s,time:c,random:r,sequence:n,elements:null==o?void 0:o.elements,cloudCustomData:null==o?void 0:o.cloudCustomData,messageVersion:null==o?void 0:o.messageVersion,conversationID:a},this._handleModifyMessageSuccess(u),{code:0,data:{message:e}}}}catch(e){const{errorCode:t}=e||{},s=new cs({functionName:"modifyMessage",code:t});throw this._logModifyMessageError(s),s}}))}_logModifyMessageError(e){kt.ssoLog.getSSOLogData("modifyMessage").setError(e).end()}_handleModifyMessageSuccess(e){const{conversationID:t}=e,{isUpdated:s,message:o}=kt.message.messageDataHandler.modifyConversationMessage(t,e);!0===s&&kt.notificationCenter.emitOuterEvent(qt.MESSAGE_MODIFIED,{name:qt.MESSAGE_MODIFIED,data:[o]}),kt.notificationCenter.emitInnerEvent(Vt.MESSAGE_MODIFIED,{conversationID:t,message:o}),Id(t,e)}_canModifyMessageElement(e){return[ku.MSG_TEXT,ku.MSG_CUSTOM,ku.MSG_LOCATION,ku.MSG_FACE].includes(e)}}class Ed{init(){const{notificationCenter:e}=kt,{InnerEventSubType:t}=e;ys.registerWorkflowStep(os.RECEIVE_C2C_NEW_MESSAGE,ns.HANDLE_C2C_NEW_MESSAGE,this._handleC2CMessagePush,this),ys.registerWorkflowStep(os.RECEIVE_C2C_NEW_MESSAGE,ns.EMIT_C2C_MESSAGE_EVENT,this._emitMessageEventsAfterReceiveNewMessage,this),ys.registerWorkflowStep(os.SYNC_SERVER_INFO_AFTER_RE_ONLINE,ns.EMIT_C2C_MESSAGE_EVENT,this._emitMessageEventsAfterSyncUnreadMessage,this),e.subscribeInnerEvent(Vt.MESSAGE_PUSH,t.C2C_REALTIME_MESSAGE,this._executeReceiverNewMessageWorkFlow,this),e.subscribeInnerEvent(Vt.MESSAGE_PUSH,t.C2C_MESSAGE_MODIFIED,this._handleC2CMessageModify,this),e.subscribeInnerEvent(Vt.DESTROY,this._dispose,this)}_executeReceiverNewMessageWorkFlow(e){ys.executeWorkflow(os.RECEIVE_C2C_NEW_MESSAGE,e)}_handleC2CMessagePush(e){const t=e.data||{},{messageDataHandler:s}=kt.message||{},o=[],n=new Map;return t.C2cMsgArray.forEach((e=>{const t=this._generateC2CMessage(e);this._updateMessageProfile(t);let i=1===t.isModified;if(s.isMessageSentByCurrentInstance(t)?t.isModified=i:i=!1,t.isOnlineMessage())t._onlineOnlyFlag=!0,s.isMessageSentByCurrentInstance(t)||o.push(t);else if(!s.isInMessageList(t)){s.storeConversationMessage(t)&&od({conversationUpdateFields:n,message:t}),s.isMessageSentByCurrentInstance(t)&&!i||o.push(t)}})),{conversationUpdateFieldList:[...n.values()],messages:o}}_emitMessageEventsAfterReceiveNewMessage(e){var t;const{messages:s=[]}=(null===(t=e.result)||void 0===t?void 0:t[ns.HANDLE_C2C_NEW_MESSAGE])||{};this._emitMessageEvents(s)}_emitMessageEventsAfterSyncUnreadMessage(e){var t;const{messages:s=[]}=(null===(t=e.result)||void 0===t?void 0:t[ns.UNREAD_MESSAGE_SYNC])||{};this._emitMessageEvents(s)}_emitMessageEvents(e){const t=(null==e?void 0:e.filter((e=>!0===(null==e?void 0:e.isModified))))||[];t.length>0&&kt.notificationCenter.emitOuterEvent("onMessageModified",{name:"onMessageModified",data:t});const s=null==e?void 0:e.filter((e=>!(null==e?void 0:e.isModified)));s.length>0&&kt.notificationCenter.emitOuterEvent("onMessageReceived",{name:"onMessageReceived",data:s})}_generateC2CMessage(e){const t=Uu.CONV_C2C,s=Xu(e),o=kt.message.messageFactory.createMessage(Object.assign(Object.assign({},s),{conversationType:t,flow:xu.IN})),{elements:n}=s;return o.setElement(n),o}_updateMessageProfile(e){var t;const{messageDataHandler:s}=kt.message||{},o=null===(t=kt.store.get("login"))||void 0===t?void 0:t.userId,{from:n,nick:i,avatar:r,conversationID:a=""}=e;if(n!==o){const t=s.getLatestMsgSentByPeer(a);if(t){const{nick:o,avatar:n}=t;c(i)||c(r)?(e.nick=l(o)?o:e.nick,e.avatar=l(n)?n:e.avatar):i===o&&r===n||(s.updateNickAndAvatarOfSentMessage({conversationID:a,latestNick:i,latestAvatar:r,isSentByMe:!1}),this._updateConversationUserProfile({conversationID:a,nick:i,avatar:r}))}}else{const e=s.getLatestMsgSentByMe(a);!e||i===e.nick&&r===e.avatar||s.updateNickAndAvatarOfSentMessage({conversationID:a,latestNick:i,latestAvatar:r,isSentByMe:!0})}}_updateConversationUserProfile(e){const{conversationID:t,nick:s,avatar:o}=e,n=eu.getConversation(t),{userProfile:i={}}=n||{};i.avatar===o&&i.nick===s||eu.updateConversation(t,{userProfile:Object.assign(Object.assign({},i),{nick:s,avatar:o})})}_updateMessageListDueToModify(e){const{conversationID:t}=e,{isUpdated:s,message:o}=kt.message.messageDataHandler.modifyConversationMessage(t,e);!0===s&&kt.notificationCenter.emitOuterEvent("onMessageModified",{name:"onMessageModified",data:[o]}),kt.notificationCenter.emitInnerEvent("ModifyMessageSuccess",e),Id(t,e)}_handleC2CMessageModify(e){e.C2cMsgModNotifys.forEach((e=>{var t;const s=Uu.CONV_C2C;let o=Qu(e);const{to:n,from:i}=o;let r=`${s}${n}`;n===(null===(t=kt.store.get("login"))||void 0===t?void 0:t.userId)&&(r=`${s}${i}`),o=Object.assign({conversationType:s,conversationID:r},o),this._updateMessageListDueToModify(o)}))}_dispose(){const{notificationCenter:e}=kt,{InnerEventSubType:t}=e;kt.notificationCenter.unSubscribeInnerEvent(Vt.MESSAGE_PUSH,t.C2C_REALTIME_MESSAGE,this._handleC2CMessagePush,this),kt.notificationCenter.unSubscribeInnerEvent(Vt.MESSAGE_PUSH,t.C2C_MESSAGE_MODIFIED,this._handleC2CMessageModify,this),kt.notificationCenter.unSubscribeInnerEvent(Vt.DESTROY,this._dispose,this)}}class Cd{init(){const{notificationCenter:e}=kt,{InnerEventSubType:t}=e;ys.registerWorkflowStep(os.RECEIVE_GROUP_NEW_MESSAGE,ns.HANDLE_GROUP_NEW_MESSAGE,this._handleGroupMessagePush,this),ys.registerWorkflowStep(os.RECEIVE_GROUP_NEW_MESSAGE,ns.EMIT_GROUP_MESSAGE_EVENT,this._emitMessageEvents,this),e.subscribeInnerEvent(Vt.MESSAGE_PUSH,t.GROUP_REALTIME_MESSAGE,this._executeReceiverNewMessageWorkFlow,this),e.subscribeInnerEvent(Vt.MESSAGE_PUSH,t.GROUP_MESSAGE_MODIFIED,this._handleGroupMessageModify,this),e.subscribeInnerEvent(Vt.DESTROY,this._dispose,this)}_executeReceiverNewMessageWorkFlow(e){ys.executeWorkflow(os.RECEIVE_GROUP_NEW_MESSAGE,e)}_handleGroupMessagePush(e){const t=e.data||{},{messageDataHandler:s}=kt.message,o=[],n=new Map,i=null==t?void 0:t.GroupMsgArray;return null==i||i.forEach((e=>{const t=this._generateGroupMessage(e);this.updateMessageProfile(t);let i=1===t.isModified;if(s.isMessageSentByCurrentInstance(t)?t.isModified=i:i=!1,t.isOnlineMessage())t._onlineOnlyFlag=!0,s.isMessageSentByCurrentInstance(t)||o.push(t);else if(!s.isInMessageList(t)){s.storeConversationMessage(t)&&(o.push(t),od({conversationUpdateFields:n,message:t}))}})),{conversationUpdateFieldList:[...n.values()],messages:o}}_emitMessageEvents(e){var t;const{messages:s}=(null===(t=e.result)||void 0===t?void 0:t[ns.HANDLE_GROUP_NEW_MESSAGE])||{},o=(null==s?void 0:s.filter((e=>!0===(null==e?void 0:e.isModified))))||[];o.length>0&&kt.notificationCenter.emitOuterEvent("onMessageModified",{name:"onMessageModified",data:o});const n=(null==s?void 0:s.filter((e=>!(null==e?void 0:e.isModified))))||[];n.length>0&&kt.notificationCenter.emitOuterEvent("onMessageReceived",{name:"onMessageReceived",data:n})}_generateGroupMessage(e){const t=Uu.CONV_GROUP,s=ed(e),o=kt.message.messageFactory.createMessage(Object.assign(Object.assign({},s),{conversationType:t,flow:xu.IN})),{elements:n}=s;return o.setElement(n),o}updateMessageProfile(e){var t;const{messageDataHandler:s}=kt.message||{},o=null===(t=kt.store.get("login"))||void 0===t?void 0:t.userId,{from:n,nick:i,avatar:r,conversationID:a=""}=e;if(n===o){const e=s.getLatestMsgSentByMe(a);!e||i===e.nick&&r===e.avatar||s.updateNickAndAvatarOfSentMessage({conversationID:a,latestNick:i,latestAvatar:r,isSentByMe:!0})}}_updateMessageListDueToModify(e){const{conversationID:t}=e,{isUpdated:s,message:o}=kt.message.messageDataHandler.modifyConversationMessage(t,e);!0===s&&kt.notificationCenter.emitOuterEvent("onMessageModified",{name:"onMessageModified",data:[o]}),Id(t,e)}_handleGroupMessageModify(e){e.GroupMsgModNotifys.forEach((e=>{const t=Uu.CONV_GROUP;let s=sd(e);const{topicID:o,groupID:n}=s,i=o||n,r=`${t}${i}`;s=Object.assign({conversationType:t,conversationID:r,to:i},s),this._updateMessageListDueToModify(s)}))}_dispose(){const{notificationCenter:e}=kt,{InnerEventSubType:{GROUP_REALTIME_MESSAGE:t,GROUP_MESSAGE_MODIFIED:s}}=e;e.unSubscribeInnerEvent(Vt.MESSAGE_PUSH,t,this._handleGroupMessagePush,this),e.unSubscribeInnerEvent(Vt.MESSAGE_PUSH,s,this._handleGroupMessageModify,this),e.unSubscribeInnerEvent(Vt.DESTROY,this._dispose,this)}}class yd{constructor(){this.c2cMessageReceiver=new Ed,this.groupMessageReceiver=new Cd}init(){this.c2cMessageReceiver.init(),this.groupMessageReceiver.init()}}const Md={createCustomMessage:{to:{required:!0,rules:["string"],allowEmpty:!1},conversationType:{required:!0,rules:["string"],allowEmpty:!1},payload:{required:!0,rules:["object"],allowEmpty:!1},cloudCustomData:{required:!1,rules:["string"],allowEmpty:!1},priority:{required:!1,rules:["string"],allowEmpty:!1},customModerationConfigurationID:{required:!1,rules:["string"],allowEmpty:!1}},sendMessage:[{key:"message",required:!0,rules:["object"],allowEmpty:!1},{key:"options",required:!1,rules:["object"],allowEmpty:!1}],createTextMessage:{to:{required:!0,rules:["string"],allowEmpty:!1},conversationType:{required:!0,rules:["string"],allowEmpty:!1,customValidator:e=>!(!e.startsWith("C2C")&&!e.startsWith("GROUP"))||"conversationType is invalid."},payload:{required:!0,rules:["object"],allowEmpty:!1,customValidator:e=>function(e){var t;if("string"!=typeof(null==e?void 0:e.text)||"string"==typeof e.text&&0===(null===(t=null==e?void 0:e.text)||void 0===t?void 0:t.length))return"payload.text is invalid.";return!0}(e)}}};const Ad={createCustomMessage:!0,sendMessage:!0,modifyMessage:!0};class Od{constructor(){this.messageHelper=nd,this.messageFactory=new Hu,this.messageSender=new _d,this.messageAction=new Sd,this.messageReceiver=new yd,this.messageDataHandler=new vd,this.messageSender.init(),this.messageFactory.init(),this.messageAction.init(),this.messageReceiver.init(),Is({auth:Ad,params:Md})}}const Td="User",Dd="Tag_Profile_IM_",Rd=100,Ld={NICK:`${Dd}Nick`,GENDER:`${Dd}Gender`,BIRTHDAY:`${Dd}BirthDay`,LOCATION:`${Dd}Location`,SELFSIGNATURE:`${Dd}SelfSignature`,ALLOWTYPE:`${Dd}AllowType`,LANGUAGE:`${Dd}Language`,AVATAR:`${Dd}Image`,MESSAGESETTINGS:`${Dd}MsgSettings`,ADMINFORBIDTYPE:`${Dd}AdminForbidType`,LEVEL:`${Dd}Level`,ROLE:`${Dd}Role`},Nd="USER_STATUS",bd=1,wd={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:[]},Pd=new Map([[Ld.NICK,"nick"],[Ld.GENDER,"gender"],[Ld.BIRTHDAY,"birthday"],[Ld.LOCATION,"location"],[Ld.SELFSIGNATURE,"selfSignature"],[Ld.ALLOWTYPE,"allowType"],[Ld.LANGUAGE,"language"],[Ld.AVATAR,"avatar"],[Ld.MESSAGESETTINGS,"messageSettings"],[Ld.ADMINFORBIDTYPE,"adminForbidType"],[Ld.LEVEL,"level"],[Ld.ROLE,"role"]]);var Ud=new class{createProfile(e,t){const s={userID:e,profileCustomField:[]};return t.forEach((e=>{const{tag:t,value:o}=e;t&&t.indexOf("Tag_Profile_Custom")>-1?s.profileCustomField.push({key:t,value:o}):Pd.has(t)&&(s[Pd.get(t)]=o)})),Object.assign(Object.assign({},wd),s)}parseProfileItem(e=[]){const t=[];return e.forEach((e=>{t.push({tag:e.Tag,value:e.Value})})),t}parseProfileList(e=[]){const t=[];return e.forEach((e=>{t.push({tag:e.Tag,value:e.ValueBytes})})),t}convertParamsToProfile(e){const t=[];return Object.keys(e).forEach((s=>{t.push({tag:Ld[s.toUpperCase()],value:e[s]})})),t}normalizeProfileFields(e){const t={};return e.forEach((e=>{const{tag:s,value:o}=e;if(Pd.has(s)){const e=Pd.get(s);t[e]=o}})),t}};const{generateProtocolData:Gd}=kt.common;function kd(e){return a(this,void 0,void 0,(function*(){const t="profile.portrait_get_all",s={From_Account:Ms(),UserItem:[]};e.forEach((e=>{s.UserItem.push({CustomSequence:0,StandardSequence:0,To_Account:e})}));const o=Gd({servcmd:t,data:s}),n=`${o.head.seq}${t}`,i=yield kt.channel.sendPacket(o,{requestId:n});if(i)return function(e){const{ActionStatus:t,ErrorCode:s,ErrorDisplay:o,ErrorInfo:n,UserProfileItem:i}=e,r=[];return i.map((e=>{const{To_Account:t,CustomSequence:s,ResultCode:o,ResultInfo:n,StandardSequence:i,ProfileItem:a}=e,c=Ud.parseProfileItem(a);r.push({userId:t,customSequence:s,resultCode:o,resultInfo:n,standardSequence:i,profileItem:c})})),{actionStatus:t,errorCode:s,errorDisplay:o,errorInfo:n,userProfile:r}}(i)}))}function Fd(e){return ou.getFriendMap().has(e)}const{isEmpty:$d}=kt.utils;class qd{init(){du({apiName:"getMyProfile",context:this}),du({apiName:"getUserProfile",context:this}),du({apiName:"updateMyProfile",context:this}),this.createProfile=Ud.createProfile.bind(Ud);const{notificationCenter:e}=kt;ys.registerWorkflowStep(os.SYNC_SERVER_INFO_AFTER_LOGIN,ns.USER_PROFILE_SYNC,this.getMyProfileCacheThenServer,this),e.subscribeInnerEvent(Vt.MESSAGE_PUSH,e.InnerEventSubType.PROFILE_MODIFIED,this._onProfileDataModify,this),e.subscribeInnerEvent(Vt.LOGOUT,this._reset,this),e.subscribeInnerEvent(Vt.DESTROY,this._dispose,this)}getMyProfile(){return a(this,void 0,void 0,(function*(){const e=kt.ssoLog.createSSOLogData({method:"getMyProfile"});try{const t=Ms(),s=yield kd([t]);if(s){const e=this._handleProfileFormResponse(s)[0];return ou.getUserProfileMap().set(t,e),{code:0,data:e}}e.end()}catch(t){const{errorCode:s,errorInfo:o}=t,n=new cs({functionName:"getMyProfile",code:s,message:o});throw e.setError(n).end(),t}}))}getUserProfile(e){return a(this,void 0,void 0,(function*(){const t=kt.ssoLog.createSSOLogData({method:"getUserProfile"});try{let{userIDList:s}=e;s.length>Rd&&(s=s.slice(0,Rd));const{userIdListToRequest:o,userIdListToCache:n}=this._filterRequestAndCacheUsers(s),i=[];n.forEach((e=>{const t=ou.getUserProfile(e);i.push(t)}));const r=`userIDList.length:${s.length}`;if(0===o.length)return t.setLogInfo({message:r}).end(),{code:0,data:i};const a=yield kd(o);if(a){const e=this._handleProfileFormResponse(a);e.forEach((e=>{Fd(e.userID)&&ou.getUserProfileMap().set(e.userID,e)}));const s=e.concat(i);return t.setLogInfo({message:r}).end(),{code:0,data:s}}}catch(e){const{errorCode:s}=e,o=new cs({functionName:"getUserProfile",code:s});throw t.setError(o).end(),o}}))}getMyProfileCacheThenServer(){return a(this,void 0,void 0,(function*(){const e=Ms(),t=ou.getUserProfileMap().has(e);return t?{code:0,data:t}:this.getMyProfile()}))}updateMyProfile(e){return a(this,void 0,void 0,(function*(){const t=kt.ssoLog.createSSOLogData({method:"updateMyProfile"}),s=Ms(),o={};for(const t in e)void 0!==e[t]&&(o[t]=e[t]);const n=Ud.convertParamsToProfile(o);try{const e={From_Account:s,ProfileItem:n};t.setLogInfo({message:JSON.stringify(n)}),yield function(e){return a(this,void 0,void 0,(function*(){const t="profile.portrait_set",s=Gd({servcmd:t,data:e}),o=`${s.head.seq}${t}`,n=yield kt.channel.sendPacket(s,{requestId:o});if(n){const{ActionStatus:e,ErrorCode:t,ErrorDisplay:s,ErrorInfo:o}=n;return{actionStatus:e,errorCode:t,errorDisplay:s,errorInfo:o}}}))}(e);const i=ou.getUserProfile(s);let r;r=i?Object.assign(Object.assign({},i),o):Ud.createProfile(s,n);return!ds(i,r,["lastUpdatedTime","profileCustomField"])&&kt.notificationCenter.emitOuterEvent(qt.PROFILE_UPDATED,{name:qt.PROFILE_UPDATED,data:[r]}),r.lastUpdatedTime=Date.now(),ou.getUserProfileMap().set(s,r),t.end(),{code:0,data:r}}catch(e){const{errorCode:s,errorInfo:o}=e,n=new cs({functionName:"updateMyProfile",code:s,message:o});throw t.setError(n).end(),n}}))}updateMyNickAndAvatar(e){return a(this,void 0,void 0,(function*(){const t=Ms(),s=Date.now(),o=ou.getUserProfile(t);let n={};n=o?Object.assign(o,e):Ud.createProfile(t,e),n.lastUpdatedTime=s,ou.getUserProfileMap().set(t,n)}))}_onProfileDataModify(e){const t=function(e){const{Profile_Account:t,PushType:s,ProfileList:o}=e;return{userId:t,pushType:s,profileList:Ud.parseProfileList(o)}}(e.ProfileDataMod[0]);if($d(t))return;const{isProfileUpdated:s,profile:o}=this._handleProfileModified(t);s&&(kt.notificationCenter.emitInnerEvent(Vt.PROFILE_UPDATE,{name:Vt.PROFILE_UPDATE,data:[o]}),kt.notificationCenter.emitOuterEvent(qt.PROFILE_UPDATED,{name:qt.PROFILE_UPDATED,data:[o]}))}_dispose(){const{notificationCenter:e}=kt;e.unSubscribeInnerEvent(Vt.LOGOUT,this._reset,this),e.unSubscribeInnerEvent(Vt.MESSAGE_PUSH,e.InnerEventSubType.PROFILE_MODIFIED,this._onProfileDataModify,this),e.unSubscribeInnerEvent(Vt.DESTROY,this._dispose,this),this._reset()}_handleProfileModified(e){const{userId:t,profileList:s}=e,o=ou.getUserProfile(t);if(!o||!Fd(t))return{isProfileUpdated:!1,profile:null};const n=Ud.normalizeProfileFields(s),i=Object.keys(n).some((e=>o[e]!==n[e]));if(!i)return{isProfileUpdated:!1,profile:o};const r=Date.now(),a=Object.assign(Object.assign(Object.assign({},o),n),{lastUpdatedTime:r});return ou.getUserProfileMap().set(t,a),eu.updateConversation(`C2C${t}`,{userProfile:a}),{isProfileUpdated:i,profile:a}}_filterRequestAndCacheUsers(e){const t=[],s=[];return e.forEach((e=>{const o=ou.getUserProfileMap().has(e);Fd(e)&&o?s.push(e):t.push(e)})),{userIdListToRequest:t,userIdListToCache:s}}_handleProfileFormResponse(e){const{userProfile:t}=e;if(!Array.isArray(t))return[];const s=t.filter((e=>"@TLS#NOT_FOUND"!==e.userId&&""!==e.userId&&!$d(e.profileItem))),o=Date.now();return s.map((e=>{const t=Ud.createProfile(e.userId,e.profileItem);return t.lastUpdatedTime=o,t}))}_reset(){ou.getUserProfileMap().clear()}}const xd=new Map,Vd=["0","1","2","3","4","5","6","7","8","9","A","B","C","D","E","F"];for(let e=0,t=Vd.length;e<t;e++)xd.set(e,Vd[e]);function Bd(e){if(!e)return"";const t=String(e).replace(/[=]+$/,"");let s="";if(t.length%4==1)return"";for(let e,o,n=0,i=0;o=t.charAt(i++);~o&&(e=n%4?64*e+o:o,n++%4)?s+=String.fromCharCode(255&e>>(-2*n&6)):0)o="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=".indexOf(o);try{return decodeURIComponent(escape(s))}catch(e){return console.warn(e),""}}const{isEmpty:Wd}=kt.utils,{generateProtocolData:Kd}=kt.common;function Hd(e){return a(this,void 0,void 0,(function*(){const t="im_open_status.ws_get_user_status",s=Kd({servcmd:t,data:{To_Account:e}}),o=`${s.head.seq}${t}`,n=yield kt.channel.sendPacket(s,{requestId:o});if(n)return function(e){const{ErrorCode:t,ErrorInfo:s,ErrorList:o=[],UserStatusList:n=[]}=e,i=n.map((e=>{const{To_Account:t,Status:s,CustomStatus:o}=e;return{userID:t,statusType:s,customStatus:Bd(o)}})),r=o.map((e=>{const{To_Account:t,Invalid_Account:s,ErrorCode:o,ErrorInfo:n}=e;return{userID:Wd(s)?t:s,code:o,message:n}}));return{errorCode:t,errorInfo:s,successUserList:i,failureUserList:r}}(n)}))}class Yd{constructor(){this._customStatus=""}init(){const{notificationCenter:e}=kt;du({apiName:"getUserStatus",context:this}),du({apiName:"setSelfStatus",context:this}),du({apiName:"subscribeUserStatus",context:this}),du({apiName:"unsubscribeUserStatus",context:this}),ys.registerWorkflowStep(os.SYNC_SERVER_INFO_AFTER_RE_ONLINE,ns.USER_STATUS_UPDATE,this._onReOnline,this),e.subscribeInnerEvent(Vt.MESSAGE_PUSH,e.InnerEventSubType.USER_STATUS_UPDATE,this._onUserStatusUpdate,this),e.subscribeInnerEvent(Vt.LOGOUT,this._reset,this),e.subscribeInnerEvent(Vt.DESTROY,this._dispose,this)}setSelfStatus(e){return a(this,void 0,void 0,(function*(){const t=kt.ssoLog.createSSOLogData({method:"setSelfStatus"}),s=Ms(),{customStatus:o}=e;try{return yield function(e){return a(this,void 0,void 0,(function*(){const t="im_open_status.ws_set_custom_status",s=Kd({servcmd:t,data:{CustomStatus:e}}),o=`${s.head.seq}${t}`,n=yield kt.channel.sendPacket(s,{requestId:o});if(n){const{ErrorCode:e,ErrorInfo:t}=n;return{errorCode:e,errorInfo:t}}}))}(o),this._customStatus=o,t.setLogInfo({message:`customStatus: ${o}`}).end(),{code:0,data:{userID:s,statusType:bd,customStatus:o}}}catch(e){const{errorCode:s,errorInfo:o}=e,n=new cs({functionName:"setSelfStatus",code:s,message:o});throw t.setError(n).end(),n}}))}getUserStatus(e){return a(this,void 0,void 0,(function*(){const t=kt.ssoLog.createSSOLogData({method:"getUserStatus"}),{userIDList:s=[]}=e;return t.setLogInfo({moreMessage:`userIDList length: ${s.length}`}),this._isOnlyMeInArray(s)?this._getMyStatus():this._getUserStatus(s)}))}setCustomStatus(e){const t=Bd(e);this._customStatus=t}subscribeUserStatus(e){return a(this,void 0,void 0,(function*(){try{console.log(`${Td} subscribeUserStatus options: `,e);const{userIDList:t=[]}=e;this._checkBusinessCapabilityBits("subscribeUserStatus");const s=this._getMaxUserCount("subscribe"),o=this._sliceUserIDList(t,s),n=yield function(e){return a(this,void 0,void 0,(function*(){const{channel:t}=kt,s="im_open_status.ws_status_subscribe",o=Kd({servcmd:s,data:{To_Account:e}}),n=`${o.head.seq}${s}`;return yield t.sendPacket(o,{requestId:n})}))}(o);return{code:0,data:{failureUserList:this._parseResponse(n)}}}catch(e){throw console.error(`${Td} subscribeUserStatus error:`,e),e}}))}unsubscribeUserStatus(e){return a(this,void 0,void 0,(function*(){try{console.log(`${Td} unsubscribeUserStatus options: `,e),this._checkBusinessCapabilityBits("unsubscribeUserStatus");const{userIDList:t=[]}=e,s=this._getMaxUserCount("unsubscribe"),o=this._sliceUserIDList(t,s),n=yield function(e){return a(this,void 0,void 0,(function*(){const{channel:t}=kt,s="im_open_status.ws_status_unsubscribe";let o={};o=0===e.length?{UnsubscribeAll:1}:{To_Account:e};const n=Kd({servcmd:s,data:o}),i=`${n.head.seq}${s}`;return yield t.sendPacket(n,{requestId:i})}))}(o);return{code:0,data:{failureUserList:this._parseResponse(n)}}}catch(e){throw console.error(`${Td} unsubscribeUserStatus error:`,e),e}}))}_onUserStatusUpdate(e){const{UserStatusList:t=[]}=e||{},s=t.map((e=>{const{To_Account:t,Status:s,CustomStatus:o}=e;return{userID:t,statusType:s,customStatus:Bd(o)}}));this._emitUserStatusUpdatedEvent(s)}_onReOnline(e){const t=Bd(e.data.customStatus);if(this._customStatus===t)return;this._customStatus=t;const s={userID:Ms(),statusType:bd,customStatus:t};this._emitUserStatusUpdatedEvent(s)}_emitUserStatusUpdatedEvent(e){kt.notificationCenter.emitOuterEvent(qt.USER_STATUS_UPDATED,{name:qt.USER_STATUS_UPDATED,data:e})}_sliceUserIDList(e,t){return e.slice(0,t)}_parseResponse(e){const{ErrorList:t=[]}=e;return t.map((e=>{const{To_Account:t,Invalid_Account:s,ErrorCode:o,ErrorInfo:n}=e;return{userID:kt.utils.isEmpty(s)?t:s,code:o,message:n}}))}_checkBusinessCapabilityBits(e){if(!kt.store.get("commercialConfig").get(Nd))throw new cs({functionName:e,code:ss.NO_USE,replacement1:e})}_getMaxUserCount(e){const t=kt.store.get("cloudConfig")||{},s={query:{key:"status_query_count",default:500},subscribe:{key:"status_sub_count",default:Rd},unsubscribe:{key:"status_unsub_count",default:Rd}},{key:o,default:n}=s[e],i=t[o]||n;return parseInt(i,10)}_getMyStatus(){const e=kt.ssoLog.getSSOLogData("getUserStatus");e.setLogInfo({moreMessage:"getUserStatus._getMyStatus"});const t={userID:Ms(),statusType:bd,customStatus:this._customStatus};return e.end(),{code:0,data:{successUserList:[t],failureUserList:[]}}}_getUserStatus(e){return a(this,void 0,void 0,(function*(){const t=kt.ssoLog.getSSOLogData("getUserStatus");t.setLogInfo({moreMessage:"getUserStatus._getUserStatus"});try{this._checkBusinessCapabilityBits("getUserStatus");const s=this._getMaxUserCount("query"),o=this._sliceUserIDList(e,s),n=yield Hd(o),{successUserList:i,failureUserList:r}=n||{};return t.end(),{code:0,data:{successUserList:i,failureUserList:r}}}catch(e){const{errorCode:s}=e,o=new cs({functionName:"getUserStatus",code:s});throw t.setError(o).end(),o}}))}_isOnlyMeInArray(e){const t=Ms();return 1===e.length&&e.indexOf(t)>-1}_dispose(){const{notificationCenter:e}=kt;e.unSubscribeInnerEvent(Vt.MESSAGE_PUSH,e.InnerEventSubType.USER_STATUS_UPDATE,this._onUserStatusUpdate,this),e.unSubscribeInnerEvent(Vt.DESTROY,this._dispose,this),e.unSubscribeInnerEvent(Vt.LOGOUT,this._reset,this),this._reset()}_reset(){this._customStatus=""}}const zd={getUserProfile:{userIDList:{required:!0,rules:["array"],allowEmpty:!1}},updateMyProfile:{nick:{required:!1,rules:["string"],allowEmpty:!0},avatar:{required:!1,rules:["string"],allowEmpty:!0},gender:{required:!1,rules:["string"],allowEmpty:!0},selfSignature:{required:!1,rules:["string"],allowEmpty:!0},allowType:{required:!1,rules:["string"],allowEmpty:!0},birthday:{required:!1,rules:["number"],allowEmpty:!1},language:{required:!1,rules:["string"],allowEmpty:!0},messageSettings:{required:!1,rules:["string"],allowEmpty:!0},adminForbidType:{required:!1,rules:["string"],allowEmpty:!0},level:{required:!1,rules:["number"],allowEmpty:!1},role:{required:!1,rules:["number"],allowEmpty:!0},profileCustomField:{required:!1,rules:["array"],allowEmpty:!0}},setSelfStatus:{customStatus:{required:!0,rules:["string"],allowEmpty:!0}},getUserStatus:{userIDList:{required:!0,rules:["array"],allowEmpty:!1}},subscribeUserStatus:{userIDList:{required:!0,rules:["array"],allowEmpty:!1}},unsubscribeUserStatus:{userIDList:{required:!1,rules:["array"],allowEmpty:!0}}},Jd={getMyProfile:!0,getUserProfile:!0,updateMyProfile:!0,setSelfStatus:!0,getUserStatus:!0,subscribeUserStatus:!0,unsubscribeUserStatus:!0};class Zd{constructor(){this.userProfile=new qd,this.userStatus=new Yd,this.userProfile.init(),this.userStatus.init(),Is({auth:Jd,params:zd})}}return console.log(`TencentCloudLiteChat.VERSION:${Ve}`),{create:function(e){const{SDKAppID:t,testEnv:s=!1,devMode:o=!1,unlimitedAVChatRoom:n=!1}=e;let i=t;if(!function(e){if("number"==typeof e)return!0;const t=Number(e);return!Number.isNaN(t)}(i))return console.error("Create SDK instance failed. Failed to parse the SDKAppID, please check the arguments"),null;if(i=Number(i),Cs.has(i))return Cs.get(i);const r=function(){function e(){return(65536*(1+Math.random())|0).toString(16).substring(1)}return`${e()+e()}${e()}${e()}${e()}${e()}${e()}${e()}`}();kt.init({sdkAppId:i,instanceId:r,testEnv:s,devMode:o,unlimitedAVChatRoom:n}),ys.init(),kt.message=new Od,kt.user=new Zd,kt.login=new Pu,Ss.installBuiltInPlugin(Zl);const a=gu();return Cs.set(i,a),a},TSignaling:Bt,EVENT:qt,VERSION:Ve,TYPES:ts}}));