@tencentcloud/lite-chat 1.6.4 → 1.6.5
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/basic.d.ts +30 -2
- package/basic.es.js +1 -1
- package/basic.js +1 -1
- package/index.d.ts +30 -2
- package/package.json +1 -1
- package/plugins/avchatroom.es.js +1 -1
- package/plugins/avchatroom.js +1 -1
- package/plugins/cloud-search.es.js +1 -1
- package/plugins/cloud-search.js +1 -1
- package/plugins/conversation-group.es.js +1 -1
- package/plugins/conversation-group.js +1 -1
- package/plugins/conversation.es.js +1 -1
- package/plugins/conversation.js +1 -1
- package/plugins/follow.es.js +1 -1
- package/plugins/follow.js +1 -1
- package/plugins/friend.es.js +1 -1
- package/plugins/friend.js +1 -1
- package/plugins/group.es.js +1 -1
- package/plugins/group.js +1 -1
- package/plugins/message-enhancer.es.js +1 -1
- package/plugins/message-enhancer.js +1 -1
- package/plugins/offline-message-synchronizer.es.js +1 -1
- package/plugins/offline-message-synchronizer.js +1 -1
- package/plugins/rich-media-message.es.js +1 -1
- package/plugins/rich-media-message.js +1 -1
- package/plugins/signaling.es.js +1 -1
- package/plugins/signaling.js +1 -1
- package/plugins/topic.es.js +1 -1
- package/plugins/topic.js +1 -1
- package/professional.d.ts +30 -2
- package/professional.es.js +1 -1
- package/professional.js +1 -1
- package/standard.es.js +1 -1
- package/standard.js +1 -1
package/standard.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?module.exports=t():"function"==typeof define&&define.amd?define(t):(e="undefined"!=typeof globalThis?globalThis:e||self).TencentCloudChat=t()}(this,function(){let G=e=>void 0===e,w=e=>"string"==typeof e,U=e=>{return null==(e=Object.prototype.toString.call(e).match(/^\[object (.*)\]$/))?void 0:e[1].toLowerCase()},q=e=>"function"==typeof Array.isArray?Array.isArray(e):"array"===U(e),x=e=>null!==e&&"object"==typeof e,V=e=>q(e)||x(e),B=e=>{return"string"==typeof e&&(e=e[0],!/[^a-zA-Z0-9]/.test(e))},j=e=>{if("object"!=typeof e||null===e)return!1;e=Object.getPrototypeOf(e);if(null===e)return!0;let t=e;for(;null!==Object.getPrototypeOf(t);)t=Object.getPrototypeOf(t);return e===t};function K(e=99999999){return Math.round(Math.random()*e)}let H=(s,r,i,n)=>{if(!V(s)||!V(r))return 0;let o=0;var a,l=Object.keys(r);for(let e=0,t=l.length;e<t;e++)if(a=l[e],!(G(r[a])||i&&i.includes(a)))if(V(s[a])&&V(r[a]))o+=H(s[a],r[a],i,n);else{if(n&&n.includes(r[a]))continue;s[a]!==r[a]&&(s[a]=r[a],o+=1)}return o};function W(s){let r,i,n=s,o="";for(let e=0,t=(n=s.length%8!=0?"0".repeat(8-s.length%8)+s:n)["length"];e<t;e+=8)r=parseInt(n.slice(e,e+4),2),i=parseInt(n.slice(e+4,e+8),2),o+=base16Map.get(r)+base16Map.get(i);return o}let Y={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},$=["heartbeat.alive","im_open_status.wslogin","im_open_status.wslogout","group_open_long_polling_http_svc.get_msg","group_open_long_polling_http_noauth_svc.get_msg"];var i,z,J;(t=i=i||{})[t.DEBUG=0]="DEBUG",t[t.INFO=1]="INFO",t[t.WARN=2]="WARN",t[t.ERROR=3]="ERROR",t[t.NONE=4]="NONE";let Q="LiteChat",X={[i.DEBUG]:console.debug,[i.INFO]:console.info,[i.WARN]:console.warn,[i.ERROR]:console.error},Z={[i.INFO]:4,[i.WARN]:5,[i.ERROR]:6},ee=((t=z=z||{})[t.CONV_DELETED=1]="CONV_DELETED",t[t.CONV_PINED=2]="CONV_PINED",t[t.CONV_UNPINED=3]="CONV_UNPINED",t[t.CONV_MARK_UPDATED=4]="CONV_MARK_UPDATED",t[t.CONV_GROUP_ADDED=5]="CONV_GROUP_ADDED",t[t.CONV_GROUP_DELETED=6]="CONV_GROUP_DELETED",t[t.CONV_GROUP_UPDATED=7]="CONV_GROUP_UPDATED",Object.freeze({__proto__:null,CONSOLE_METHOD:X,CloudConfigReportLevelMap:Z,get ConvModifyPushType(){return z},DEFAULT_GLOBAL_MAX_TOTAL_COUNT:50,DEFAULT_GLOBAL_THROTTLE_TIME:5e3,DEFAULT_SINGLE_MAX_TOTAL_COUNT:2,DEFAULT_SINGLE_THROTTLE_TIME:1e3,ENUM_PLATFORM:Y,IS_TOPIC_MESSAGE:2,get LogLevel(){return i},NOT_NEED_CRC_SERVCMD:$,SDK_NAME:Q})),te="undefined"!=typeof wx&&"function"==typeof wx.getSystemInfoSync&&("mac"===wx.getSystemInfoSync().platform||"windows"===wx.getSystemInfoSync().platform),se="undefined"!=typeof wx&&"function"==typeof wx.getSystemInfoSync&&Boolean(wx.getSystemInfoSync().fontSizeSetting)||te,re=se&&"function"==typeof wx.createGamePortal,ie="undefined"!=typeof qq&&"function"==typeof qq.getSystemInfoSync&&Boolean(qq.getSystemInfoSync().fontSizeSetting),ne="undefined"!=typeof tt&&"function"==typeof tt.getSystemInfoSync&&Boolean(tt.getSystemInfoSync().fontSizeSetting),oe=ne&&"function"==typeof tt.onShow,ae="undefined"!=typeof swan&&"function"==typeof swan.getSystemInfoSync&&Boolean(swan.getSystemInfoSync().fontSizeSetting),le="undefined"!=typeof my&&"function"==typeof my.getSystemInfoSync&&Boolean(my.getSystemInfoSync().fontSizeSetting),ue="undefined"!=typeof jd&&"function"==typeof jd.getSystemInfoSync,ce="undefined"!=typeof uni&&"undefined"==typeof window&&"function"==typeof uni.requireNativePlugin,de=se&&"object"==typeof wx.miniapp,he="undefined"!=typeof uni,ge=se||ie||ne||ae||le||ce||ue,pe="undefined"==typeof window&&!ge&&"undefined"!=typeof global&&void 0!==global.NativeScriptGlobals,_e="undefined"!=typeof global&&(void 0!==global.nativeModuleProxy||void 0!==global.ReactNative),me="undefined"!=typeof wx&&"function"==typeof wx.getAccountInfoSync&&Boolean(wx.getAccountInfoSync().plugin),ve="undefined"!=typeof uni?!ge:"undefined"!=typeof window&&!ge&&!_e,fe=ie?qq:ne?tt:ae?swan:le?my:se?wx:ce?uni:ue?jd:{},s=ve&&window&&window.navigator&&window.navigator.userAgent||"",Ie=/(micromessenger|webbrowser)/i.test(s),Ee=function(){let e="WEB";return Ie?e="WEB":ie?e="QQ_MP":ne?e="TT_MP":ae?e="BAIDU_MP":le?e="ALI_MP":se?e=de?"DONUT_NATIVE_APP":"WX_MP":ce?e="UNI_NATIVE_APP":pe?e="NS_NATIVE_APP":_e&&(e="RN_NATIVE_APP"),Y[e]}(),Se=/iPad/i.test(s),Ce=/iPhone/i.test(s)&&!Se,Me=/iPod/i.test(s),ye=Ce||Se||Me,Oe=(t=s.match(/OS (\d+)_/i))&&t[1]?t[1]:null,Ae=/Android/i.test(s),Te=(t=s.match(/Android (\d+)(?:\.(\d+))?(?:\.(\d+))*/i))?(e=t[1]&&parseFloat(t[1]),J=t[2]&&parseFloat(t[2]),e&&J?parseFloat(t[1]+"."+t[2]):e||null):null,Re=/Firefox/i.test(s),De=/Edge/i.test(s),be=!De&&/Chrome/i.test(s),Ne=/MSIE/.test(s)||-1<s.indexOf("Trident")&&-1<s.indexOf("rv:11.0"),Le=function(){var e=/MSIE\s(\d+)\.\d/.exec(s);let t=e&&parseFloat(e[1]);return t=!t&&/Trident\/7.0/i.test(s)&&/rv:11.0/.test(s)?11:t}(),Pe=/Safari/i.test(s)&&!be&&!Ae&&!De,Ge=/Windows/i.test(s),we=/MAC OS X/i.test(s),Ue=ve&&"undefined"!=typeof Worker&&!Ne,ke=Ae||ye,Fe=ve&&void 0!==window.tencent_cloud_im_csig_flutter_for_web_25F_cy,qe="undefined"!=typeof window&&void 0!==window.navigator&&(J=window.navigator["standalone"],!(!ye||J||Pe));function xe(){let e="unknown";if(we&&(e="mac"),Ge&&(e="windows"),ye&&(e="ios"),Ae&&(e="android"),ge)try{var t=fe.getSystemInfoSync()["platform"];void 0!==t&&(e=t)}catch(e){console.error(e)}return e}function f(e,t){var s={};for(i in e)Object.prototype.hasOwnProperty.call(e,i)&&t.indexOf(i)<0&&(s[i]=e[i]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols)for(var r=0,i=Object.getOwnPropertySymbols(e);r<i.length;r++)t.indexOf(i[r])<0&&Object.prototype.propertyIsEnumerable.call(e,i[r])&&(s[i[r]]=e[i[r]]);return s}function I(e,o,a,l){return new(a=a||Promise)(function(s,t){function r(e){try{n(l.next(e))}catch(e){t(e)}}function i(e){try{n(l.throw(e))}catch(e){t(e)}}function n(e){var t;e.done?s(e.value):((t=e.value)instanceof a?t:new a(function(e){e(t)})).then(r,i)}n((l=l.apply(e,o||[])).next())})}let Ve="application/x-www-form-urlencoded;charset=UTF-8";function Be(e){return I(this,arguments,void 0,function*({method:i,url:n,data:o,timeout:a=3e3}){return new Promise(ge?(t,e)=>{fe.request({url:n,data:o,method:i,timeout:a,header:{"content-type":Ve},success:e=>t(e.data),fail:()=>e(new Error('{"message":"Network error","code":2800}'))})}:(t,e)=>{let s=new XMLHttpRequest,r=setTimeout(()=>{s.abort(),e(new Error('{"message":"Request timeout","code":2801}'))},a);s.onreadystatechange=function(){if(4===s.readyState)if(clearTimeout(r),200===s.status||304===s.status)try{t(s.responseText?JSON.parse(s.responseText):null)}catch(e){t(s.responseText)}else e(new Error('{"message":"Network error","code":2800}'))},s.open(i,n,!0),s.setRequestHeader("Content-type",Ve),s.send(o||null)})})}function je(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(j(e)){for(var t in e)if(Object.prototype.hasOwnProperty.call(e,t))return!1;return!0}return("[object Map]"===Object.prototype.toString.call(e)||"[object Set]"===Object.prototype.toString.call(e)||"[object File]"===Object.prototype.toString.call(e))&&0===e.size}function Ke(r){if(null===r||"object"!=typeof r)return r;if(r instanceof Date)return new Date(r.getTime());if(r instanceof RegExp)return new RegExp(r.source,r.flags);if(r instanceof Map){let s=new Map;return r.forEach((e,t)=>{s.set(Ke(t),Ke(e))}),s}if(r instanceof Set){let t=new Set;return r.forEach(e=>{t.add(Ke(e))}),t}if(Array.isArray(r))return r.map(e=>Ke(e));let e=Object.getPrototypeOf(r),s=Object.create(e);return[...Object.getOwnPropertyNames(r),...Object.getOwnPropertySymbols(r)].forEach(e=>{var t=Object.getOwnPropertyDescriptor(r,e);t&&(t.get||t.set?Object.defineProperty(s,e,t):s[e]=Ke(r[e]))}),s}function He(e,s,t){let r=new WeakSet;try{return JSON.stringify(e,(e,t)=>{if(void 0===(t=s?s(e,t):t))return"undefined";if(null===t)return null;if(Number.isNaN(t))return"NaN";if(t===1/0)return"Infinity";if(t===-1/0)return"-Infinity";if("function"==typeof t)return`[Function: ${t.name||"anonymous"}]`;if("symbol"==typeof t)return t.toString();if("bigint"==typeof t)return t.toString()+"n";if("object"==typeof t&&null!==t){if(r.has(t))return"[Circular]";r.add(t)}return t instanceof Date?t.toISOString():t instanceof Error?{name:t.name,message:t.message,stack:t.stack}:t instanceof Map?{dataType:"Map",value:Array.from(t.entries())}:t instanceof Set?{dataType:"Set",value:Array.from(t.values())}:t},t)}catch(e){return console.error("Failed to stringify:",e),""}}function We(){let s,r;return{promise:new Promise((e,t)=>{s=e,r=t}),resolve:s,reject:r}}var r,e,Ye,t=Object.freeze({__proto__:null,ANDROID_VERSION:Te,IE_VERSION:Le,IN_ALIPAY_MINI_APP:le,IN_BAIDU_MINI_APP:ae,IN_BROWSER:ve,IN_DONUT_NATIVE_APP:de,IN_JD_MINI_APP:ue,IN_MINI_APP:ge,IN_NS_NATIVE_APP:pe,IN_QQ_MINI_APP:ie,IN_RN_APP:_e,IN_TT_MINI_APP:ne,IN_TT_MINI_GAME:oe,IN_UNI_APP:he,IN_UNI_NATIVE_APP:ce,IN_WX_MINI_APP:se,IN_WX_MINI_APP_DESK:te,IN_WX_MINI_GAME:re,IN_WX_MINI_PLUGIN:me,IOS_VERSION:Oe,IS_ANDROID:Ae,IS_CHROME:be,IS_EDGE:De,IS_FIREFOX:Re,IS_IE:Ne,IS_IOS:ye,IS_IPAD:Se,IS_IPHONE:Ce,IS_IPOD:Me,IS_MAC:we,IS_SAFARI:Pe,IS_WECHAT:Ie,IS_WIN:Ge,IS_WORKER_AVAILABLE:Ue,MINI_APP_NAMESPACE:fe,USER_AGENT:s,base16EncodeBinaryString:W,deepCopyWithMethods:Ke,deepMerge:H,generatePromise:We,getPlatformType:xe,getType:U,httpRequest:Be,isArray:q,isArrayOrObject:V,isEmpty:je,isFlutterWeb:Fe,isH5:ke,isIOSWebView:qe,isNumber:e=>null!==e&&("number"==typeof e&&!Number.isNaN(+e)||"object"==typeof e&&e.constructor===Number),isObject:x,isPlainObject:j,isString:w,isUndefined:G,isUniIOSApp:function(){return ce&&"ios"===uni.getDeviceInfo().platform.toLocaleLowerCase()},isValidRequestKey:B,platform:Ee,randomInt:K,randomString:function(){let t="";for(let e=32;0<e;--e)t+="0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"[Math.floor(62*Math.random())];return t},safeStringify:He});class $e{constructor(){this.listeners={}}on(e,t,s){this.listeners[e]||(this.listeners[e]=[]),this.listeners[e].push({fn:t,context:s})}off(e,s,r){s&&(this.listeners[e]=null==(e=this.listeners[e])?void 0:e.filter(e=>{var t=e.fn===s,e=!r||e.context===r;return!(t&&e)}))}emit(s,...r){var e=this.listeners[s];e&&e.forEach(e=>{var{fn:e,context:t}=e;try{e.apply(t,r)}catch(e){console.warn(`Error in event handler for ${s} error: `+He(e))}})}once(t,s,r){let i=(...e)=>{s.apply(r,e),this.off(t,i)};this.on(t,i)}}(e=r=r||{}).BUSINESS_COMMAND="business_command",e.C2C_REALTIME_MESSAGE="c2c_realtime_message",e.C2C_MESSAGE_MODIFIED="c2c_message_modified",e.C2C_REVOKED_MESSAGE="c2c_message_revoked",e.GROUP_REALTIME_MESSAGE="group_realtime_message",e.GROUP_MESSAGE_MODIFIED="group_message_modified",e.GROUP_MESSAGE_REVOKED="group_message_revoked",e.C2C_MESSAGE_READ_RECEIPT="c2c_message_read_receipt",e.MESSAGE_REACTION_UPDATED="message_reaction_updated",e.MESSAGE_REACTION_UPDATED_SYNC="message_reaction_updated_sync",e.GROUP_AT_TIPS="group_at_tips",e.USER_STATUS_UPDATE="user_status_update",e.FRIEND_LIST_MODIFIED="friend_list_modified",e.PROFILE_MODIFIED="profile_modified",e.CONV_MODIFIED="conversation_modified",e.GROUP_TIPS_NOTIFICATION="group_tips_notification",e.GROUP_MESSAGE_READ_RECEIPT="group_message_read_receipt",e.GROUP_MESSAGE_READ_SYNC="group_message_read_sync",e.GROUP_SYSTEM_NOTIFICATION="group_system_notification",e.C2C_MESSAGE_PEER_READ="c2c_message_peer_read",e.C2C_MESSAGE_READ_SYNC="c2c_message_read_sync",e.C2C_REMIND_TYPE_SYNC="c2c_remind_type_sync",e.FOLLOW_LIST_UPDATED="follow_list_updated",e.MESSAGE_EXTENSIONS_UPDATED="message_extensions_updated",e.ALL_MESSAGE_READ="all_message_read",e.CONVERSATION_MARK_UPDATED="conversation_mark_updated",e.CONVERSATION_GROUP_ADD="conversation_group_add",e.CONVERSATION_GROUP_DELETED="conversation_group_deleted",e.CONVERSATION_GROUP_UPDATED="conversation_group_updated",e.ALL_RECEIVE_MESSAGE_OPTION="all_receive_message_option",e.TOPIC_AT_TIPS="topic_at_tips",e.TOPIC_TIPS_NOTIFICATION="topic_tips_notification",e.TOPIC_SYSTEM_NOTIFICATION="topic_system_notification",e.TOPIC_MESSAGE_READ_SYNC="topic_message_read_sync",e.TOPIC_LATEST_MESSAGE="topic_latest_message",e.GROUP_MESSAGE_PINNED="group_message_pinned";let ze=[16,17];function Je(e){let t,s=[];return null!=(t=null==e?void 0:e.GroupTips)&&t.forEach(e=>{2===e.GroupInfo.MillionGroupFlag?s.push(r.TOPIC_TIPS_NOTIFICATION):ze.includes(null==(e=null==e?void 0:e.MsgBody)?void 0:e.OpType)?s.push(r.GROUP_MESSAGE_PINNED):s.push(r.GROUP_TIPS_NOTIFICATION)}),s}let Qe=[{conditions:[{type:"event",value:100}],subType:r.BUSINESS_COMMAND},{conditions:[{type:"event",value:24}],subType:r.ALL_RECEIVE_MESSAGE_OPTION},{conditions:[{type:"event",value:26}],subType:r.TOPIC_LATEST_MESSAGE},{conditions:[{type:"hasKey",value:"C2cMsgArray"}],subType:r.C2C_REALTIME_MESSAGE},{conditions:[{type:"hasKey",value:"C2cMsgModNotifys"}],subType:r.C2C_MESSAGE_MODIFIED},{conditions:[{type:"hasKey",value:"ProfileDataMod"}],subType:r.PROFILE_MODIFIED},{conditions:[{type:"hasKey",value:"UserStatusList"}],subType:r.USER_STATUS_UPDATE},{conditions:[{type:"hasKey",value:"FriendListMod"}],subType:r.FRIEND_LIST_MODIFIED},{conditions:[{type:"hasKey",value:"GroupMsgArray"}],subType:r.GROUP_REALTIME_MESSAGE},{conditions:[{type:"hasKey",value:"GroupMsgModNotifys"}],subType:r.GROUP_MESSAGE_MODIFIED},{conditions:[{type:"hasKey",value:"C2cNotifyMsgArray"}],subTypeParser:function(e){let t,s=[];return null!=(t=null==e?void 0:e.C2cNotifyMsgArray)&&t.forEach(e=>{e.WithdrawC2cMsgNotify&&s.push(r.C2C_REVOKED_MESSAGE),e.C2cReadedReceipt&&s.push(r.C2C_MESSAGE_PEER_READ),e.ReadC2cMsgNotify&&s.push(r.C2C_MESSAGE_READ_SYNC),e.MuteNotificationsSync&&s.push(r.C2C_REMIND_TYPE_SYNC)}),s}},{conditions:[{type:"hasKey",value:"GroupTips"},{type:"event",value:4}],subTypeParser:Je},{conditions:[{type:"hasKey",value:"GroupTips"},{type:"event",value:5}],subTypeParser:function(e){let t,s=[];return null!=(t=null==e?void 0:e.GroupTips)&&t.forEach(e=>{Array.isArray(e.MsgBody.GroupWithdrawInfoArray)?s.push(r.GROUP_MESSAGE_REVOKED):Array.isArray(e.MsgBody.GroupMsgReceiptList)?s.push(r.GROUP_MESSAGE_READ_RECEIPT):Array.isArray(e.MsgBody.GroupReadInfoArray)?e.MsgBody.GroupReadInfoArray[0].TopicId?s.push(r.TOPIC_MESSAGE_READ_SYNC):s.push(r.GROUP_MESSAGE_READ_SYNC):2===e.GroupInfo.MillionGroupFlag?s.push(r.TOPIC_SYSTEM_NOTIFICATION):s.push(r.GROUP_SYSTEM_NOTIFICATION)}),s}},{conditions:[{type:"hasKey",value:"GroupTips"},{type:"event",value:6}],subTypeParser:Je},{conditions:[{type:"hasKey",value:"GroupTips"},{type:"event",value:12}],subTypeParser:function(e){let t,s=[];return null!=(t=null==e?void 0:e.GroupTips)&&t.forEach(e=>{var e=e["GroupAtTips"]["TopicId"];e?s.push(r.TOPIC_AT_TIPS):s.push(r.GROUP_AT_TIPS)}),s}},{conditions:[{type:"hasKey",value:"RecentContactMod"}],subTypeParser:function(e){let t,s=[];return null!=(t=null==e?void 0:e.RecentContactMod)&&t.forEach(e=>{switch(e.PushType){case z.CONV_MARK_UPDATED:s.push(r.CONVERSATION_MARK_UPDATED);break;case z.CONV_GROUP_ADDED:s.push(r.CONVERSATION_GROUP_ADD);break;case z.CONV_GROUP_DELETED:s.push(r.CONVERSATION_GROUP_DELETED);break;case z.CONV_GROUP_UPDATED:s.push(r.CONVERSATION_GROUP_UPDATED);break;default:s.push(r.CONV_MODIFIED)}}),s}},{conditions:[{type:"hasKey",value:"MsgReactionNotifyList"}],subType:r.MESSAGE_REACTION_UPDATED},{conditions:[{type:"hasKey",value:"MsgReactionNotify"}],subType:r.MESSAGE_REACTION_UPDATED_SYNC},{conditions:[{type:"hasKey",value:"C2cMsgInfo"}],subType:r.C2C_MESSAGE_READ_RECEIPT},{conditions:[{type:"hasKey",value:"FollowChangeList"}],subType:r.FOLLOW_LIST_UPDATED},{conditions:[{type:"hasKey",value:"MsgExtensionNotify"}],subType:r.MESSAGE_EXTENSIONS_UPDATED},{conditions:[{type:"hasKey",value:"C2CReadAllMsg"}],subType:r.ALL_MESSAGE_READ}];function Xe(r){let e,t=Array.isArray(null==(e=null==r?void 0:r.body)?void 0:e.EventArray)?r.body.EventArray:[],i=[];return t.forEach(t=>{t.Flag=r.body.Flag;var e=Qe.find(e=>e.conditions.every(e=>{switch(e.type){case"event":return t.Event===e.value;case"hasKey":return Object.prototype.hasOwnProperty.call(t,e.value);default:return!1}}));if(!e)return null;let s=[];"function"==typeof e.subTypeParser?s=e.subTypeParser(t):e.subType&&(s=e.subType),Array.isArray(s)?s.forEach(e=>{i.push({type:Ye.SERVER_PUSH_MESSAGE+":"+e,data:t})}):i.push({type:Ye.SERVER_PUSH_MESSAGE+":"+s,data:t})}),i}(n=Ye=Ye||{}).SERVER_PUSH_MESSAGE="im_open_push.msg_push",n.SERVER_PUSH_MESSAGE_MULTIPLE="im_open_push.multi_msg_push_ws",n.ERROR="error";let Ze={[Ye.SERVER_PUSH_MESSAGE]:Xe,[Ye.SERVER_PUSH_MESSAGE_MULTIPLE]:Xe,[Ye.ERROR]:function(e){var t=e["errorCode"];return[{type:"error:"+t,data:e}]}},et=new class{constructor(){this._outerEventEmitter=null,this._innerEventEmitter=null,this._outerEventEmitter=new $e,this._innerEventEmitter=new $e,this.InnerEventSubType=r}subscribeInnerEvent(s,r,i,n){var o,t;if(["string","number"].includes(typeof r)){let e=r,t=i;null!=(o=this._innerEventEmitter)&&o.on(s+":"+e,t,n)}else{let e=r;null!=(t=this._innerEventEmitter)&&t.on(s,e,i)}}emitInnerEvent(t,s){var e;if(null!=(e=this._innerEventEmitter)&&e.emit(t,s),Object.keys(Ze).includes(t)){let e=null==(t=Ze[t])?void 0:t.call(Ze,s);null!=e&&e.forEach(e=>{var t;e&&null!=(t=this._innerEventEmitter)&&t.emit(e.type,e.data)})}}unSubscribeInnerEvent(s,r,i,n){var o,t;if(["string","number"].includes(typeof r)){let e=r,t=i;null!=(o=this._innerEventEmitter)&&o.off(s+":"+e,t,n)}else{let e=r;null!=(t=this._innerEventEmitter)&&t.off(s,e,i)}}subscribeOuterEvent(e,t,s){var r;null!=(r=this._outerEventEmitter)&&r.on(e,t,s)}unSubscribeOuterEvent(e,t,s){var r;null!=(r=this._outerEventEmitter)&&r.off(e,t,s)}emitOuterEvent(e,t){var s;null!=(s=this._outerEventEmitter)&&s.emit(e,t)}getOuterEventEmitter(){return this._outerEventEmitter}rest(){this._outerEventEmitter=null,this._innerEventEmitter=null}};class st{constructor(){this._socket=null}connectSocket(e){return this._socket=new WebSocket(e),this._socket}send(e){var t;try{null!=(t=this._socket)&&t.send(e)}catch(e){null!=(t=this._onSendFail)&&t.call(this,e)}}bindSocketHandlers(e){var{onOpen:e,onMessage:t,onClose:s,onError:r,onSendFail:i}=e;this._socket&&(this._socket.binaryType="arraybuffer",this._socket.onopen=e,this._socket.onmessage=t,this._socket.onclose=s,this._socket.onerror=r,this._onSendFail=i)}unbindSocketHandlers(){this._socket&&(this._socket.onopen=null,this._socket.onmessage=null,this._socket.onclose=null,this._socket.onerror=null)}disconnect(){this._socket&&(this._socket.close(),this._socket=null)}}class rt{connectSocket(e){return this._socket=fe.connectSocket({url:e,header:{"content-type":"application/json"},complete:()=>{}}),this._socket}send(e){var t;null!=(t=this._socket)&&t.send({data:e,fail:this._onSendFail})}bindSocketHandlers(e){var{onOpen:e,onMessage:t,onClose:s,onError:r,onSendFail:i}=e;this._socket.onClose(s),this._socket.onOpen(e),this._socket.onMessage(t),this._socket.onError(r),this._onSendFail=i}unbindSocketHandlers(){this._socket&&(this._socket.onClose(()=>{}),this._socket.onOpen(()=>{}),this._socket.onMessage(()=>{}),this._socket.onError(()=>{}))}disconnect(){this._socket&&(this._socket.close(),this._socket=null)}}class it{constructor(){this._worker=null,this._blobUrl=null}connectSocket(e){var t=new Blob(["\n let _socket = null;\n\n self.onmessage = (event) => {\n const { type, url, data } = event.data;\n\n switch (type) {\n case 'CONNECT':\n connectSocket(url);\n break;\n case 'SEND':\n send(data);\n break;\n case 'DISCONNECT':\n disconnect();\n break;\n }\n };\n\n function connectSocket(url) {\n _socket = new WebSocket(url);\n _socket.binaryType = 'arraybuffer';\n bindSocketHandlers();\n return _socket;\n }\n\n function send(packet) {\n try {\n _socket?.send(packet);\n } catch (error) {\n self.postMessage({\n type: 'SEND_FAIL', \n error: {\n message: error.message,\n name: error.name,\n },\n });\n }\n }\n\n function bindSocketHandlers() {\n if (_socket) {\n _socket.onopen = (event) => {\n self.postMessage({\n type: 'OPEN',\n data: {\n type: event.type,\n timeStamp: event.timeStamp,\n },\n });\n };\n\n _socket.onmessage = (event) => {\n self.postMessage({ \n type: 'MESSAGE',\n data: event.data,\n });\n };\n\n _socket.onclose = (event) => {\n self.postMessage({ \n type: 'CLOSE', \n data: { \n code: event.code,\n reason: event.reason,\n timeStamp: event.timeStamp,\n },\n });\n };\n\n _socket.onerror = (error) => {\n self.postMessage({\n type: 'ERROR',\n data: {\n message: error.message,\n name: error.name\n },\n });\n };\n }\n }\n\n function unbindSocketHandlers() {\n if (_socket) {\n _socket.onopen = null;\n _socket.onmessage = null;\n _socket.onclose = null;\n _socket.onerror = null;\n }\n }\n\n function disconnect() {\n if (_socket) {\n _socket.close();\n _socket = null;\n }\n }\n"],{type:"application/javascript"});this._worker=new Worker(URL.createObjectURL(t)),this._worker.postMessage({type:"CONNECT",url:e})}send(e){var t;try{null!=(t=this._worker)&&t.postMessage({type:"SEND",data:e})}catch(e){null!=(t=this._onSendFail)&&t.call(this,e)}}bindSocketHandlers(e){var{onOpen:t,onMessage:r,onClose:i,onError:n,onSendFail:o}=e;if(this._worker){let s={OPEN:t,MESSAGE:r,CLOSE:i,ERROR:n,SEND_FAIL:o};this._onSendFail=o,this._worker.onmessage=e=>{var t=((null==e?void 0:e.data)||{})["type"];"function"==typeof s[t]&&null!=(t=s[t])&&t.call(s,null==e?void 0:e.data)}}}unbindSocketHandlers(){this._worker&&(this._worker.onmessage=null)}disconnect(){this._worker&&(this._worker.postMessage({type:"DISCONNECT"}),this._worker.terminate(),this._worker=null),this._blobUrl&&(URL.revokeObjectURL(this._blobUrl),this._blobUrl=null)}}var nt,c=new class{constructor(){this._store=new Map}get(e){return this._store.get(e)}getStorage(e){return ge?le?my.getStorageSync({key:e}).data:fe.getStorageSync(e):this._canUseLocalStorage()?localStorage.getItem(e):{}}set(e,t){var s=this._store.get(e)||{};t instanceof Map?this._store.set(e,t):this._store.set(e,Object.assign(Object.assign({},s),t))}setStorage(e,t){ge?le?my.setStorageSync({key:e,data:JSON.stringify(t)}):fe.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}};(n=nt=nt||{})[n.CONNECTED=0]="CONNECTED",n[n.CONNECTING=1]="CONNECTING",n[n.DISCONNECTED=2]="DISCONNECTED";class ot{constructor(e){this._url="",this._readyState=nt.DISCONNECTED,this._url=e,this._id=K(),this._emitter=new $e,se||ce||oe?this._socket=new rt:this._canUseWebWorker()?this._socket=new it:this._socket=new st,this.connect()}connect(){this.doOpen(),this._bindSocketHandlers()}doOpen(){[nt.CONNECTED,nt.CONNECTING].includes(this._readyState)||(this._readyState=nt.CONNECTING,this._ws=this._socket.connectSocket(this._url))}send(e){this._readyState!==nt.CONNECTED?this.reconnect():this._socket.send(e)}reconnect(){[nt.CONNECTED,nt.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===nt.CONNECTED}disconnect(){this._readyState=nt.DISCONNECTED,this._unbindSocketHandlers(),this._socket.disconnect()}_onOpen(e){this._readyState===nt.CONNECTING&&(this._readyState=nt.CONNECTED,this._emitter.emit("connect",{socketId:this._id,event:e}))}_onMessage(e){this._emitter.emit("message",e)}_onClose(e){this._readyState=nt.DISCONNECTED,this._emitter.emit("close",{socketId:this._id,event:e})}_onError(e){this._readyState=nt.DISCONNECTED,this._emitter.emit("error",{socketId:this._id,error:e})}_onSendFail(e){this._readyState=nt.DISCONNECTED,this._emitter.emit("sendFail",{socketId:this._id,error:e})}_bindSocketHandlers(){this._socket.bindSocketHandlers({onOpen:this._onOpen.bind(this),onMessage:this._onMessage.bind(this),onClose:this._onClose.bind(this),onError:this._onError.bind(this),onSendFail:this._onSendFail.bind(this)})}_unbindSocketHandlers(){this._socket.unbindSocketHandlers()}_canUseWebWorker(){var e=c.get("cloudConfig")||{};return(G(e.isWorkerEnabled)||"1"===e.isWorkerEnabled)&&Ue}}let at={TEST:{CHINA:{DEFAULT:"wss://wss-dev.tim.qq.com"},OVERSEA:{DEFAULT:"wss://wss-dev.tim.qq.com"},SINGAPORE:{DEFAULT:"wss://wsssgp-dev.im.qcloud.com"},KOREA:{DEFAULT:"wss://wsskr-dev.im.qcloud.com"},GERMANY:{DEFAULT:"wss://wssger-dev.im.qcloud.com"},IND:{DEFAULT:"wss://wssind-dev.im.qcloud.com"},JPN:{DEFAULT:"wss://wssjpn-dev.im.qcloud.com"},USA:{DEFAULT:"wss://wssusa-dev.im.qcloud.com"},INDONESIA:{DEFAULT:"wss://wssidn-dev.im.qcloud.com"}},PRODUCTION:{CHINA:{INITIAL:"wss://*w4c.my-imcloud.com",DEFAULT:"wss://wss.im.qcloud.com",IPV6:"wss://wssv6.im.qcloud.com",BACKUP:"wss://wss.tim.qq.com",BACKUP_WEB_ONLY:"wss://*w4c.my-cpaas.com",BACKUP_CN:"wss://wss.im.tencent.cn",STAT:"https://events.im.qcloud.com",ANYCAST:"wss://162.14.13.203"},OVERSEA:{INITIAL:"wss://*w4c.my-imcloud.com",DEFAULT:"wss://wss.im.qcloud.com",IPV6:"wss://wssv6.im.qcloud.com",BACKUP:"wss://wss.my-imcloud.com",BACKUP_WEB_ONLY:"wss://*w4c.my-cpaas.com",BACKUP_CN:"wss://wss.im.tencent.cn",STAT:"https://api.my-imcloud.com"},SINGAPORE:{INITIAL:"wss://*w4s.my-imcloud.com",DEFAULT:"wss://wsssgp.im.qcloud.com",IPV6:"wss://wsssgpv6.im.qcloud.com",BACKUP:"wss://wsssgp.my-imcloud.com",BACKUP_WEB_ONLY:"wss://*w4s.my-cpaas.com",STAT:"https://apisgp.my-imcloud.com",ANYCAST:"wss://162.14.19.159"},KOREA:{INITIAL:"wss://*w4k.my-imcloud.com",DEFAULT:"wss://wsskr.im.qcloud.com",IPV6:"wss://wsskrv6.im.qcloud.com",BACKUP:"wss://wsskr.my-imcloud.com",BACKUP_WEB_ONLY:"wss://*w4k.my-cpaas.com",STAT:"https://apikr.my-imcloud.com",ANYCAST:"wss://162.14.13.104"},GERMANY:{INITIAL:"wss://*w4g.my-imcloud.com",DEFAULT:"wss://wssger.im.qcloud.com",IPV6:"wss://wssgerv6.im.qcloud.com",BACKUP:"wss://wssger.my-imcloud.com",BACKUP_WEB_ONLY:"wss://*w4g.my-cpaas.com",STAT:"https://apiger.my-imcloud.com",ANYCAST:"wss://162.14.3.17"},IND:{INITIAL:"wss://*w4i.my-imcloud.com",DEFAULT:"wss://wssind.my-imcloud.com",IPV6:"wss://wssindv6.im.qcloud.com",BACKUP:"wss://wssind.im.qcloud.com",BACKUP_WEB_ONLY:"wss://*w4i.my-cpaas.com",STAT:"https://apiind.my-imcloud.com",ANYCAST:"wss://162.14.19.46"},JPN:{INITIAL:"wss://*w4j.my-imcloud.com",DEFAULT:"wss://wssjpn.im.qcloud.com",IPV6:"wss://wssjpnv6.im.qcloud.com",BACKUP:"wss://wssjpn.my-imcloud.com",BACKUP_WEB_ONLY:"wss://*w4j.my-cpaas.com",STAT:"https://apijpn.my-imcloud.com",ANYCAST:"wss://162.14.13.254"},USA:{INITIAL:"wss://*w4u.my-imcloud.com",DEFAULT:"wss://wssusa.im.qcloud.com",IPV6:"wss://wssusav6.im.qcloud.com",BACKUP:"wss://wssusa.my-imcloud.com",BACKUP_WEB_ONLY:"wss://*w4u.my-cpaas.com",STAT:"https://apiusa.my-imcloud.com",ANYCAST:"wss://162.14.10.42"},INDONESIA:{INITIAL:"wss://*w4y.my-imcloud.com",DEFAULT:"wss://wssidn.im.qcloud.com",IPV6:"wss://wssidnv6.im.qcloud.com",BACKUP:"wss://wssidn.my-imcloud.com",BACKUP_WEB_ONLY:"wss://*w4y.my-cpaas.com",STAT:"https://apiidn.my-imcloud.com",ANYCAST:"wss://43.129.34.169"}}},lt={SINGAPORE:[[2e7,3e7],[172e7,173e7]],KOREA:[[3e7,4e7],[173e7,174e7]],GERMANY:[[4e7,5e7],[174e7,175e7]],IND:[[5e7,6e7],[175e7,176e7]],JPN:[[6e7,7e7],[176e7,177e7]],USA:[[7e7,8e7],[177e7,178e7]],INDONESIA:[[8e7,9e7],[178e7,179e7]]};function ut(t){var e;if(null!=(e=c.get("instance"))&&e.oversea)return"OVERSEA";for(let e of Object.keys(lt))for(var[s,r]of lt[e])if(t>=s&&t<r)return e;return"CHINA"}var a,ct="1.6.4";(n=a=a||{}).INITIAL="INITIAL",n.DEFAULT="DEFAULT",n.BACKUP="BACKUP",n.BACKUP_WEB_ONLY="BACKUP_WEB_ONLY",n.BACKUP_CN="BACKUP_CN",n.ANYCAST="ANYCAST",n.IPV6="IPV6";let dt=a.INITIAL;function ht(e,t){var s,{isBinary:t=!1}=t||{},{sdkAppId:r,instanceId:i}=c.get("instance"),n=function e(){var t=Math.random();return 0===t?e():t}(),o=xe(),a=function(){var e=xe();let t=-1;return"ios"===e?t=Oe||-1:"android"===e&&(t=Te||-1),t}(),r=(s={sdkappid:r,instanceid:i,random:n,platform:Ee,host:o,version:a,sdkversion:ct},Object.keys(s).map(e=>e+"="+s[e]).join("&"));return t?e+`/binfo?${r}&compress=gzip`:e+"/info?"+r}function gt(e){var{sdkAppId:t,testEnv:s}=c.get("instance"),t=ut(t);if(s)return ht(at.TEST[t].DEFAULT,{isBinary:e});let r=at.PRODUCTION[t],i=ve&&r.ANYCAST,n=ve,o=!!r.BACKUP_CN;return ht({[a.INITIAL]:()=>(dt=a.DEFAULT,r.DEFAULT),[a.DEFAULT]:()=>(dt=a.IPV6,r.IPV6),[a.IPV6]:()=>(dt=a.BACKUP,r.BACKUP),[a.BACKUP]:()=>{return n?(dt=a.BACKUP_WEB_ONLY,e=r.BACKUP_WEB_ONLY,t=Math.floor(10001*Math.random())+1e4,e.replace("*",String(t))):o?(dt=a.BACKUP_CN,r.BACKUP_CN):i?(dt=a.ANYCAST,r.ANYCAST):r.DEFAULT;var e,t},[a.BACKUP_WEB_ONLY]:()=>o?(dt=a.BACKUP_CN,r.BACKUP_CN):i?(dt=a.ANYCAST,r.ANYCAST):r.DEFAULT,[a.BACKUP_CN]:()=>(dt=i?a.ANYCAST:a.DEFAULT,r[dt]),[a.ANYCAST]:()=>(dt=a.DEFAULT,r.ANYCAST="",r.DEFAULT)}[dt](),{isBinary:e})}var pt=new class{constructor(){this._timeOffsetWithServer=0}getServerTimeMs(){return Date.now()+this._timeOffsetWithServer}getServerTimeSeconds(){return Math.floor(this.getServerTimeMs()/1e3)}getTimeOffsetWithServer(){return this._timeOffsetWithServer}calculateTimeOffsetWithServer(e,t){var s=Date.now();this._timeOffsetWithServer=t+(s-e)-s}};var _t=new class{constructor(){this._tasks=[],this._timer=null,this._taskMap=new Map}_addTaskToScheduler(e){var t=e["id"];this.removeTask(t),this._tasks.push(e),this._taskMap.set(t,e),this._sort(),this._scheduleNextTask()}_createTask(e){var{id:e,callback:t,context:s,isOnce:r=!1,intervalMs:i=16}=e,n=Math.max(i,16);return{id:e,nextExecuteTime:Date.now()+n,intervalMs:i,callback:t,context:s,isOnce:r}}addTask(e){e=this._createTask(e);this._addTaskToScheduler(e)}addOnceTask(e){e=this._createTask(Object.assign(Object.assign({},e),{isOnce:!0}));this._addTaskToScheduler(e)}removeTask(t){var e=this._tasks.findIndex(e=>e.id===t);-1<e&&(this._tasks.splice(e,1),this._taskMap.delete(t),this._scheduleNextTask())}updateTaskInterval(e,t){e=this._taskMap.get(e);e&&(e.intervalMs=t,e.nextExecuteTime=Date.now()+t,this._sort(),this._scheduleNextTask())}clearAllTasks(){this._tasks=[],this._taskMap.clear(),this._timer&&(clearTimeout(this._timer),this._timer=null)}dispose(){this.clearAllTasks()}_sort(){this._tasks.sort((e,t)=>e.nextExecuteTime-t.nextExecuteTime)}_scheduleNextTask(){this._timer&&(clearTimeout(this._timer),this._timer=null);var e=this._tasks[0];e&&(e=Math.max(0,e.nextExecuteTime-Date.now()),this._timer=setTimeout(()=>this._execute(),e))}_execute(){for(var e=Date.now();this._tasks.length&&this._tasks[0].nextExecuteTime<=e;){var t=this._tasks[0];try{t.context?t.callback.call(t.context):t.callback(),t.isOnce?this.removeTask(t.id):(t.nextExecuteTime=e+t.intervalMs,this._sort())}catch(e){console.warn(`Task ${t.id} execution failed:`,e),t.isOnce&&this.removeTask(t.id)}}this._scheduleNextTask()}};function mt(t){var s=[];for(let e=0;e<t.length;e+=1){var r,i=t.charCodeAt(e);55296<=i&&i<=56319?(r=t.charCodeAt(++e)-56320+(i-55296<<10)+65536,s.push(240|r>>18,128|r>>12&63,128|r>>6&63,128|63&r)):i<=127?s.push(i):i<=2047?s.push(192|i>>6,128|63&i):s.push(224|i>>12,128|i>>6&63,128|63&i)}return new Uint8Array(s)}function vt(e){var t,s=Array.isArray(e)?[]:Object.create(null);for(t in e)Object.prototype.hasOwnProperty.call(e,t)&&B(t)&&null!=e[t]&&(null===e[t]||"object"!=typeof e[t]?s[t]=e[t]:s[t]=vt(e[t]));return s}function ft(e,t){if($.includes(e))return 0;var s=mt(JSON.stringify(t));let r=4294967295;var i=s["length"];for(let e=0;e<i;e++){r^=s[e];for(let e=0;e<8;e++)1&~r?r>>>=1:r=r>>>1^3988292384}return(4294967295^r)>>>0}function It(e){var t,{servcmd:e,data:s}=e,r=(r=e,i=c.get("login")||{},t=c.get("instance")||{},{servcmd:r,ver:"v4",platform:Ee,websdkappid:537048168,websdkversion:"1.7.3",a2:i.a2Key||void 0,tinyid:i.tinyID||void 0,status_instid:i.statusInstanceId||0,sdkappid:t.sdkAppId,contenttype:"json",reqtime:Math.floor(Date.now()/1e3),identifier:i.a2Key?void 0:i.userId,usersig:i.a2Key?void 0:i.userSig,sdkability:75689843,sdkability_ext:W(""),cappid:t.applicationID||0,tjgID:"",seq:Ct(),cs:0}),i=vt(s);return r.cs=ft(e,i),{head:r,body:i}}function Et(e){var t,{servcmd:e,data:s}=e,r=(r=e,i=c.get("login")||{},t=c.get("instance")||{},{servcmd:r,ver:"v4",platform:Ee,websdkappid:537048168,websdkversion:"1.7.3",sdkappid:t.sdkAppId,contenttype:"",reqtime:Math.floor(Date.now()/1e3),identifier:"",usersig:"",status_instid:i.statusInstanceId||0,sdkability:75689843,sdkability_ext:W(""),cappid:t.applicationID||0,seq:Ct(),cs:0}),i=vt(s);return r.cs=ft(e,i),{head:r,body:i}}let St=K();function Ct(){return St=St<2415919103?St+1:K()}function Mt(){var e=c.get("login")||{},t=c.get("instance")||{};return{sdk_type:30,sdk_app_id:t.sdkAppId,sdk_version:"1.6.4",tiny_id:Number(e.tinyID),user_id:e.userId,platform:Ee,instance_id:t.instanceId,trace_id:(new Date).getTime()}}var yt,n=Object.freeze({__proto__:null,generateCosSpecifiedData:function(e){var t,{servcmd:e,data:s}=e,r=(r=e,i=c.get("login")||{},t=c.get("instance")||{},{servcmd:r,ver:"v4",platform:Ee,websdkappid:537048168,websdkversion:"1.7.3",sdkappid:t.sdkAppId,contenttype:"json",reqtime:Math.floor(Date.now()/1e3),identifier:i.userId,usersig:i.userSig,status_instid:i.statusInstanceId||0,sdkability:75689843,sdkability_ext:W(""),cappid:t.applicationID||0,seq:Ct(),cs:0}),i=vt(s);return r.cs=ft(e,i),{head:r,body:i}},generateProtocolData:It,generateSSOLogProtocolData:Et,generateSequence:Ct,getCommonHead:Mt,taskScheduler:_t,timeManager:pt});(S=yt=yt||{})[S.info=4]="info",S[S.warning=5]="warning",S[S.error=6]="error";let Ot={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 At{constructor(e){this.level=yt.info,this._canSendLog=!0,this._logCreatedAt=pt.getServerTimeMs(),this.timestamp=0,this.networkType=8,this.code=0,this.moreMessage="",this.method="",this.message="",this.costTime=0,this.duplicate=!1,this.eventType=0,this.uiPlatform=this._getUiPlatform(),this._sdkEdition=this._getSDKEdition();var{method:e,eventType:t=0,message:s="",costTime:r=0,error:i,moreMessage:n=""}=e||{};this.eventType=t,this.method=e,this.message=s,this.costTime=r,this.moreMessage=n,i&&this.setError(i)}setMoreMessage(e){this.moreMessage=this.moreMessage+" "+e}updateLogCreatedAtByTimeOffset(){this._logCreatedAt+=pt.getTimeOffsetWithServer()}end(e=!1){this._canSendLog&&(this._canSendLog=!1,this.timestamp=pt.getServerTimeMs(),this._ssoLogModule.pushToLogQueue(this._convertSSOLogDataKeyToServe()),e)&&this._ssoLogModule.uploadSSOLogData()}setError(e){var t;return e instanceof Error?this._canSendLog&&(null!=(t=c.get("netWorkMonitor"))&&t.isNetworkOnline&&(e.errorCode&&(this.code=e.errorCode),e.errorMessage)&&this.setMoreMessage(e.errorMessage),this.level=yt.error):console.warn("SSOLogData.setError value not instanceof Error, please check!"),this}setLogInfo(t){return Object.keys(t).forEach(e=>{Object.keys(Ot).includes(e)&&(this[e]=t[e])}),this}setSSOLogModule(e){this._ssoLogModule=e}_convertSSOLogDataKeyToServe(){let t={};return Object.keys(this).forEach(e=>{Ot[e]&&(t[Ot[e]]=this[e])}),t}_getUiPlatform(){var e,t=null==(e=c.get("instance"))?void 0:e.scene;if("string"==typeof t){let e=Number(t);return isNaN(e)?void 0:e}}_getSDKEdition(){var e;return null==(e=c.get("instance"))?void 0:e.sdkEdition}}(S=m=m||{}).RECONNECTED="reconnected",S.CLOUD_CONFIG_UPDATE="cloud_config_update",S.SOCKET_DISCONNECTED="socket_disconnected";var Tt=m;let Rt=[4,5,6],Dt=[],bt=[],Nt="report-logger";var Lt=new class{constructor(){this._sdkAppIdBlackList=[],this._tinyIdWhiteList=[],this._reportLevel=[4,5,6],this._minThreshold=20,this._maxThreshold=100,this._waitingTime=6e4,this._lastReportAt=Date.now(),this._ssoLogMap=new Map,this._logLevel=i.DEBUG,this._throttleConfig={global:{throttleTime:5e3,maxCount:50},single:{throttleTime:1e3,maxCount:2}},this._globalThrottle={count:0,startTime:Date.now()},this._singleThrottleMap=new Map,et.subscribeInnerEvent(Tt.CLOUD_CONFIG_UPDATE,this._handleCloudConfigUpdate,this),_t.addTask({id:Nt,intervalMs:1e3,callback:this._checkAndReportIfDue,context:this}),this._logQueue=[],this._savePlatFormInfo()}_handleCloudConfigUpdate(e){var{evt_rpt_threshold:e=20,evt_rpt_waiting:t=6e4,evt_rpt_level:s=Rt,evt_rpt_sdkappid_bl:r=Dt,evt_rpt_tinyid_wl:i=bt,evt_rpt_global_throttle_time:n=5e3,evt_rpt_global_throttle_count:o=50,evt_rpt_single_throttle_time:a=1e3,evt_rpt_single_throttle_count:l=2}=e||{};this._sdkAppIdBlackList=r,this._waitingTime=t,this._minThreshold=e,this._reportLevel=s,this._tinyIdWhiteList=i,this._throttleConfig={global:{throttleTime:n,maxCount:o},single:{throttleTime:a,maxCount:l}}}createSSOLogData(e){var t=new At(e);return t.setSSOLogModule(this),this._ssoLogMap.set(e.method,t),t}getSSOLogData(e){return this._ssoLogMap.get(e)||{}}pushToLogQueue(e){e&&(this._logQueue.push(e),this._shouldUploadImmediately())&&this.uploadSSOLogData()}setLogLevel(e){[i.DEBUG,i.ERROR,i.INFO,i.NONE,i.WARN].includes(e)&&(this._logLevel=e)}debug(e,t="",s){this._log(i.DEBUG,e,t,s)}info(e,t="",s){this._log(i.INFO,e,t,s)}warn(e,t="",s){this._log(i.WARN,e,t,s)}error(e,t="",s){this._log(i.ERROR,e,t,s)}_shouldUploadImmediately(){return this._logQueue.length>=this._minThreshold}_isReportDue(){return Date.now()>=this._lastReportAt+this._waitingTime}_checkAndReportIfDue(){this._isReportDue()&&0<this._logQueue.length&&this.uploadSSOLogData()}uploadSSOLogData(){return I(this,void 0,void 0,function*(){var e,t;0!==this._logQueue.length&&(t=this._logQueue.slice(),t=this._filterLogs(t),this._logQueue=[],0===t.length||je((t={Header:Mt(),Event:t}).Header.user_id)||(e=(t=Et({servcmd:e="imopenstat.tim_web_report_v2",data:t})).head.seq+e,yield void Vt.sendPacket(t,{requestId:e})),this._lastReportAt=Date.now())})}_savePlatFormInfo(){var e,t;if(se){var s=null==(t=null==(e=wx.getAccountInfoSync)?void 0:e.call(wx))?void 0:t.miniProgram;if(s){let{appId:e,envVersion:t}=s;c.set("instance",{appId:e,envVersion:t})}}else ve&&c.set("instance",{href:window.location.href})}_filterLogs(e){var t=(c.get("login")||{})["tinyID"],s=(c.get("instance")||{})["sdkAppId"];return this._sdkAppIdBlackList.includes(s)&&!this._tinyIdWhiteList.includes(t)?[]:e.filter(e=>this._reportLevel.includes(e.level))}_checkThrottle(e){return!!this._checkGlobalThrottle()||this._checkSingleThrottle(e)}_checkGlobalThrottle(){var e=Date.now();if(e-this._globalThrottle.startTime>=this._throttleConfig.global.throttleTime)this._globalThrottle.count=1,this._globalThrottle.startTime=e;else if(this._globalThrottle.count++,this._globalThrottle.count>this._throttleConfig.global.maxCount)return!0;return!1}_checkSingleThrottle(e){var t=Date.now(),s=this._singleThrottleMap.get(e);return s?t-s.startTime>=this._throttleConfig.single.throttleTime?(s.count=1,s.startTime=t,!1):s.count>=this._throttleConfig.single.maxCount||(s.count++,!1):(this._singleThrottleMap.set(e,{count:1,startTime:t}),!1)}_shouldLog(e){return e>=this._logLevel&&this._logLevel!==i.NONE}_shouldReport(e){return this._reportLevel.includes(Z[e])}_formatLog(e,t,s){var r=new Date,r=`${r.getHours()}:${r.getMinutes()}:${r.getSeconds()}:`+r.getMilliseconds(),e=`<${i[e]}>`;return Ne||ge?[Q+` [${r}] ${e} [${t}] `+s]:["%c%s%c%s","background:#0abf5b; padding:1px; border-radius:3px; color: #fff",Q,"",`[${r}] ${e} [${t}] `+s]}_log(e,t,s,r){if(this._shouldLog(e)){var i=this._formatLog(e,t,s);if(X[e].apply(console,i),this._shouldReport(e)){let e=this._getThrottleKey(t,s,r);this._checkThrottle(e)||this.createSSOLogData(Object.assign(Object.assign({message:s},r),{method:t})).end()}}}_getThrottleKey(e,t,s){var e=""+e+t+He(Object.assign(Object.assign({},s),{costTime:""})),r=mt(JSON.stringify(e));let i=4294967295;var n=r["length"];for(let e=0;e<n;e++){i^=r[e];for(let e=0;e<8;e++)1&~i?i>>>=1:i=i>>>1^3988292384}return""+((4294967295^i)>>>0)}reset(){console.log("SSO_LOG_MODULE.reset"),_t.removeTask(Nt),et.unSubscribeInnerEvent(Tt.CLOUD_CONFIG_UPDATE,this._handleCloudConfigUpdate,this),this._lastReportAt=0,this.uploadSSOLogData(),this._sdkAppIdBlackList=[],this._tinyIdWhiteList=[],this._minThreshold=20,this._maxThreshold=100,this._waitingTime=6e4,this._logQueue=[],this._logLevel=i.DEBUG,this._globalThrottle={count:0,startTime:Date.now()},this._singleThrottleMap.clear()}};let l="Channel",Pt="channel_schedule_task",Gt="channel_reconnect_task",wt="connected",Ut="disconnected",kt="network_status_change";function Ft(e){return(Ft="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e})(e)}function qt(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 xt=function s(r,i,n){function o(t,e){if(!i[t]){if(!r[t]){if(!e&&qt)return qt(t);if(a)return a(t,!0);e=new Error("Cannot find module '"+t+"'");throw e.code="MODULE_NOT_FOUND",e}e=i[t]={exports:{}};r[t][0].call(e.exports,function(e){return o(r[t][1][e]||e)},e,e.exports,s,r,i,n)}return i[t].exports}for(var a=qt,e=0;e<n.length;e++)o(n[e]);return o}({1:[function(e,t,s){var r="undefined"!=typeof Uint8Array&&"undefined"!=typeof Uint16Array&&"undefined"!=typeof Int32Array,i=(s.assign=function(e){for(var t,s,r=Array.prototype.slice.call(arguments,1);r.length;){var i=r.shift();if(i){if("object"!=Ft(i))throw new TypeError(i+"must be non-object");for(var n in i)t=i,s=n,Object.prototype.hasOwnProperty.call(t,s)&&(e[n]=i[n])}}return e},s.shrinkBuf=function(e,t){return e.length===t?e:e.subarray?e.subarray(0,t):(e.length=t,e)},{arraySet:function(e,t,s,r,i){if(t.subarray&&e.subarray)e.set(t.subarray(s,s+r),i);else for(var n=0;n<r;n++)e[i+n]=t[s+n]},flattenChunks:function(e){for(var t,s,r,i,n=t=0,o=e.length;n<o;n++)t+=e[n].length;for(i=new Uint8Array(t),n=s=0,o=e.length;n<o;n++)r=e[n],i.set(r,s),s+=r.length;return i}}),n={arraySet:function(e,t,s,r,i){for(var n=0;n<r;n++)e[i+n]=t[s+n]},flattenChunks:function(e){return[].concat.apply([],e)}};s.setTyped=function(e){e?(s.Buf8=Uint8Array,s.Buf16=Uint16Array,s.Buf32=Int32Array,s.assign(s,i)):(s.Buf8=Array,s.Buf16=Array,s.Buf32=Array,s.assign(s,n))},s.setTyped(r)},{}],2:[function(e,t,s){var l=e("./common"),i=!0,n=!0;try{String.fromCharCode.apply(null,[0])}catch(e){i=!1}try{String.fromCharCode.apply(null,new Uint8Array(1))}catch(e){n=!1}for(var u=new l.Buf8(256),r=0;r<256;r++)u[r]=252<=r?6:248<=r?5:240<=r?4:224<=r?3:192<=r?2:1;function c(e,t){if(t<65534&&(e.subarray&&n||!e.subarray&&i))return String.fromCharCode.apply(null,l.shrinkBuf(e,t));for(var s="",r=0;r<t;r++)s+=String.fromCharCode(e[r]);return s}u[254]=u[254]=1,s.string2buf=function(e){for(var t,s,r,i,n=e.length,o=0,a=0;a<n;a++)55296==(64512&(s=e.charCodeAt(a)))&&a+1<n&&56320==(64512&(r=e.charCodeAt(a+1)))&&(s=65536+(s-55296<<10)+(r-56320),a++),o+=s<128?1:s<2048?2:s<65536?3:4;for(t=new l.Buf8(o),a=i=0;i<o;a++)55296==(64512&(s=e.charCodeAt(a)))&&a+1<n&&56320==(64512&(r=e.charCodeAt(a+1)))&&(s=65536+(s-55296<<10)+(r-56320),a++),s<128?t[i++]=s:(s<2048?t[i++]=192|s>>>6:(s<65536?t[i++]=224|s>>>12:(t[i++]=240|s>>>18,t[i++]=128|s>>>12&63),t[i++]=128|s>>>6&63),t[i++]=128|63&s);return t},s.buf2binstring=function(e){return c(e,e.length)},s.binstring2buf=function(e){for(var t=new l.Buf8(e.length),s=0,r=t.length;s<r;s++)t[s]=e.charCodeAt(s);return t},s.buf2string=function(e,t){for(var s,r,i,n=t||e.length,o=new Array(2*n),a=s=0;a<n;)if((r=e[a++])<128)o[s++]=r;else if(4<(i=u[r]))o[s++]=65533,a+=i-1;else{for(r&=2===i?31:3===i?15:7;1<i&&a<n;)r=r<<6|63&e[a++],i--;1<i?o[s++]=65533:r<65536?o[s++]=r:(r-=65536,o[s++]=55296|r>>10&1023,o[s++]=56320|1023&r)}return c(o,s)},s.utf8border=function(e,t){for(var s=(t=(t=t||e.length)>e.length?e.length:t)-1;0<=s&&128==(192&e[s]);)s--;return!(s<0||0===s)&&s+u[e[s]]>t?s:t}},{"./common":1}],3:[function(e,t,s){t.exports=function(e,t,s,r){for(var i=65535&e,n=e>>>16&65535,o=0;0!==s;){for(s-=o=2e3<s?2e3:s;n=n+(i=i+t[r++]|0)|0,--o;);i%=65521,n%=65521}return i|n<<16}},{}],4:[function(e,t,s){t.exports={Z_NO_FLUSH:0,Z_PARTIAL_FLUSH:1,Z_SYNC_FLUSH:2,Z_FULL_FLUSH:3,Z_FINISH:4,Z_BLOCK:5,Z_TREES:6,Z_OK:0,Z_STREAM_END:1,Z_NEED_DICT:2,Z_ERRNO:-1,Z_STREAM_ERROR:-2,Z_DATA_ERROR:-3,Z_BUF_ERROR:-5,Z_NO_COMPRESSION:0,Z_BEST_SPEED:1,Z_BEST_COMPRESSION:9,Z_DEFAULT_COMPRESSION:-1,Z_FILTERED:1,Z_HUFFMAN_ONLY:2,Z_RLE:3,Z_FIXED:4,Z_DEFAULT_STRATEGY:0,Z_BINARY:0,Z_TEXT:1,Z_UNKNOWN:2,Z_DEFLATED:8}},{}],5:[function(e,t,s){var a=function(){for(var e=[],t=0;t<256;t++){for(var s=t,r=0;r<8;r++)s=1&s?3988292384^s>>>1:s>>>1;e[t]=s}return e}();t.exports=function(e,t,s,r){var i=a,n=r+s;e^=-1;for(var o=r;o<n;o++)e=e>>>8^i[255&(e^t[o])];return-1^e}},{}],6:[function(e,t,s){t.exports=function(){this.text=0,this.time=0,this.xflags=0,this.os=0,this.extra=null,this.extra_len=0,this.name="",this.comment="",this.hcrc=0,this.done=!1}},{}],7:[function(e,t,s){t.exports=function(e,t){var s,r,i,n,o,a,l=e.state,u=e.next_in,c=e.input,d=u+(e.avail_in-5),h=e.next_out,g=e.output,p=h-(t-e.avail_out),_=h+(e.avail_out-257),m=l.dmax,v=l.wsize,f=l.whave,I=l.wnext,E=l.window,S=l.hold,C=l.bits,M=l.lencode,y=l.distcode,O=(1<<l.lenbits)-1,A=(1<<l.distbits)-1;e:do{for(C<15&&(S+=c[u++]<<C,C+=8,S+=c[u++]<<C,C+=8),s=M[S&O];;){if(S>>>=r=s>>>24,C-=r,0==(r=s>>>16&255))g[h++]=65535&s;else{if(!(16&r)){if(!(64&r)){s=M[(65535&s)+(S&(1<<r)-1)];continue}if(32&r){l.mode=12;break e}e.msg="invalid literal/length code",l.mode=30;break e}for(i=65535&s,(r&=15)&&(C<r&&(S+=c[u++]<<C,C+=8),i+=S&(1<<r)-1,S>>>=r,C-=r),C<15&&(S+=c[u++]<<C,C+=8,S+=c[u++]<<C,C+=8),s=y[S&A];;){if(S>>>=r=s>>>24,C-=r,!(16&(r=s>>>16&255))){if(!(64&r)){s=y[(65535&s)+(S&(1<<r)-1)];continue}e.msg="invalid distance code",l.mode=30;break e}if(n=65535&s,C<(r&=15)&&(S+=c[u++]<<C,(C+=8)<r)&&(S+=c[u++]<<C,C+=8),m<(n+=S&(1<<r)-1)){e.msg="invalid distance too far back",l.mode=30;break e}if(S>>>=r,C-=r,(r=h-p)<n){if(f<(r=n-r)&&l.sane){e.msg="invalid distance too far back",l.mode=30;break e}if(a=E,(o=0)===I){if(o+=v-r,r<i){for(i-=r;g[h++]=E[o++],--r;);o=h-n,a=g}}else if(I<r){if(o+=v+I-r,(r-=I)<i){for(i-=r;g[h++]=E[o++],--r;);if(o=0,I<i){for(i-=r=I;g[h++]=E[o++],--r;);o=h-n,a=g}}}else if(o+=I-r,r<i){for(i-=r;g[h++]=E[o++],--r;);o=h-n,a=g}for(;2<i;)g[h++]=a[o++],g[h++]=a[o++],g[h++]=a[o++],i-=3;i&&(g[h++]=a[o++],1<i)&&(g[h++]=a[o++])}else{for(o=h-n;g[h++]=g[o++],g[h++]=g[o++],g[h++]=g[o++],2<(i-=3););i&&(g[h++]=g[o++],1<i)&&(g[h++]=g[o++])}break}}break}}while(u<d&&h<_);u-=i=C>>3,S&=(1<<(C-=i<<3))-1,e.next_in=u,e.next_out=h,e.avail_in=u<d?d-u+5:5-(u-d),e.avail_out=h<_?_-h+257:257-(h-_),l.hold=S,l.bits=C}},{}],8:[function(e,t,s){var N=e("../utils/common"),L=e("./adler32"),P=e("./crc32"),G=e("./inffast"),w=e("./inftrees"),U=0,k=-2,F=1,r=852,i=592;function q(e){return(e>>>24&255)+(e>>>8&65280)+((65280&e)<<8)+((255&e)<<24)}function n(){this.mode=0,this.last=!1,this.wrap=0,this.havedict=!1,this.flags=0,this.dmax=0,this.check=0,this.total=0,this.head=null,this.wbits=0,this.wsize=0,this.whave=0,this.wnext=0,this.window=null,this.hold=0,this.bits=0,this.length=0,this.offset=0,this.extra=0,this.lencode=null,this.distcode=null,this.lenbits=0,this.distbits=0,this.ncode=0,this.nlen=0,this.ndist=0,this.have=0,this.next=null,this.lens=new N.Buf16(320),this.work=new N.Buf16(288),this.lendyn=null,this.distdyn=null,this.sane=0,this.back=0,this.was=0}function o(e){var t;return e&&e.state?(t=e.state,e.total_in=e.total_out=t.total=0,e.msg="",t.wrap&&(e.adler=1&t.wrap),t.mode=F,t.last=0,t.havedict=0,t.dmax=32768,t.head=null,t.hold=0,t.bits=0,t.lencode=t.lendyn=new N.Buf32(r),t.distcode=t.distdyn=new N.Buf32(i),t.sane=1,t.back=-1,U):k}function a(e){var t;return e&&e.state?((t=e.state).wsize=0,t.whave=0,t.wnext=0,o(e)):k}function l(e,t){var s,r;return!e||!e.state||(r=e.state,t<0?(s=0,t=-t):(s=1+(t>>4),t<48&&(t&=15)),t&&(t<8||15<t))?k:(null!==r.window&&r.wbits!==t&&(r.window=null),r.wrap=s,r.wbits=t,a(e))}function u(e,t){var s;return e?(s=new n,(e.state=s).window=null,(s=l(e,t))!==U&&(e.state=null),s):k}var x,V,B=!0;function j(e,t,s,r){var i,e=e.state;return null===e.window&&(e.wsize=1<<e.wbits,e.wnext=0,e.whave=0,e.window=new N.Buf8(e.wsize)),r>=e.wsize?(N.arraySet(e.window,t,s-e.wsize,e.wsize,0),e.wnext=0,e.whave=e.wsize):(r<(i=e.wsize-e.wnext)&&(i=r),N.arraySet(e.window,t,s-r,i,e.wnext),(r-=i)?(N.arraySet(e.window,t,s-r,r,0),e.wnext=r,e.whave=e.wsize):(e.wnext+=i,e.wnext===e.wsize&&(e.wnext=0),e.whave<e.wsize&&(e.whave+=i))),0}s.inflateReset=a,s.inflateReset2=l,s.inflateResetKeep=o,s.inflateInit=function(e){return u(e,15)},s.inflateInit2=u,s.inflate=function(e,t){var s,r,i,n,o,a,l,u,c,d,h,g,p,_,m,v,f,I,E,S,C,M,y,O,A=0,T=new N.Buf8(4),R=[16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15];if(!e||!e.state||!e.output||!e.input&&0!==e.avail_in)return k;12===(s=e.state).mode&&(s.mode=13),o=e.next_out,i=e.output,l=e.avail_out,n=e.next_in,r=e.input,a=e.avail_in,u=s.hold,c=s.bits,d=a,h=l,M=U;e:for(;;)switch(s.mode){case F:if(0===s.wrap)s.mode=13;else{for(;c<16;){if(0===a)break e;a--,u+=r[n++]<<c,c+=8}if(2&s.wrap&&35615===u)T[s.check=0]=255&u,T[1]=u>>>8&255,s.check=P(s.check,T,2,0),c=u=0,s.mode=2;else if(s.flags=0,s.head&&(s.head.done=!1),!(1&s.wrap)||(((255&u)<<8)+(u>>8))%31)e.msg="incorrect header check",s.mode=30;else if(8!=(15&u))e.msg="unknown compression method",s.mode=30;else{if(c-=4,C=8+(15&(u>>>=4)),0===s.wbits)s.wbits=C;else if(C>s.wbits){e.msg="invalid window size",s.mode=30;break}s.dmax=1<<C,e.adler=s.check=1,s.mode=512&u?10:12,c=u=0}}break;case 2:for(;c<16;){if(0===a)break e;a--,u+=r[n++]<<c,c+=8}if(s.flags=u,8!=(255&s.flags)){e.msg="unknown compression method",s.mode=30;break}if(57344&s.flags){e.msg="unknown header flags set",s.mode=30;break}s.head&&(s.head.text=u>>8&1),512&s.flags&&(T[0]=255&u,T[1]=u>>>8&255,s.check=P(s.check,T,2,0)),c=u=0,s.mode=3;case 3:for(;c<32;){if(0===a)break e;a--,u+=r[n++]<<c,c+=8}s.head&&(s.head.time=u),512&s.flags&&(T[0]=255&u,T[1]=u>>>8&255,T[2]=u>>>16&255,T[3]=u>>>24&255,s.check=P(s.check,T,4,0)),c=u=0,s.mode=4;case 4:for(;c<16;){if(0===a)break e;a--,u+=r[n++]<<c,c+=8}s.head&&(s.head.xflags=255&u,s.head.os=u>>8),512&s.flags&&(T[0]=255&u,T[1]=u>>>8&255,s.check=P(s.check,T,2,0)),c=u=0,s.mode=5;case 5:if(1024&s.flags){for(;c<16;){if(0===a)break e;a--,u+=r[n++]<<c,c+=8}s.length=u,s.head&&(s.head.extra_len=u),512&s.flags&&(T[0]=255&u,T[1]=u>>>8&255,s.check=P(s.check,T,2,0)),c=u=0}else s.head&&(s.head.extra=null);s.mode=6;case 6:if(1024&s.flags&&((g=a<(g=s.length)?a:g)&&(s.head&&(C=s.head.extra_len-s.length,s.head.extra||(s.head.extra=new Array(s.head.extra_len)),N.arraySet(s.head.extra,r,n,g,C)),512&s.flags&&(s.check=P(s.check,r,g,n)),a-=g,n+=g,s.length-=g),s.length))break e;s.length=0,s.mode=7;case 7:if(2048&s.flags){if(0===a)break e;for(g=0;C=r[n+g++],s.head&&C&&s.length<65536&&(s.head.name+=String.fromCharCode(C)),C&&g<a;);if(512&s.flags&&(s.check=P(s.check,r,g,n)),a-=g,n+=g,C)break e}else s.head&&(s.head.name=null);s.length=0,s.mode=8;case 8:if(4096&s.flags){if(0===a)break e;for(g=0;C=r[n+g++],s.head&&C&&s.length<65536&&(s.head.comment+=String.fromCharCode(C)),C&&g<a;);if(512&s.flags&&(s.check=P(s.check,r,g,n)),a-=g,n+=g,C)break e}else s.head&&(s.head.comment=null);s.mode=9;case 9:if(512&s.flags){for(;c<16;){if(0===a)break e;a--,u+=r[n++]<<c,c+=8}if(u!==(65535&s.check)){e.msg="header crc mismatch",s.mode=30;break}c=u=0}s.head&&(s.head.hcrc=s.flags>>9&1,s.head.done=!0),e.adler=s.check=0,s.mode=12;break;case 10:for(;c<32;){if(0===a)break e;a--,u+=r[n++]<<c,c+=8}e.adler=s.check=q(u),c=u=0,s.mode=11;case 11:if(0===s.havedict)return e.next_out=o,e.avail_out=l,e.next_in=n,e.avail_in=a,s.hold=u,s.bits=c,2;e.adler=s.check=1,s.mode=12;case 12:if(5===t||6===t)break e;case 13:if(s.last)u>>>=7&c,c-=7&c,s.mode=27;else{for(;c<3;){if(0===a)break e;a--,u+=r[n++]<<c,c+=8}switch(s.last=1&u,--c,3&(u>>>=1)){case 0:s.mode=14;break;case 1:D=b=void 0;var D,b=s;if(B){for(x=new N.Buf32(512),V=new N.Buf32(32),D=0;D<144;)b.lens[D++]=8;for(;D<256;)b.lens[D++]=9;for(;D<280;)b.lens[D++]=7;for(;D<288;)b.lens[D++]=8;for(w(1,b.lens,0,288,x,0,b.work,{bits:9}),D=0;D<32;)b.lens[D++]=5;w(2,b.lens,0,32,V,0,b.work,{bits:5}),B=!1}if(b.lencode=x,b.lenbits=9,b.distcode=V,b.distbits=5,s.mode=20,6!==t)break;u>>>=2,c-=2;break e;case 2:s.mode=17;break;case 3:e.msg="invalid block type",s.mode=30}u>>>=2,c-=2}break;case 14:for(u>>>=7&c,c-=7&c;c<32;){if(0===a)break e;a--,u+=r[n++]<<c,c+=8}if((65535&u)!=(u>>>16^65535)){e.msg="invalid stored block lengths",s.mode=30;break}if(s.length=65535&u,c=u=0,s.mode=15,6===t)break e;case 15:s.mode=16;case 16:if(g=s.length){if(0===(g=l<(g=a<g?a:g)?l:g))break e;N.arraySet(i,r,n,g,o),a-=g,n+=g,l-=g,o+=g,s.length-=g}else s.mode=12;break;case 17:for(;c<14;){if(0===a)break e;a--,u+=r[n++]<<c,c+=8}if(s.nlen=257+(31&u),u>>>=5,c-=5,s.ndist=1+(31&u),u>>>=5,c-=5,s.ncode=4+(15&u),u>>>=4,c-=4,286<s.nlen||30<s.ndist){e.msg="too many length or distance symbols",s.mode=30;break}s.have=0,s.mode=18;case 18:for(;s.have<s.ncode;){for(;c<3;){if(0===a)break e;a--,u+=r[n++]<<c,c+=8}s.lens[R[s.have++]]=7&u,u>>>=3,c-=3}for(;s.have<19;)s.lens[R[s.have++]]=0;if(s.lencode=s.lendyn,s.lenbits=7,y={bits:s.lenbits},M=w(0,s.lens,0,19,s.lencode,0,s.work,y),s.lenbits=y.bits,M){e.msg="invalid code lengths set",s.mode=30;break}s.have=0,s.mode=19;case 19:for(;s.have<s.nlen+s.ndist;){for(;v=(A=s.lencode[u&(1<<s.lenbits)-1])>>>16&255,f=65535&A,!((m=A>>>24)<=c);){if(0===a)break e;a--,u+=r[n++]<<c,c+=8}if(f<16)u>>>=m,c-=m,s.lens[s.have++]=f;else{if(16===f){for(O=m+2;c<O;){if(0===a)break e;a--,u+=r[n++]<<c,c+=8}if(u>>>=m,c-=m,0===s.have){e.msg="invalid bit length repeat",s.mode=30;break}C=s.lens[s.have-1],g=3+(3&u),u>>>=2,c-=2}else if(17===f){for(O=m+3;c<O;){if(0===a)break e;a--,u+=r[n++]<<c,c+=8}C=0,g=3+(7&(u>>>=m)),u>>>=3,c=c-m-3}else{for(O=m+7;c<O;){if(0===a)break e;a--,u+=r[n++]<<c,c+=8}C=0,g=11+(127&(u>>>=m)),u>>>=7,c=c-m-7}if(s.have+g>s.nlen+s.ndist){e.msg="invalid bit length repeat",s.mode=30;break}for(;g--;)s.lens[s.have++]=C}}if(30===s.mode)break;if(0===s.lens[256]){e.msg="invalid code -- missing end-of-block",s.mode=30;break}if(s.lenbits=9,y={bits:s.lenbits},M=w(1,s.lens,0,s.nlen,s.lencode,0,s.work,y),s.lenbits=y.bits,M){e.msg="invalid literal/lengths set",s.mode=30;break}if(s.distbits=6,s.distcode=s.distdyn,y={bits:s.distbits},M=w(2,s.lens,s.nlen,s.ndist,s.distcode,0,s.work,y),s.distbits=y.bits,M){e.msg="invalid distances set",s.mode=30;break}if(s.mode=20,6===t)break e;case 20:s.mode=21;case 21:if(6<=a&&258<=l){e.next_out=o,e.avail_out=l,e.next_in=n,e.avail_in=a,s.hold=u,s.bits=c,G(e,h),o=e.next_out,i=e.output,l=e.avail_out,n=e.next_in,r=e.input,a=e.avail_in,u=s.hold,c=s.bits,12===s.mode&&(s.back=-1);break}for(s.back=0;v=(A=s.lencode[u&(1<<s.lenbits)-1])>>>16&255,f=65535&A,!((m=A>>>24)<=c);){if(0===a)break e;a--,u+=r[n++]<<c,c+=8}if(v&&!(240&v)){for(I=m,E=v,S=f;v=(A=s.lencode[S+((u&(1<<I+E)-1)>>I)])>>>16&255,f=65535&A,!(I+(m=A>>>24)<=c);){if(0===a)break e;a--,u+=r[n++]<<c,c+=8}u>>>=I,c-=I,s.back+=I}if(u>>>=m,c-=m,s.back+=m,s.length=f,0===v){s.mode=26;break}if(32&v){s.back=-1,s.mode=12;break}if(64&v){e.msg="invalid literal/length code",s.mode=30;break}s.extra=15&v,s.mode=22;case 22:if(s.extra){for(O=s.extra;c<O;){if(0===a)break e;a--,u+=r[n++]<<c,c+=8}s.length+=u&(1<<s.extra)-1,u>>>=s.extra,c-=s.extra,s.back+=s.extra}s.was=s.length,s.mode=23;case 23:for(;v=(A=s.distcode[u&(1<<s.distbits)-1])>>>16&255,f=65535&A,!((m=A>>>24)<=c);){if(0===a)break e;a--,u+=r[n++]<<c,c+=8}if(!(240&v)){for(I=m,E=v,S=f;v=(A=s.distcode[S+((u&(1<<I+E)-1)>>I)])>>>16&255,f=65535&A,!(I+(m=A>>>24)<=c);){if(0===a)break e;a--,u+=r[n++]<<c,c+=8}u>>>=I,c-=I,s.back+=I}if(u>>>=m,c-=m,s.back+=m,64&v){e.msg="invalid distance code",s.mode=30;break}s.offset=f,s.extra=15&v,s.mode=24;case 24:if(s.extra){for(O=s.extra;c<O;){if(0===a)break e;a--,u+=r[n++]<<c,c+=8}s.offset+=u&(1<<s.extra)-1,u>>>=s.extra,c-=s.extra,s.back+=s.extra}if(s.offset>s.dmax){e.msg="invalid distance too far back",s.mode=30;break}s.mode=25;case 25:if(0===l)break e;if(s.offset>(g=h-l)){if((g=s.offset-g)>s.whave&&s.sane){e.msg="invalid distance too far back",s.mode=30;break}p=g>s.wnext?(g-=s.wnext,s.wsize-g):s.wnext-g,g>s.length&&(g=s.length),_=s.window}else _=i,p=o-s.offset,g=s.length;for(l-=g=l<g?l:g,s.length-=g;i[o++]=_[p++],--g;);0===s.length&&(s.mode=21);break;case 26:if(0===l)break e;i[o++]=s.length,l--,s.mode=21;break;case 27:if(s.wrap){for(;c<32;){if(0===a)break e;a--,u|=r[n++]<<c,c+=8}if(h-=l,e.total_out+=h,s.total+=h,h&&(e.adler=s.check=(s.flags?P:L)(s.check,i,h,o-h)),h=l,(s.flags?u:q(u))!==s.check){e.msg="incorrect data check",s.mode=30;break}c=u=0}s.mode=28;case 28:if(s.wrap&&s.flags){for(;c<32;){if(0===a)break e;a--,u+=r[n++]<<c,c+=8}if(u!==(4294967295&s.total)){e.msg="incorrect length check",s.mode=30;break}c=u=0}s.mode=29;case 29:M=1;break e;case 30:M=-3;break e;case 31:return-4;default:return k}return e.next_out=o,e.avail_out=l,e.next_in=n,e.avail_in=a,s.hold=u,s.bits=c,(s.wsize||h!==e.avail_out&&s.mode<30&&(s.mode<27||4!==t))&&j(e,e.output,e.next_out,h-e.avail_out)?(s.mode=31,-4):(d-=e.avail_in,h-=e.avail_out,e.total_in+=d,e.total_out+=h,s.total+=h,s.wrap&&h&&(e.adler=s.check=(s.flags?P:L)(s.check,i,h,e.next_out-h)),e.data_type=s.bits+(s.last?64:0)+(12===s.mode?128:0)+(20===s.mode||15===s.mode?256:0),M=(0==d&&0===h||4===t)&&M===U?-5:M)},s.inflateEnd=function(e){var t;return e&&e.state?((t=e.state).window&&(t.window=null),e.state=null,U):k},s.inflateGetHeader=function(e,t){return e&&e.state&&2&(e=e.state).wrap?((e.head=t).done=!1,U):k},s.inflateSetDictionary=function(e,t){var s,r=t.length;return!e||!e.state||0!==(s=e.state).wrap&&11!==s.mode?k:11===s.mode&&L(1,t,r,0)!==s.check?-3:j(e,t,r,r)?(s.mode=31,-4):(s.havedict=1,U)},s.inflateInfo="pako inflate (from Nodeca project)"},{"../utils/common":1,"./adler32":3,"./crc32":5,"./inffast":7,"./inftrees":9}],9:[function(e,t,s){var G=e("../utils/common"),w=[3,4,5,6,7,8,9,10,11,13,15,17,19,23,27,31,35,43,51,59,67,83,99,115,131,163,195,227,258,0,0],U=[16,16,16,16,16,16,16,16,17,17,17,17,18,18,18,18,19,19,19,19,20,20,20,20,21,21,21,21,16,72,78],k=[1,2,3,4,5,7,9,13,17,25,33,49,65,97,129,193,257,385,513,769,1025,1537,2049,3073,4097,6145,8193,12289,16385,24577,0,0],F=[16,16,16,16,17,17,18,18,19,19,20,20,21,21,22,22,23,23,24,24,25,25,26,26,27,27,28,28,29,29,64,64];t.exports=function(e,t,s,r,i,n,o,a){for(var l,u,c,d,h,g,p,_,m,v=a.bits,f=0,I=0,E=0,S=0,C=0,M=0,y=0,O=0,A=0,T=0,R=null,D=0,b=new G.Buf16(16),N=new G.Buf16(16),L=null,P=0,f=0;f<=15;f++)b[f]=0;for(I=0;I<r;I++)b[t[s+I]]++;for(C=v,S=15;1<=S&&0===b[S];S--);if(S<C&&(C=S),0===S)i[n++]=20971520,i[n++]=20971520,a.bits=1;else{for(E=1;E<S&&0===b[E];E++);for(C<E&&(C=E),f=O=1;f<=15;f++)if((O=(O<<1)-b[f])<0)return-1;if(0<O&&(0===e||1!==S))return-1;for(N[1]=0,f=1;f<15;f++)N[f+1]=N[f]+b[f];for(I=0;I<r;I++)0!==t[s+I]&&(o[N[t[s+I]]++]=I);if(g=0===e?(R=L=o,19):1===e?(R=w,D-=257,L=U,P-=257,256):(R=k,L=F,-1),f=E,h=n,y=I=T=0,c=-1,d=(A=1<<(M=C))-1,1===e&&852<A||2===e&&592<A)return 1;for(;;){for(m=o[I]<g?(_=0,o[I]):o[I]>g?(_=L[P+o[I]],R[D+o[I]]):(_=96,0),l=1<<(p=f-y),E=u=1<<M;i[h+(T>>y)+(u-=l)]=p<<24|_<<16|m,0!==u;);for(l=1<<f-1;T&l;)l>>=1;if(0!==l?T=(T&l-1)+l:T=0,I++,0==--b[f]){if(f===S)break;f=t[s+o[I]]}if(C<f&&(T&d)!==c){for(h+=E,O=1<<(M=f-(y=0===y?C:y));M+y<S&&!((O-=b[M+y])<=0);)M++,O<<=1;if(A+=1<<M,1===e&&852<A||2===e&&592<A)return 1;i[c=T&d]=C<<24|M<<16|h-n}}0!==T&&(i[h+T]=f-y<<24|64<<16),a.bits=C}return 0}},{"../utils/common":1}],10:[function(e,t,s){t.exports={2:"need dictionary",1:"stream end",0:"","-1":"file error","-2":"stream error","-3":"data error","-4":"insufficient memory","-5":"buffer error","-6":"incompatible version"}},{}],11:[function(e,t,s){t.exports=function(){this.input=null,this.next_in=0,this.avail_in=0,this.total_in=0,this.output=null,this.next_out=0,this.avail_out=0,this.total_out=0,this.msg="",this.state=null,this.data_type=2,this.adler=0}},{}],"/lib/inflate.js":[function(e,t,s){var d=e("./zlib/inflate"),h=e("./utils/common"),g=e("./utils/strings"),p=e("./zlib/constants"),r=e("./zlib/messages"),i=e("./zlib/zstream"),n=e("./zlib/gzheader"),_=Object.prototype.toString;function o(e){if(!(this instanceof o))return new o(e);this.options=h.assign({chunkSize:16384,windowBits:0,to:""},e||{});var t=this.options,e=(t.raw&&0<=t.windowBits&&t.windowBits<16&&(t.windowBits=-t.windowBits,0===t.windowBits)&&(t.windowBits=-15),!(0<=t.windowBits&&t.windowBits<16)||e&&e.windowBits||(t.windowBits+=32),15<t.windowBits&&t.windowBits<48&&!(15&t.windowBits)&&(t.windowBits|=15),this.err=0,this.msg="",this.ended=!1,this.chunks=[],this.strm=new i,this.strm.avail_out=0,d.inflateInit2(this.strm,t.windowBits));if(e!==p.Z_OK)throw new Error(r[e]);if(this.header=new n,d.inflateGetHeader(this.strm,this.header),t.dictionary&&("string"==typeof t.dictionary?t.dictionary=g.string2buf(t.dictionary):"[object ArrayBuffer]"===_.call(t.dictionary)&&(t.dictionary=new Uint8Array(t.dictionary)),t.raw)&&(e=d.inflateSetDictionary(this.strm,t.dictionary))!==p.Z_OK)throw new Error(r[e])}function a(e,t){t=new o(t);if(t.push(e,!0),t.err)throw t.msg||r[t.err];return t.result}o.prototype.push=function(e,t){var s,r,i,n,o,a=this.strm,l=this.options.chunkSize,u=this.options.dictionary,c=!1;if(this.ended)return!1;r=t===~~t?t:!0===t?p.Z_FINISH:p.Z_NO_FLUSH,"string"==typeof e?a.input=g.binstring2buf(e):"[object ArrayBuffer]"===_.call(e)?a.input=new Uint8Array(e):a.input=e,a.next_in=0,a.avail_in=a.input.length;do{if(0===a.avail_out&&(a.output=new h.Buf8(l),a.next_out=0,a.avail_out=l),(s=(s=d.inflate(a,p.Z_NO_FLUSH))===p.Z_NEED_DICT&&u?d.inflateSetDictionary(this.strm,u):s)===p.Z_BUF_ERROR&&!0===c&&(s=p.Z_OK,c=!1),s!==p.Z_STREAM_END&&s!==p.Z_OK)return this.onEnd(s),!(this.ended=!0)}while(!a.next_out||0!==a.avail_out&&s!==p.Z_STREAM_END&&(0!==a.avail_in||r!==p.Z_FINISH&&r!==p.Z_SYNC_FLUSH)||("string"===this.options.to?(i=g.utf8border(a.output,a.next_out),n=a.next_out-i,o=g.buf2string(a.output,i),a.next_out=n,a.avail_out=l-n,n&&h.arraySet(a.output,a.output,i,n,0),this.onData(o)):this.onData(h.shrinkBuf(a.output,a.next_out))),0===a.avail_in&&0===a.avail_out&&(c=!0),(0<a.avail_in||0===a.avail_out)&&s!==p.Z_STREAM_END);return(r=s===p.Z_STREAM_END?p.Z_FINISH:r)===p.Z_FINISH?(s=d.inflateEnd(this.strm),this.onEnd(s),this.ended=!0,s===p.Z_OK):r!==p.Z_SYNC_FLUSH||(this.onEnd(p.Z_OK),!(a.avail_out=0))},o.prototype.onData=function(e){this.chunks.push(e)},o.prototype.onEnd=function(e){e===p.Z_OK&&("string"===this.options.to?this.result=this.chunks.join(""):this.result=h.flattenChunks(this.chunks)),this.chunks=[],this.err=e,this.msg=this.strm.msg},s.Inflate=o,s.inflate=a,s.inflateRaw=function(e,t){return(t=t||{}).raw=!0,a(e,t)},s.ungzip=a},{"./utils/common":1,"./utils/strings":2,"./zlib/constants":4,"./zlib/gzheader":6,"./zlib/inflate":8,"./zlib/messages":10,"./zlib/zstream":11}]},{},[])("/lib/inflate.js"),Vt=new class{constructor(){this._socketAdapter=null,this._url="",this._isReconnecting=!1,this._pendingRequests=new Map,this._nextHeartbeatAt=0,this._lastDiagnoseAt=0,this._isHeartbeatInProgress=!1,this._connectionEstablishedTime=0,this._connectionStartTime=0,this._connectionId=-1,this._isBinarySupported=!0,this._intendedDelay=1e3,this._currentConnectState=wt,this._beforeSendInterceptors=[]}init(){_t.addTask({id:Pt,intervalMs:1e3,callback:this._executeScheduledTaskIfReady,context:this}),this._updateIsBinarySupported(),this._url=function(e){var{sdkAppId:t,testEnv:s,disableIndependentDomain:r}=c.get("instance"),i=ut(t);let n="";return s?n=at.TEST[i].DEFAULT:r?(n=at.PRODUCTION[i].DEFAULT,dt=a.DEFAULT):n=at.PRODUCTION[i].INITIAL.replace("*",""+t),ht(n,{isBinary:e})}(this._isBinarySupported),et.subscribeInnerEvent("networkStatusChange",this._handleNetworkStatusChange,this),et.subscribeInnerEvent("activityStatusChange",this._handleActivityStatusChange,this),this.connect()}sendPacket(e,t){var s,{requestId:r,timeout:i=15e3,canResend:n=!0}=t||{};if(je(e))return Lt.warn("sendPacket",l+".sendPacket: packet is empty "),null;this._executeBeforeSendInterceptors(e),this._currentConnectState===Ut&&this._handleConnectStateChange({state:Ut,shouldEmitEvent:!0,shouldAttemptReconnect:!0,reason:"send_fail"});var o=JSON.stringify(e);let a=null;if(r){let{resolve:e,reject:t,promise:s}=We();a=s,this._pendingRequests.set(r,{resolve:e,reject:t,timestamp:Date.now(),uplinkData:o,timeout:i,canResend:n})}t=this._isBinarySupported?mt(o).buffer:o;return null!=(s=this._socketAdapter)&&s.send(t),a}connect(){this._socketAdapter=new ot(this._url),this._connectionEstablishedTime=0,this._addEventListeners(),this._connectionStartTime=Date.now();var e=null==(e=this._socketAdapter)?void 0:e.getId(),t=l+`.connect isWorkerEnabled: false socketID:${e} url:`+this._url;this._connectionId=e,this._ssoLog({method:"connect",message:t})}disconnect(){var e=null==(e=this._socketAdapter)?void 0:e.getId(),e=l+".disconnect socketID:"+e;this._ssoLog({method:"disconnect",message:e}),this._removeEventListeners(),null!=(e=this._socketAdapter)&&e.disconnect()}getSocketAdapter(){return this._socketAdapter}dispose(){console.log(l+".dispose"),_t.removeTask(Pt),_t.removeTask(Gt),et.unSubscribeInnerEvent("networkStatusChange",this._handleNetworkStatusChange,this),et.unSubscribeInnerEvent("activityStatusChange",this._handleActivityStatusChange,this),this.disconnect(),this._socketAdapter=null,this._isReconnecting=!1,this._isHeartbeatInProgress=!1,this._pendingRequests.clear(),this._nextHeartbeatAt=0,this._lastDiagnoseAt=0,this._intendedDelay=1e3,this._url=""}registerBeforeSendInterceptor(e,t){this._beforeSendInterceptors.push(e.bind(t))}_executeBeforeSendInterceptors(e){for(var t of this._beforeSendInterceptors){var{servcmd:s=""}=null==e?void 0:e.head;t(s.includes(".")?s.split(".").pop():"")}}_shouldSkipReconnect(){var e="connecting"===this._currentConnectState&&this._isReconnecting;return!this._socketAdapter||e}reconnect(){return I(this,void 0,void 0,function*(){var e=l+`.reconnect isReconnecting: ${this._isReconnecting} currentConnectState: `+this._currentConnectState;if(this._ssoLog({method:"reconnect",message:e}),!this._shouldSkipReconnect()){this._url=gt(this._isBinarySupported);try{this._isReconnecting=!0,this.disconnect(),this.connect()}catch(e){this._isReconnecting=!1,this._handleConnectStateChange({state:Ut,shouldEmitEvent:!0,shouldAttemptReconnect:!0,reason:"reconnect_failed"}),console.warn(l+".reconnect failed: ",e)}}})}_addEventListeners(){var e;null!=(e=this._socketAdapter)&&e.on("connect",this._onConnect,this),null!=(e=this._socketAdapter)&&e.on("message",this._onMessage,this),null!=(e=this._socketAdapter)&&e.on("close",this._onClose,this),null!=(e=this._socketAdapter)&&e.on("error",this._onError,this),null!=(e=this._socketAdapter)&&e.on("sendFail",this._onSendFail,this)}_removeEventListeners(){var e;null!=(e=this._socketAdapter)&&e.off("connect",this._onConnect,this),null!=(e=this._socketAdapter)&&e.off("message",this._onMessage,this),null!=(e=this._socketAdapter)&&e.off("close",this._onClose,this),null!=(e=this._socketAdapter)&&e.off("error",this._onError,this),null!=(e=this._socketAdapter)&&e.off("sendFail",this._onSendFail,this)}_onClose(e){var{socketId:e,event:t}=e||{},s=0!==this._connectionEstablishedTime?Date.now()-this._connectionEstablishedTime:0,s=l+`.onClose closeSocketID: ${e} currentSocketID: ${this._connectionId} connectionDuration: ${s} code: ${null==t?void 0:t.code} reason: `+(null==t?void 0:t.reason);this._ssoLog({method:"onClose",message:s}),e===this._connectionId&&this._handleConnectStateChange({state:Ut,shouldEmitEvent:!0,shouldAttemptReconnect:!0,reason:"socket_close"}),this._isReconnecting&&(this._isReconnecting=!1)}_onError(e){var{socketId:e,error:t}=e||{},t=l+`.onError sourceSocketID: ${e} currentSocketID: ${this._connectionId} isReconnecting: ${this._isReconnecting} error: `+JSON.stringify(t);this._ssoLog({method:"onError",message:t}),e===this._connectionId&&this._handleConnectStateChange({state:Ut,shouldEmitEvent:!0,shouldAttemptReconnect:!0,reason:"socket_error"}),this._isReconnecting&&(this._isReconnecting=!1)}_onSendFail(e){var{socketId:e,error:t}=e||{},e=l+`.onSendFail sendFailSocketId: ${e} currentSocketID: ${this._connectionId} isReconnecting: ${this._isReconnecting} error: `+t;this._ssoLog({method:"onSendFail",message:e}),this._isReconnecting&&(this._isReconnecting=!1)}_onMessage(t){let s,e;this._updateHeartbeatTime();try{s=this._isBinarySupported?(this._isCompressedData(t.data)?e=>{var t=new Uint8Array(e).slice(4);let s;try{s=xt.inflate(t,{to:"string"})}catch(e){console.error("inflate error",e)}return s}:function(e){var i=new Uint8Array(e);let n="",o=0;for(var a=i["length"];o<a;){let t=i[o],s=0,r=0;if(t<=127?(s=0,r=255&t):t<=223?(s=1,r=31&t):t<=239?(s=2,r=15&t):t<=244&&(s=3,r=7&t),0<a-o-s)for(let e=0;e<s;e+=1)t=i[o+e+1],r=r<<6|63&t;else r=65533,s=a-o;n+=String.fromCodePoint(r),o+=s+1}return n})(t.data):t.data,e=JSON.parse(s)}catch(s){let e=t.data;return void this._ssoLog({method:"jsonParseError",message:e})}var r;e&&e.head&&({seq:t,servcmd:r}=e.head,this._pendingRequests.has(""+t+r)?this._handleRequestResponse(e):this._handlePushMessage(e))}_handleRequestResponse(e){var{seq:t,servcmd:s}=e.head,{int32_error_code:r,str_error_message:i}=(null==e?void 0:e.body)||{},n=(null==(n=null==e?void 0:e.body)?void 0:n.ErrorCode)||r,r=(null==(r=null==e?void 0:e.body)?void 0:r.ErrorInfo)||i,i=""+t+s,{resolve:t,reject:s}=this._pendingRequests.get(i);this._pendingRequests.delete(i),n&&0!==n?(et.emitInnerEvent("error",{errorCode:n,errorInfo:r}),s({errorCode:n,errorInfo:r})):t(e.body)}_handlePushMessage(e){var t=e.head["servcmd"],{NeedAck:s,SessionData:r}=e.body;1===s&&this._sendAck(r),et.emitInnerEvent(t,e)}_checkPendingRequestsAndResend(){var e;Lt.debug("_checkPendingRequestsAndResend",` reConnectFlag:${this._isReconnecting} promiseMap.size:`+this._pendingRequests.size),null!=(e=this._pendingRequests)&&e.forEach((e,t)=>{var{uplinkData:s,canResend:r,resolve:i,reject:n,timeout:o}=e;if(r){this._pendingRequests.set(t,{resolve:i,reject:n,timestamp:Date.now(),uplinkData:s,timeout:o,canResend:r});let e=this._isBinarySupported?mt(s).buffer:s;null!=(i=this._socketAdapter)&&i.send(e)}else this._pendingRequests.delete(t)})}_onConnect(e){var{socketId:e,event:t={}}=e||{},s=(this._connectionId=e,this._connectionEstablishedTime=Date.now(),Date.now()-this._connectionStartTime),s=l+`.onConnect cost:${s} ms. socketID:${e} res:`+JSON.stringify(t);if(this._ssoLog({method:"onConnect",message:s}),this._checkPendingRequestsAndResend(),this._sendHeartbeatIfReady(),this._isReconnecting){l;this._ssoLog({method:"reconnectSuccess",message:"Channel.reconnect success"}),et.emitInnerEvent(Tt.RECONNECTED),this._isReconnecting=!1}this._resetReconnectDelay(),this._handleConnectStateChange({state:wt,shouldEmitEvent:!0,shouldAttemptReconnect:!1})}_sendAck(e){e=It({servcmd:"openim.ws_msg_push_ack",data:{SessionData:e}});this.sendPacket(e)}_executeScheduledTaskIfReady(){return I(this,void 0,void 0,function*(){this._clearTimeoutRequest(),this._sendHeartbeatIfReady()})}_canSendHeartbeat(){var e;return(null==(e=this._socketAdapter)?void 0:e.isConnected())&&Date.now()>=this._nextHeartbeatAt&&!this._isHeartbeatInProgress}_sendHeartbeat(){return I(this,void 0,void 0,function*(){var e,t=It({servcmd:"heartbeat.alive",data:{}});try{let e=""+t.head.seq+t.head.servcmd;yield this.sendPacket(t,{requestId:e,timeout:3e3})}catch(t){var s=null==(e=c.get("netWorkMonitor"))?void 0:e.isNetWorkOnline,s=l+`.sendHeartbeat failed. isNetWorkOnline:${s} error: `+t;this._ssoLog({method:"sendHeartbeatError",message:s}),this._handleConnectStateChange({state:Ut,shouldEmitEvent:!0,shouldAttemptReconnect:!0})}})}_sendHeartbeatIfReady(){return I(this,void 0,void 0,function*(){this._canSendHeartbeat()&&(this._isHeartbeatInProgress=!0,yield this._sendHeartbeat(),this._isHeartbeatInProgress=!1)})}_updateHeartbeatTime(){this._nextHeartbeatAt=ce?Date.now()+5e3:Date.now()+1e4}_handleNetworkStatusChange(e){var t=l+".networkStatusChange "+JSON.stringify(e),{isNetworkOnline:t,networkType:e}=(this._ssoLog({method:"networkStatusChange",message:t}),e);t&&"none"!==e?this._handleConnectStateChange({state:wt,shouldEmitEvent:!1,shouldAttemptReconnect:!0,reason:kt}):this._handleConnectStateChange({state:Ut,shouldEmitEvent:!1,shouldAttemptReconnect:!0,reason:kt})}isPrivateNetWork(){var e=c.get("instance")||{};return e.proxyServer&&!e.fileDownloadProxy}_handleConnectStateChange(e){var{state:e,shouldAttemptReconnect:t,shouldEmitEvent:s,reason:r}=e,r=l+`._handleConnectStateChange currentConnectState: ${this._currentConnectState} shouldAttemptReconnect: ${t} shouldEmitEvent: ${s} reason: `+r;this._currentConnectState!==e&&(this._ssoLog({method:"handleConnectStateChange",message:r}),s&&(Lt.info("_handleConnectStateChange",` from ${this._currentConnectState} to `+e),et.emitOuterEvent("netStateChange",{name:"netStateChange",data:{state:e}}),(this._currentConnectState=e)===Ut)&&et.emitInnerEvent(Tt.SOCKET_DISCONNECTED),t)&&(this._resetReconnectDelay(),_t.addTask({id:Gt,intervalMs:this._intendedDelay,callback:this._scheduleReconnectWithBackoff,context:this}))}_handleActivityStatusChange(e){var t=null==(t=null==(t=this._socketAdapter)?void 0:t._ws)?void 0:t.readyState,e=l+`.activityStatusChange ${JSON.stringify(e)} readyState: `+t;this._ssoLog({method:"activityStatusChange",message:e}),3===t&&this._handleConnectStateChange({state:Ut,shouldEmitEvent:!0,shouldAttemptReconnect:!0,reason:"activity_status_change"})}_resetReconnectDelay(){var e;Lt.debug(l+"._resetReconnectDelay"),_t.removeTask(Gt),null!=(e=c.get("activityMonitor"))&&e.isActive;this._intendedDelay=1e3}_scheduleReconnectWithBackoff(){var e=null==(e=c.get("activityMonitor"))?void 0:e.isActive,e=(this._intendedDelay=e?Math.min(5e3,Math.max(1e3,1.5*this._intendedDelay)):Math.min(3e5,Math.max(1e3,1.5*this._intendedDelay)),(new Date).toTimeString().slice(0,8)),e=l+`.scheduleReconnectWithBackoff timeStr: ${e} intendedDelay: `+this._intendedDelay;Lt.debug(e),this.reconnect(),_t.updateTaskInterval(Gt,this._intendedDelay)}_ssoLog(e){var{method:e,message:t}=e;Lt.info(e,t)}_diagnose(){this.isPrivateNetWork()||(this._lastDiagnoseAt=Date.now(),function(t){I(this,void 0,void 0,function*(){var e=t.split("/")[2];if(e.startsWith("ws")){e=`https://${e}/v3/netcheck/getconninfo?${t.slice(t.indexOf("info?")+5)}&reqtime=`+Date.now();try{yield Be({method:"GET",url:e,data:{}})}catch(e){Lt.warn("diagnoseBySSO","diagnoseBySSO failed. error:"+e.message)}}})}(this._url),function(t){I(this,void 0,void 0,function*(){var e=`https://boce-cdn.my-imcloud.com/v3/netcheck/getconninfo?${t.slice(t.indexOf("info?")+5)}&reqtime=`+Date.now();try{yield Be({method:"GET",url:e,data:{}})}catch(e){Lt.warn("diagnoseByCDN', 'diagnoseByCDN failed. error:"+e.message)}})}(this._url),this._beforeSendInterceptors=[])}_clearTimeoutRequest(){for(var[e,t]of this._pendingRequests.entries()){var{reject:t,timestamp:s,timeout:r}=t;Date.now()-s>=r&&(this._pendingRequests.delete(e),3e4<=Date.now()-this._lastDiagnoseAt&&this._diagnose(),t({errorCode:2801,errorInfo:"NETWORK_TIMEOUT",data:{requestId:e}}))}}_updateIsBinarySupported(){var e;(null!=(e=c.get("instance"))&&e.devMode||(e=xe(),le)||se&&"windows"===e||ce)&&(this._isBinarySupported=!1)}_isCompressedData(e){e=new Uint8Array(e);return 67===e[0]&&79===e[1]&&77===e[2]&&80===e[3]}};let k={init:function(e){c.set("instance",e),Vt.init()},destroy:function(){Vt.dispose(),c.clear(),_t.dispose()},notificationCenter:et,channel:Vt,store:c,ssoLog:Lt,utils:t,common:n,constants:ee},Bt=e=>"function"==typeof e;function jt(t,s,r){let i=r||[];var e,n;return!(!t||!s)&&(e=Object.keys(t).filter(e=>!i.includes(e)),n=Object.keys(s).filter(e=>!i.includes(e)),e.length===n.length)&&e.every(e=>!!s.hasOwnProperty(e)&&("object"==typeof t[e]&&null!==t[e]?jt(t[e],s[e],r):t[e]===s[e]))}(S=gr=gr||{}).SDK_READY="sdkStateReady",S.SDK_NOT_READY="sdkStateNotReady",S.SDK_DESTROY="sdkDestroy",S.MESSAGE_RECEIVED="onMessageReceived",S.ROOM_CUSTOM_DATA_RECEIVED="onRoomCustomDataReceived",S.MESSAGE_MODIFIED="onMessageModified",S.MESSAGE_REVOKED="onMessageRevoked",S.MESSAGE_READ_BY_PEER="onMessageReadByPeer",S.MESSAGE_READ_RECEIPT_RECEIVED="onMessageReadReceiptReceived",S.MESSAGE_EXTENSIONS_UPDATED="onMessageExtensionsUpdated",S.MESSAGE_EXTENSIONS_DELETED="onMessageExtensionsDeleted",S.MESSAGE_REACTIONS_UPDATED="onMessageReactionsUpdated",S.CONVERSATION_LIST_UPDATED="onConversationListUpdated",S.TOTAL_UNREAD_MESSAGE_COUNT_UPDATED="onTotalUnreadMessageCountUpdated",S.CONVERSATION_GROUP_LIST_UPDATED="onConversationGroupListUpdated",S.CONVERSATION_IN_GROUP_UPDATED="onConversationInGroupUpdated",S.GROUP_LIST_UPDATED="onGroupListUpdated",S.GROUP_ATTRIBUTES_UPDATED="groupAttributesUpdated",S.GROUP_COUNTER_UPDATED="onGroupCounterUpdated",S.TOPIC_CREATED="onTopicCreated",S.TOPIC_DELETED="onTopicDeleted",S.TOPIC_UPDATED="onTopicUpdated",S.PROFILE_UPDATED="onProfileUpdated",S.USER_STATUS_UPDATED="onUserStatusUpdated",S.BLACKLIST_UPDATED="blacklistUpdated",S.FRIEND_LIST_UPDATED="onFriendListUpdated",S.FRIEND_GROUP_LIST_UPDATED="onFriendGroupListUpdated",S.FRIEND_APPLICATION_LIST_UPDATED="onFriendApplicationListUpdated",S.MY_FOLLOWERS_LIST_UPDATED="onMyFollowersListUpdated",S.MY_FOLLOWING_LIST_UPDATED="onMyFollowingListUpdated",S.MUTUAL_FOLLOWERS_LIST_UPDATED="onMutualFollowersListUpdated",S.KICKED_OUT="kickedOut",S.ERROR="error",S.NET_STATE_CHANGE="netStateChange",S.ALL_RECEIVE_MESSAGE_OPT_UPDATED="onAllReceiveMessageOptUpdated",S.SERVER_CONFIG_UPDATED="onServerConfigUpdated",S.PINNED_GROUP_MESSAGE_UPDATED="onPinnedGroupMessageUpdated";var Kt=gr;(m=L=L||{}).LOGOUT="logout",m.DESTROY="destroy",m.CLOUD_CONFIG_UPDATE="cloud_config_update",m.PROFILE_UPDATE="profile_updated",m.ERROR="error",m.RECONNECTED="reconnected",m.FORCE_OFFLINE="im_open_status.stat_forceoffline",m.COMMERCIAL_CONFIG_PUSH="im_sdk_config_mgr.push_imsdk_purchase_bitsv2",m.OVERLOAD_PUSH="OverLoadPush.notify2",m.NEW_MESSAGE="new_message",m.MESSAGE_PUSH="im_open_push.msg_push",m.MESSAGE_DELETED="message_deleted",m.MESSAGE_REVOKED="message_revoked",m.MESSAGE_MODIFIED="message_modified",m.SOCKET_DISCONNECTED="socket_disconnected",m.CONVERSATION_UPDATED="conversation_updated",m.TOPIC_MESSAGE_DELETED="topic_message_deleted",m.TOPIC_MESSAGE_REVOKED="topic_message_revoked",m.TOPIC_MESSAGE_MODIFIED="topic_message_modified",m.TOPIC_NEW_MESSAGE="topic_new_message",m.QUALITY_STAT="quality_stat",m.SYNC_CONVERSATION_LIST="sync_conversation_list";var Ht,Wt,d=L,Yt=((t=hr=hr||{}).NEW_INVITATION_RECEIVED="newInvitationReceived",t.INVITEE_ACCEPTED="ts_invitee_accepted",t.INVITEE_REJECTED="ts_invitee_rejected",t.INVITATION_CANCELLED="ts_invitation_cancelled",t.INVITATION_TIMEOUT="ts_invitation_timeout",t.INVITATION_MODIFIED="ts_invitation_modified",hr);let $t=Object.assign({},{KICKED_OUT_MULT_ACCOUNT:"multipleAccount",KICKED_OUT_MULT_DEVICE:"multipleDevice",KICKED_OUT_USERSIG_EXPIRED:"userSigExpired",KICKED_OUT_REST_API:"REST_API_Kick"}),zt={MSG_TEXT:"TIMTextElem",MSG_IMAGE:"TIMImageElem",MSG_AUDIO:"TIMSoundElem",MSG_FILE:"TIMFileElem",MSG_FACE:"TIMFaceElem",MSG_VIDEO:"TIMVideoFileElem",MSG_LOCATION:"TIMLocationElem",MSG_GRP_TIP:"TIMGroupTipElem",MSG_GRP_SYS_NOTICE:"TIMGroupSystemNoticeElem",MSG_CUSTOM:"TIMCustomElem",MSG_MERGER:"TIMRelayElem"},Jt=((n=Ht=Ht||{}).UNSENT="unSend",n.SUCCESS="success",n.FAIL="fail",{modify:d.MESSAGE_MODIFIED,delete:d.MESSAGE_DELETED,revoke:d.MESSAGE_REVOKED}),Qt=((S=Wt=Wt||{})[S.FORWARD=0]="FORWARD",S[S.BACKWARD=1]="BACKWARD",Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},zt),{MSG_PRIORITY_HIGH:"High",MSG_PRIORITY_NORMAL:"Normal",MSG_PRIORITY_LOW:"Low",MSG_PRIORITY_LOWEST:"Lowest"}),{RECEIVE_WITH_OFFLINE_PUSH_EXCEPT_AT:"AcceptNotNotifyExceptAt",NOT_RECEIVE_OFFLINE_PUSH_EXCEPT_AT:"AcceptNotNotifyExceptAt",NOT_RECEIVE_MSG_EXCEPT_AT:"NotReceiveMsgExceptAt",MSG_AT_ALL:"__kImSDK_MesssageAtALL__"}),{MSG_REMIND_ACPT_AND_NOTE:"AcceptAndNotify",MSG_REMIND_ACPT_NOT_NOTE:"AcceptNotNotify",MSG_REMIND_DISCARD:"Discard"}),{MessageStatus:Ht,Direction:Wt})),Xt={[Jt.modify]:d.TOPIC_MESSAGE_MODIFIED,[Jt.delete]:d.TOPIC_MESSAGE_DELETED,[Jt.revoke]:d.TOPIC_MESSAGE_REVOKED},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"},es=Object.assign({},Zt),ts={CONV_C2C:"C2C",CONV_GROUP:"GROUP",CONV_TOPIC:"TOPIC",CONV_SYSTEM:"@TIM#SYSTEM"},ss=Object.assign(Object.assign(Object.assign(Object.assign({},ts),{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"}),rs=Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},{SNS_TYPE_NO_RELATION:"CheckResult_Type_NoRelation",SNS_TYPE_A_WITH_B:"CheckResult_Type_AWithB",SNS_TYPE_B_WITH_A:"CheckResult_Type_BWithA",SNS_TYPE_BOTH_WAY:"CheckResult_Type_BothWay"}),{ALLOW_TYPE_ALLOW_ANY:"AllowType_Type_AllowAny",ALLOW_TYPE_NEED_CONFIRM:"AllowType_Type_NeedConfirm",ALLOW_TYPE_DENY_ANY:"AllowType_Type_DenyAny"}),{SNS_ADD_TYPE_SINGLE:"Add_Type_Single",SNS_ADD_TYPE_BOTH:"Add_Type_Both"}),{SNS_DELETE_TYPE_SINGLE:"Delete_Type_Single",SNS_DELETE_TYPE_BOTH:"Delete_Type_Both"}),{SNS_APPLICATION_TYPE_BOTH:"Pendency_Type_Both",SNS_APPLICATION_SENT_TO_ME:"Pendency_Type_ComeIn",SNS_APPLICATION_SENT_BY_ME:"Pendency_Type_SendOut",SNS_APPLICATION_AGREE:"Response_Action_Agree",SNS_APPLICATION_AGREE_AND_ADD:"Response_Action_AgreeAndAdd"}),{SNS_CHECK_TYPE_BOTH:"CheckResult_Type_Both",SNS_CHECK_TYPE_SINGLE:"CheckResult_Type_Single"}),{FORBID_TYPE_NONE:"AdminForbid_Type_None",FORBID_TYPE_SEND_OUT:"AdminForbid_Type_SendOut"}),is={GRP_WORK:"Private",GRP_PUBLIC:"Public",GRP_MEETING:"ChatRoom",GRP_AVCHATROOM:"AVChatRoom",GRP_COMMUNITY:"Community",GRP_ROOM:"Room",GRP_LIVE:"Live"},ns={COMMUNITY:"@TGS#_",TOPIC:"@TOPIC#_"},os={JOINED:1,QUITTED:2,KICKED:3,ADMIN_SET:4,ADMIN_CANCELED:5,GROUP_PROFILE_UPDATED:6,GROUP_MEMBER_PROFILE_UPDATED:7,TOPIC_PROFILE_UPDATED:8},as=Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},is),{GRP_MBR_ROLE_OWNER:"Owner",GRP_MBR_ROLE_ADMIN:"Admin",GRP_MBR_ROLE_MEMBER:"Member",GRP_MBR_ROLE_CUSTOM:"Custom"}),{GRP_TIP_MBR_JOIN:1,GRP_TIP_MBR_QUIT:2,GRP_TIP_MBR_KICKED_OUT:3,GRP_TIP_MBR_SET_ADMIN:4,GRP_TIP_MBR_CANCELED_ADMIN:5,GRP_TIP_GRP_PROFILE_UPDATED:6,GRP_TIP_MBR_PROFILE_UPDATED:7,GRP_TIP_BAN_AVCHATROOM_MEMBER:10,GRP_TIP_UNBAN_AVCHATROOM_MEMBER:11}),{JOIN_OPTIONS_FREE_ACCESS:"FreeAccess",JOIN_OPTIONS_NEED_PERMISSION:"NeedPermission",JOIN_OPTIONS_DISABLE_APPLY:"DisableApply",JOIN_STATUS_SUCCESS:"JoinedSuccess",JOIN_STATUS_ALREADY_IN_GROUP:"AlreadyInGroup",JOIN_STATUS_WAIT_APPROVAL:"WaitAdminApproval"}),{INVITE_OPTIONS_DISABLE_INVITE:"DisableInvite",INVITE_OPTIONS_NEED_PERMISSION:"NeedPermission",INVITE_OPTIONS_FREE_ACCESS:"FreeAccess"}),{GRP_PROFILE_OWNER_ID:"ownerID",GRP_PROFILE_CREATE_TIME:"createTime",GRP_PROFILE_LAST_INFO_TIME:"lastInfoTime",GRP_PROFILE_MEMBER_NUM:"memberNum",GRP_PROFILE_MAX_MEMBER_NUM:"maxMemberNum",GRP_PROFILE_JOIN_OPTION:"joinOption",GRP_PROFILE_INVITE_OPTION:"inviteOption",GRP_PROFILE_INTRODUCTION:"introduction",GRP_PROFILE_NOTIFICATION:"notification",GRP_PROFILE_MUTE_ALL_MBRS:"muteAllMembers"}),{GROUP_ID_PREFIX:ns,GROUP_TIPS_OPERATION_TYPE:os}),C=Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},$t),Qt),es),ss),rs),as),{IOS_OFFLINE_PUSH_NO_SOUND:"push.no_sound",IOS_OFFLINE_PUSH_DEFAULT_SOUND:"default"}),{NET_STATE_CONNECTING:"connecting",NET_STATE_DISCONNECTED:"disconnected"}),ls={NO_SDKAPPID:2e3,NO_TINYID:2022,NO_A2KEY:2023,USER_NOT_LOGGED_IN:2024,REPEAT_LOGIN:2025,MSG_SEND_FAIL:2100,MSG_SEND_FAIL_NOT_IN_AV:2101,MSG_SEND_GRP_WITH_TOPIC_FAIL:2115,MSG_INSTANCE_REQUIRED:2105,MSG_INVALID_CONV_TYPE:2106,MSG_REVOKE_FAIL:2110,MSG_DELETE_FAIL:2111,MSG_UNREAD_ALL_FAIL:2112,READ_RECEIPT_MSG_LIST_EMPTY:2114,CANNOT_DELETE_GRP_SYSTEM_NOTICE:2116,NOT_MY_FRIEND:2700,NETWORK_ERROR:2800,NETWORK_TIMEOUT:2801,NO_NETWORK:2805,UNCAUGHT_ERROR:2903,INVALID_OPERATION:2905,SDK_IS_NOT_READY:2999,LOGGING_IN:3e3,LOGIN_FAILED:3001,KICKED_OUT_MULT_DEVICE:3002,KICKED_OUT_MULT_ACCOUNT:3003,KICKED_OUT_USERSIG_EXPIRED:3004,LOGGED_OUT:3005,KICKED_OUT_REST_API:3006,NO_USE:3122,OPTIONS_IS_EMPTY:3153,MSG_A2KEY_EXPIRED:20002,ACCOUNT_A2KEY_EXPIRED:70001,HELLO_ANSWER_KICKED_OUT:1002,OPEN_SERVICE_OVERLOAD_ERROR:60022},us={BASIC:"1",STANDARD:"2",PROFESSIONAL:"3"},h={SYNC_SERVER_INFO_AFTER_RE_ONLINE:"sync-server-info-after-re-online",SYNC_SERVER_INFO_AFTER_LOGIN:"sync-server-info-after-login",RECEIVE_C2C_NEW_MESSAGE:"receive-c2c-new-message",RECEIVE_GROUP_NEW_MESSAGE:"receive-group-new-message",RECEIVE_GROUP_TIPS_NOTIFICATION:"receive-group-tips-notification"},o={USER_STATUS_UPDATE:"user-status-update",CONVERSATION_RECOVER:"conversation-recover",HISTORY_MESSAGE_RECOVER:"history-message-recover",BLACKLIST_RECOVER:"blacklist-recover",FRIEND_RECOVER:"friend-recover",GROUP_ATTRIBUTE_CACHE_CLEAR:"group-attribute-cache-clear",UNREAD_MESSAGE_RECOVER:"unread-message-recover",HANDLE_NEW_MESSAGE:"handle-new-message",HANDLE_CONVERSATION_PROFILE_UPDATED:"handle-conversation-profile-updated",COMMERCIAL_CONFIG_UPDATE:"commercial-config-update",UNREAD_MESSAGE_SYNC:"unread-message-sync",FRIEND_AND_BLACKLIST_SYNC:"friend-and-blacklist-sync",SIGNALING_MESSAGE_RECOVER:"signaling-message-recover",GROUP_LIST_SYNC:"group-list-sync",CONVERSATION_LIST_SYNC:"conversation-list-sync",USER_PROFILE_SYNC:"user-profile-sync",CONVERSATION_UPDATE_AFTER_UNREAD_SYNC_FINISHED:"conversation-update-after-unread-sync-finished",CONVERSATION_UPDATE_AFTER_GROUP_LIST_SYNC_FINISHED:"conversation-update-after-group-list-sync-finished",HANDLE_C2C_NEW_MESSAGE:"handle-c2c-new-message",HANDLE_GROUP_NEW_MESSAGE:"handle-group-new-message",CREATE_OR_UPDATE_CONVERSATION_BY_RECEIVE_NEW_MESSAGE:"create-or-update-conversation-by-receive-new-message",HANDLE_GROUP_TIPS_FROM_SYNC_UNREAD:"handle-group-tips-from-sync-unread",HANDLE_C2C_REVOKED_MESSAGE_FROM_SYNC_UNREAD:"handle-c2c-revoked-message-from-sync-unread",GROUP_REVOKED_NOTICE_RECOVER:"group-revoked-notice-recover",CLOUD_CONFIG_SYNC:"cloud-config-sync",UPDATE_GROUP_NEXT_SEQUENCE:"update-group-next-sequence",EMIT_C2C_MESSAGE_EVENT:"emit-c2c-message-event",EMIT_GROUP_MESSAGE_EVENT:"emit-group-message-event",CONVERSATION_GROUP_LIST_SYNC:"conversation-group-list-sync",CONVERSATION_GROUP_UPDATE:"conversation-group-update",UPDATE_TOPIC_AFTER_UNREAD_SYNC_FINISHED:"update-topic-after-unread-sync-finished",UPDATE_TOPIC_BY_RECEIVE_NEW_MESSAGE:"update-topic-by-received-new-message",TOPIC_REQUEST_INFO_RESET:"topic-request-info-reset",QUALITY_REPORT:"quality-report",GROUP_TIPS_RECOVER:"group-tips-recover",HANDLE_GROUP_TIPS_NOTIFICATION:"handle-group-tips-notification"},cs={[h.SYNC_SERVER_INFO_AFTER_RE_ONLINE]:[{stepId:o.USER_STATUS_UPDATE},{stepId:o.GROUP_ATTRIBUTE_CACHE_CLEAR},{stepId:o.UNREAD_MESSAGE_SYNC},{stepId:o.CONVERSATION_RECOVER},{stepId:o.HISTORY_MESSAGE_RECOVER,dependency:o.CONVERSATION_RECOVER},{stepId:o.BLACKLIST_RECOVER},{stepId:o.FRIEND_RECOVER},{stepId:o.GROUP_REVOKED_NOTICE_RECOVER,dependency:o.HISTORY_MESSAGE_RECOVER},{stepId:o.GROUP_TIPS_RECOVER,dependency:o.HISTORY_MESSAGE_RECOVER},{stepId:o.TOPIC_REQUEST_INFO_RESET},{stepId:o.HANDLE_C2C_REVOKED_MESSAGE_FROM_SYNC_UNREAD,dependency:o.UNREAD_MESSAGE_SYNC},{stepId:o.HANDLE_GROUP_TIPS_FROM_SYNC_UNREAD,dependency:o.UNREAD_MESSAGE_SYNC},{stepId:o.CONVERSATION_UPDATE_AFTER_UNREAD_SYNC_FINISHED,dependency:[o.UNREAD_MESSAGE_SYNC,o.CONVERSATION_RECOVER]},{stepId:o.EMIT_C2C_MESSAGE_EVENT,dependency:[o.UNREAD_MESSAGE_SYNC,o.CONVERSATION_UPDATE_AFTER_UNREAD_SYNC_FINISHED],skipIfDependencyMissing:!1}],[h.SYNC_SERVER_INFO_AFTER_LOGIN]:[{stepId:o.COMMERCIAL_CONFIG_UPDATE},{stepId:o.CLOUD_CONFIG_SYNC},{stepId:o.USER_PROFILE_SYNC},{stepId:o.UNREAD_MESSAGE_SYNC},{stepId:o.FRIEND_AND_BLACKLIST_SYNC},{stepId:o.GROUP_LIST_SYNC},{stepId:o.CONVERSATION_LIST_SYNC},{stepId:o.SIGNALING_MESSAGE_RECOVER,dependency:o.UNREAD_MESSAGE_SYNC},{stepId:o.UPDATE_TOPIC_AFTER_UNREAD_SYNC_FINISHED,dependency:[o.UNREAD_MESSAGE_SYNC]},{stepId:o.CONVERSATION_UPDATE_AFTER_UNREAD_SYNC_FINISHED,dependency:[o.UNREAD_MESSAGE_SYNC,o.CONVERSATION_LIST_SYNC]},{stepId:o.CONVERSATION_UPDATE_AFTER_GROUP_LIST_SYNC_FINISHED,dependency:[o.GROUP_LIST_SYNC,o.CONVERSATION_LIST_SYNC]},{stepId:o.CONVERSATION_GROUP_LIST_SYNC},{stepId:o.CONVERSATION_GROUP_UPDATE,dependency:[o.CONVERSATION_LIST_SYNC,o.CONVERSATION_GROUP_LIST_SYNC]},{stepId:o.QUALITY_REPORT}],[h.RECEIVE_C2C_NEW_MESSAGE]:[{stepId:o.HANDLE_C2C_NEW_MESSAGE},{stepId:o.UNREAD_MESSAGE_SYNC},{stepId:o.CREATE_OR_UPDATE_CONVERSATION_BY_RECEIVE_NEW_MESSAGE,dependency:o.HANDLE_C2C_NEW_MESSAGE},{stepId:o.EMIT_C2C_MESSAGE_EVENT,dependency:[o.HANDLE_C2C_NEW_MESSAGE,o.CREATE_OR_UPDATE_CONVERSATION_BY_RECEIVE_NEW_MESSAGE],skipIfDependencyMissing:!1},{stepId:o.CONVERSATION_UPDATE_AFTER_UNREAD_SYNC_FINISHED,dependency:[o.UNREAD_MESSAGE_SYNC]}],[h.RECEIVE_GROUP_NEW_MESSAGE]:[{stepId:o.HANDLE_GROUP_NEW_MESSAGE},{stepId:o.CREATE_OR_UPDATE_CONVERSATION_BY_RECEIVE_NEW_MESSAGE,dependency:o.HANDLE_GROUP_NEW_MESSAGE},{stepId:o.UPDATE_GROUP_NEXT_SEQUENCE,dependency:o.HANDLE_GROUP_NEW_MESSAGE},{stepId:o.UPDATE_TOPIC_BY_RECEIVE_NEW_MESSAGE,dependency:o.HANDLE_GROUP_NEW_MESSAGE},{stepId:o.EMIT_GROUP_MESSAGE_EVENT,dependency:[o.HANDLE_GROUP_NEW_MESSAGE,o.CREATE_OR_UPDATE_CONVERSATION_BY_RECEIVE_NEW_MESSAGE],skipIfDependencyMissing:!1}],[h.RECEIVE_GROUP_TIPS_NOTIFICATION]:[{stepId:o.HANDLE_GROUP_TIPS_NOTIFICATION},{stepId:o.CREATE_OR_UPDATE_CONVERSATION_BY_RECEIVE_NEW_MESSAGE,dependency:o.HANDLE_GROUP_TIPS_NOTIFICATION}]},ds={MESSAGE_SEND_SUCCESS_RATE:"messageSendSuccessRate"},hs={TOTAL_COUNT:"sendMessageTotalCount",SUCCESS_COUNT:"sendMessageSuccessCount",FAILED_COUNT:"sendMessageFailedCount",SEND_COST:"sendMessageCost"},gs=["login","getMyProfile","getUserProfile","updateMyProfile","setSelfStatus","getUserStatus","subscribeUserStatus","unsubscribeUserStatus","modifyMessage","deleteGroupMember","dismissGroup","getGroupMemberList","getGroupOnlineMemberCount","joinGroup","markGroupMemberList","quitGroup","searchCloudMessages","searchCloudGroups","searchCloudGroupMembers","searchCloudUsers","getMyFollowingList","getMyFollowersList","getMutualFollowersList","followUser","unfollowUser","getUserFollowInfo","checkFollowType","getFriendProfile","addFriend","deleteFriend","updateFriend","checkFriend","setFriendApplicationRead","createFriendGroup","deleteFriendGroup","addToFriendGroup","removeFromFriendGroup","renameFriendGroup","changeGroupOwner","createGroup","dismissGroup","getGroupList","getGroupOnlineMemberCount","getGroupProfile","searchGroupByID","updateGroupProfile","handleGroupApplication","deleteGroupAttributes","getGroupAttributes","initGroupAttributes","setGroupAttributes","addGroupMember","deleteGroupMember","getGroupMemberList","getGroupMemberProfile","setGroupMemberMuteTime","setGroupMemberNameCard","setGroupMemberRole","deleteMessage","revokeMessage","setMessageExtensions","getMessageExtensions","deleteMessageExtensions","getMessageList","addMessageReaction","removeMessageReaction","clearHistoryMessage","invite","accept","cancel","reject","modifyInvitation","deleteConversation","pinConversation","setMessageRead","setAllMessageRead","getConversationList","getTotalUnreadMessageCount","renameConversationGroup","deleteConversationGroup","markConversation","setConversationCustomData","deleteConversationsFromGroup","addConversationsToGroup","createConversationGroup"];var ps,_s,ms=Object.freeze({__proto__:null,ERROR_CODE:ls,InnerEvent:d,NEED_LOG_API:gs,OuterConstant:C,OuterEvent:Kt,QUALITY_METRICS:ds,SDK_EDITION:us,SDK_INFO:{VERSION:"1.7.3",APPID:537048168},SEND_MESSAGE_STAT:hs,SignalingEvent:Yt,WORKFLOW_DEFINITIONS:cs,WORKFLOW_NAME:h,WORKFLOW_STEP:o});(gr=ps=ps||{})[gr.USER_INITIATED=0]="USER_INITIATED",gr[gr.KICKED_OUT=1]="KICKED_OUT",(m=_s=_s||{})[m.multipleAccount=1]="multipleAccount",m[m.multipleDevice=2]="multipleDevice",m[m.restApi=3]="restApi",(L=y=y||{})[L.multipleDevice=3002]="multipleDevice",L[L.multipleAccount=3003]="multipleAccount",L[L.usersigExpired=70001]="usersigExpired",L[L.restApi=20002]="restApi";let vs={[_s.multipleAccount]:"multipleAccount",[_s.multipleDevice]:"multipleDevice",[_s.restApi]:"REST_API_Kick",[y.multipleAccount]:"multipleAccount",[y.multipleDevice]:"multipleDevice",[y.restApi]:"REST_API_Kick",[y.usersigExpired]:"userSigExpired"},fs="login_online_presence_task",{ERROR:Is,DESTROY:Es,FORCE_OFFLINE:Ss}=d,{KICKED_OUT_MULT_ACCOUNT:Cs,KICKED_OUT_MULT_DEVICE:Ms,KICKED_OUT_REST_API:ys,ACCOUNT_A2KEY_EXPIRED:Os,MSG_A2KEY_EXPIRED:As}=ls;class Ts{init(){var e=k["notificationCenter"];e.subscribeInnerEvent(Ss,this._handleForceOfflineFromServerPush,this),e.subscribeInnerEvent(Is,As,this._handleForceOfflineFromResponse,this),e.subscribeInnerEvent(Is,Os,this._handleForceOfflineFromResponse,this),e.subscribeInnerEvent(Is,Cs,this._handleForceOfflineFromResponse,this),e.subscribeInnerEvent(Is,Ms,this._handleForceOfflineFromResponse,this),e.subscribeInnerEvent(Is,ys,this._handleForceOfflineFromResponse,this),e.subscribeInnerEvent(Es,this._dispose,this)}_handleForceOfflineFromServerPush(e){var{EventArray:e=[]}=(null==e?void 0:e.body)||{};this._extractKickedOutMessages(e).forEach(e=>{var{KickType:e,NewInstInfo:t}=e["KickoutMsgNotify"];this._processKickedOutReasonInfo({kickedOutReasonCode:e,newInstanceInfo:t})})}_extractKickedOutMessages(e){return e.reduce((e,t)=>[...e,...t.C2cNotifyMsgArray||[]],[]).filter(e=>{return this._isKickedOut(null==(e=null==e?void 0:e.KickoutMsgNotify)?void 0:e.KickType)})}_handleForceOfflineFromResponse(e){e=e.errorCode;this._processKickedOutReasonInfo({kickedOutReasonCode:e})}_processKickedOutReasonInfo(r){return I(this,void 0,void 0,function*(){var e=r["kickedOutReasonCode"],{ssoLog:t,utils:{safeStringify:s}}=k;try{this._logKickedOutEvent(r),yield k.login.loginAction.logout(ps.KICKED_OUT)}catch(e){t.debug("_processKickedOutReasonInfo"," fail "+s(e))}finally{k.notificationCenter.emitOuterEvent(Kt.KICKED_OUT,{data:{type:vs[e]},name:Kt.KICKED_OUT}),[_s.restApi,Os,As].includes(e)&&k.channel.reconnect()}})}_logKickedOutEvent(e){var{kickedOutReasonCode:e,newInstanceInfo:t={}}=e,e=`type:${vs[e]} newInstanceInfo: `+JSON.stringify(t);k.ssoLog.warn("kickedOut",e)}_isKickedOut(e){return[_s.multipleAccount,_s.multipleDevice,_s.restApi].includes(e)}_dispose(){var e=k["notificationCenter"];e.unSubscribeInnerEvent(Ss,this._handleForceOfflineFromServerPush,this),e.unSubscribeInnerEvent(Is,Os,this._handleForceOfflineFromResponse,this),e.unSubscribeInnerEvent(Is,As,this._handleForceOfflineFromResponse,this),e.unSubscribeInnerEvent(Is,Cs,this._handleForceOfflineFromResponse,this),e.unSubscribeInnerEvent(Is,Ms,this._handleForceOfflineFromResponse,this),e.unSubscribeInnerEvent(Is,ys,this._handleForceOfflineFromResponse,this),e.unSubscribeInnerEvent(Es,this._dispose,this)}}function Rs(r){return I(this,void 0,void 0,function*(){let e="im_open_status.wslogin",t=k.common.generateProtocolData({servcmd:e,data:{State:"Online",is_web_uniapp:0,InstType:0,CustomInfo:r}}),s=""+t.head.seq+e,d=yield k.channel.sendPacket(t,{timeout:9e4,requestId:s});if(d){let{HelloInterval:e,InstId:t,TinyId:s,TimeStamp:r,CustomStatus:i,PurchaseBits:n,A2Key:o,RichMsgAuthKey:a,ErrorCode:l,ErrorInfo:u,ActionStatus:c}=d;return{helloInterval:e,instanceID:t,tinyID:s,timeStamp:r,customStatus:i,purchaseBits:n,a2Key:o,authKey:a,errorCode:l,errorInfo:u,actionStatus:c}}})}function Ds(t){var s;try{var r=c.getStorage("errorMessage");if(!t||!r)return"";var i=(null==(s=JSON.parse(r))?void 0:s.errorMessage)||{},{isIntl:n=!1,code:o,replacement1:a="",replacement2:l=""}=t;if(!o)return"";var u=n?o+"_en":o+"_cn";let e=i[i[u]?u:o]||"";return e=e&&(a&&(e=e.replace("$replacement1",a)),l)?e.replace("$replacement2",l):e}catch(t){return console.warn("Error parsing stored error messages:",t),""}}class _ extends Error{constructor(e){var{functionName:t="Unknown",code:s,message:r="",data:i="",moreMessage:n=""}=e;let o=r;s&&!r&&(o=Ds(e));r=(s?`${t} failed. error: {"message": ${o}, "code": ${s}}`:`${t} failed. error: {"message": ${o}}`)+" "+n;super(),this.code=s,this.errorCode=s,this.errorMessage=r,this.message=r,this.data=i}}function bs(e,t){if(e&&!0!==(null==(e=k.store.get("login"))?void 0:e.isLoggedIn))throw new _({code:ls.USER_NOT_LOGGED_IN,functionName:t})}function Ns(t,s,r){if(Array.isArray(t))for(let e=0;e<t.length;e++)Ls.call(this,Object.assign(Object.assign({},t[e]),{value:s[e],name:r}));else for(var e in t)Ls.call(this,Object.assign(Object.assign({},t[e]),{value:s[0][e],name:r,key:e}))}function Ls({required:e,rules:r,value:t,allowEmpty:i,name:n,key:o,customValidator:a}){if(void 0===t){if(e)throw new _({functionName:n,message:`[${n}] Missing required params: "${o}"`})}else{let s="";if(!r.some(e=>{return e===Object.prototype.toString.call(t).match(/^\[object (.*)\]$/)[1].toLowerCase()})){for(let t=0;t<r.length;t++){let e=r[t];e=e.replace(e[0],e[0].toUpperCase()),s+=e+"/"}let e=`[${o}] must be type of ${s=s.substring(0,s.length-1)}, received type: ${Reflect.apply(Object.prototype.toString,t,[]).replace(/^\[object\s(\w+)\]$/,"$1").toLowerCase()}.`;throw new _({functionName:n,message:e})}if(!1===i){if(Array.isArray(t)&&(0===t.length||"string"==typeof t[0]&&""===t[0].trim()))throw new _({functionName:n,message:o+" can not be empty."});if("string"==typeof t&&""===t.trim())throw new _({functionName:n,message:o+" can not be empty."})}if(a&&"function"==typeof a){let e=a(t);if(!0!==e)throw new _({functionName:n,message:`[${o}] custom validation failed: `+(e||"Invalid value")})}}}let Ps=[],Gs={},ws={};function Us(e,t){var s;bs(Gs[e],e),Ns(ws[e],t,e),s=e,Ps.forEach(e=>{var{interceptor:e,context:t}=e;e.apply(t,[s])})}function ks(e,t){Ps.push({interceptor:e,context:t})}function Fs(e){var{params:e,auth:t}=e;e&&"object"==typeof e&&Object.assign(ws,e),t&&"object"==typeof t&&Object.assign(Gs,t)}function qs(e){return k.store.get("commercialConfig").get(e)}class g{constructor(){this._handlers=new Map,this._activeWorkflows=new Map,this._stepStartTimes=new Map,this._logHandlers={start:(e,t)=>{var s=Date.now();t?(this._stepStartTimes.set(e+"-"+t,s),k.ssoLog.debug("_executeWorkflowStep",`[Workflow ${e}] Step ${t} started at `+new Date(s).toISOString())):(this._workflowStartTimes.set(e,s),k.ssoLog.debug("_executeWorkflowStep",`[Workflow ${e}] started at `+new Date(s).toISOString()))},success:(s,e)=>{var r=Date.now();if(e){var t=this._stepStartTimes.get(s+"-"+e),t=t?r-t:0;this._stepStartTimes.delete(s+"-"+e),k.ssoLog.debug("_executeWorkflowStep",`[Workflow ${s}] Step ${e} completed successfully at ${new Date(r).toISOString()} (${t}ms)`)}else{let e=this._workflowStartTimes.get(s),t=e?r-e:0;this._workflowStartTimes.delete(s),k.ssoLog.debug("_executeWorkflowStep",`[Workflow ${s}] completed successfully at ${new Date(r).toISOString()} (${t}ms)`)}},error:(s,e,r)=>{var{ssoLog:i,utils:{safeStringify:n}}=k,o=Date.now();if(e){var t=this._stepStartTimes.get(s+"-"+e),t=t?o-t:0;this._stepStartTimes.delete(s+"-"+e),i.error("_executeWorkflowStep",`[Workflow ${s}] Step ${e} failed at ${new Date(o).toISOString()} (${t}ms) `+n(r),{error:r})}else{let e=this._workflowStartTimes.get(s),t=e?o-e:0;this._workflowStartTimes.delete(s),i.error("_executeWorkflowStep",`[Workflow ${s}] failed at ${new Date(o).toISOString()} (${t}ms) `+n(r),{error:r})}}}}static getInstance(){return g._instance||(g._instance=new g),g._instance}static setInstance(e){g._instance=e}init(){this._initializeWorkflows()}registerWorkflowStep(e,t,s,r){var i;this._handlers.has(e)?cs[e].find(e=>e.stepId===t)?(i=this._handlers.get(e)).has(t)||i.set(t,r?s.bind(r):s):k.ssoLog.debug("registerWorkflowStep",`Step '${t}' not defined in workflow '${e}'`):k.ssoLog.debug("registerWorkflowStep",`Workflow '${e}' not defined in core`)}executeWorkflow(o,s){return I(this,void 0,void 0,function*(){if(this._validateWorkflow(o)){k.ssoLog.debug("executeWorkflow",`[Workflow ${o}] Started execution at `+(new Date).toISOString());let e=cs[o],n={cancelled:!1};this._activeWorkflows.set(o,{cancelToken:n});try{let t=new Map,i=(e.forEach(e=>{t.set(e.stepId,e)}),{workflowName:o,pendingSteps:new Set(e.map(e=>e.stepId)),completedSteps:new Set,runningSteps:new Set,stepMap:t,stepResults:{},data:s,cancelToken:n});yield new Promise((t,s)=>{let r=()=>{n.cancelled?t():this._getExecutableSteps({pendingSteps:i.pendingSteps,completedSteps:i.completedSteps,stepMap:i.stepMap,workflowName:o}).filter(e=>!i.runningSteps.has(e)).forEach(e=>{i.completedSteps.has(e)||i.runningSteps.has(e)||this._executeWorkflowStep(e,i,{onComplete:()=>{0===i.pendingSteps.size?t():0===this._getExecutableSteps({pendingSteps:i.pendingSteps,completedSteps:i.completedSteps,stepMap:i.stepMap,workflowName:o}).filter(e=>!i.runningSteps.has(e)).length&&0===i.runningSteps.size&&(k.ssoLog.debug("executeWorkflow",`Workflow ${o} completed with some steps skipped due to dependency failures`),t())},onError:s,onStepComplete:r})})};r()}),k.ssoLog.debug("executeWorkflow",`[Workflow ${o}] Completed execution at `+(new Date).toISOString())}catch(e){k.ssoLog.error("executeWorkflow",`[Workflow ${o}] Failed execution at `+(new Date).toISOString(),{error:e})}finally{this._activeWorkflows.delete(o)}}})}_executeWorkflowStep(a,l,u){return I(this,void 0,void 0,function*(){let{workflowName:n,runningSteps:e,stepMap:s,stepResults:r,data:i}=l;e.add(a),this._logWorkflowExecution(n,a,"start");try{let e=s.get(a),t=null;null!=e&&e.dependency&&(w(e.dependency)?t=r[e.dependency]:Array.isArray(e.dependency)&&(t={},e.dependency.forEach(e=>{t[e]=r[e]})));var o=this._handlers.get(n).get(a);if(o){let e=yield Promise.resolve(o({data:i,result:t}));r[a]=e,this._logWorkflowExecution(n,a,"success")}l.completedSteps.add(a)}catch(e){let t=`[Workflow].${n}.`+a,{errorCode:s,errorInfo:r=t+" failed"}=e||{},i=new _({functionName:t,code:s,message:r});k.ssoLog.error(t,r,{error:i}),this._logWorkflowExecution(n,a,"error",e),u.onError(e)}finally{e.delete(a),l.pendingSteps.delete(a),u.onStepComplete(),u.onComplete()}})}reset(){this._cancelAllWorkflows()}destroy(){this.reset(),this._handlers.clear()}_initializeWorkflows(){Object.keys(cs).forEach(e=>{this._handlers.has(e)||this._handlers.set(e,new Map)})}_cancelWorkFlow(e){var t=this._activeWorkflows.get(e);t&&(t=t["cancelToken"],t.cancelled=!0,this._activeWorkflows.delete(e))}_cancelAllWorkflows(){Object.keys(cs).forEach(e=>{this._cancelWorkFlow(e)})}_validateWorkflow(e){return!!cs[e]&&!!this._handlers.get(e)}_getExecutableSteps(e){let{pendingSteps:t,completedSteps:s,stepMap:r,workflowName:i}=e;return Array.from(t).filter(e=>{var{dependency:t,skipIfDependencyMissing:e=!0}=r.get(e)||{};if(!t)return!0;if(w(t))return this._isStepRegistered({workflowName:i,stepId:t})?s.has(t):!e;if(q(t)){if(0<t.filter(e=>!this._isStepRegistered({workflowName:i,stepId:e})).length&&e)return!1;for(let e of t)if(!s.has(e))return!1;return!0}return!1})}_isStepRegistered(e){var{workflowName:e,stepId:t}=e;return null==(e=this._handlers.get(e))?void 0:e.has(t)}_logWorkflowExecution(e,t,s,r){this._logHandlers[s](e,t)}}let xs=new Map,Vs=({type:e,groupID:t})=>e===C.GRP_COMMUNITY||(""+t).startsWith(ns.COMMUNITY)&&!(""+t).includes(ns.TOPIC),Bs=(e="")=>{e=e.startsWith("GROUP")?e.replace("GROUP",""):e;return e.startsWith(ns.COMMUNITY)&&(""+e).includes(ns.TOPIC)},js="openim",Ks="million_group_open_http_svc";function Hs(s){return I(this,void 0,void 0,function*(){var{servcmd:e,data:t}=Ws(e=s.data)||Ys(e)?function(e){let{servcmd:t,data:s}=e;var r,i,n;return Ys(s)?({servcmd:e,data:r}=e,{GroupId:i=""}=r,[i]=(n=i).split(ns.TOPIC),{servcmd:$s(e),data:Object.assign(Object.assign({},r),{GroupId:i,TopicId:n})}):{servcmd:t=Ws(s)?$s(t):t,data:s}}(s):s,t=k.common.generateProtocolData({servcmd:e,data:t}),e=""+t.head.seq+e;return k.channel.sendPacket(t,{requestId:e})})}function Ws(e){var{Type:e,GroupId:t,GroupIdList:s=[]}=e,t=t||s[0]||"";return Vs({type:e,groupID:t})}function Ys(e){var{GroupId:e=""}=e;return Bs(e)}function $s(e){return e.includes(js)?e:(e=e.split(".")[1],Ks+"."+e)}function p(){var e;return null==(e=k.store.get("login"))?void 0:e.userId}let zs=e=>q(e)||x(e),Js=(s,r,i,n)=>{if(!zs(s)||!zs(r))return 0;let o=0;var a,l=Object.keys(r);for(let e=0,t=l.length;e<t;e++)if(a=l[e],!(G(r[a])||i&&i.includes(a)))if(zs(s[a])&&zs(r[a]))o+=Js(s[a],r[a],i,n);else{if(n&&n.includes(r[a]))continue;s[a]!==r[a]&&(s[a]=r[a],o+=1)}return o},Qs=(e,t)=>{if(G(t))return"";switch(e){case C.MSG_TEXT:return t.text||"";case C.MSG_IMAGE:return"[Image]";case C.MSG_LOCATION:return"[Location]";case C.MSG_AUDIO:return"[Voice]";case C.MSG_VIDEO:return"[Video]";case C.MSG_FILE:return"[File]";case C.MSG_CUSTOM:return"[Custom Messages]";case C.MSG_GRP_TIP:return"[Group Notification]";case C.MSG_GRP_SYS_NOTICE:return"[Group System Message]";case C.MSG_FACE:return"[Animated Sticker]";case C.MSG_MERGER:return"[Chat Record]";default:return""}},Xs=[{cmd:"ws_get_user_status",interval:5,count:20},{cmd:"ws_status_subscribe",interval:5,count:20},{cmd:"ws_status_unsubscribe",interval:5,count:20},{cmd:"get_group_self_member_info",interval:5,count:20},{cmd:"modify_group_base_info",interval:1,count:8},{cmd:"get_pendency",interval:1,count:15},{cmd:"set_group_attr",interval:5,count:10},{cmd:"modify_group_attr",interval:5,count:10},{cmd:"delete_group_attr",interval:5,count:10},{cmd:"clear_group_attr",interval:5,count:10},{cmd:"get_group_attr",interval:5,count:20},{cmd:"update_group_counter",interval:5,count:20},{cmd:"get_group_counter",interval:5,count:20},{cmd:"get_topic",interval:1,count:10},{cmd:"read_all_unread_msg",interval:1,count:1},{cmd:"query",interval:5,count:20}],Zs="im_sdk_config_mgr.fetch_config",er="im_sdk_config_mgr.push_configv2",tr="cloud-config",sr=new class{init(e){this.core=e}};function rr(s){return I(this,void 0,void 0,function*(){var e=(sr.core.store.get("instance")||{})["sdkAppId"],e=sr.core.helper.generateProtocolData({servcmd:Zs,data:{uint32_sdkappid:e,uint64_version:s}}),t=""+e.head.seq+Zs;return sr.core.channel.sendPacket(e,{requestId:t})})}var ir=new class{constructor(){this._core=null,this._expirationTime=0,this._version=0,this._isFetching=!1,this._cmdFrequencyLimitMap=new Map,this._methodCallFrequencyMap=new Map}install(e){var{notificationCenter:e,InnerEvent:t,helper:s,constants:{WORKFLOW_NAME:r,WORKFLOW_STEP:i},channel:n}=this._core=e;e.subscribeInnerEvent(er,this._handlePushedConfig,this),s.registerWorkflowStep(r.SYNC_SERVER_INFO_AFTER_LOGIN,i.CLOUD_CONFIG_SYNC,this._handleLoginSuccess,this),e.subscribeInnerEvent(t.LOGOUT,this._reset,this),e.subscribeInnerEvent(t.DESTROY,this._dispose,this),s.registerExperimentalAPI("getServerConfig",this),this._updateCmdFreqLimitMap(Xs),n.registerBeforeSendInterceptor(this.checkMethodCallOverLimit,this)}getServerConfig(s){return I(this,void 0,void 0,function*(){var e,t={code:0,data:""};return s&&(t.data=(null==(e=this._core.store.get("cloudConfig"))?void 0:e[s])||""),t})}checkMethodCallOverLimit(e){if(this._cmdFrequencyLimitMap.has(e))if(this._methodCallFrequencyMap.has(e)){var{count:t,interval:s}=this._cmdFrequencyLimitMap.get(e),{startTime:r,methodCallCounter:i}=this._methodCallFrequencyMap.get(e);if(Date.now()-r>1e3*s)this._methodCallFrequencyMap.set(e,{startTime:Date.now(),methodCallCounter:1});else if(this._methodCallFrequencyMap.set(e,{startTime:r,methodCallCounter:i+=1}),t<i)throw new this._core.helper.ChatError({code:2996,replacement1:e})}else this._methodCallFrequencyMap.set(e,{startTime:Date.now(),methodCallCounter:1})}_handlePushedConfig(s){return I(this,void 0,void 0,function*(){var{ssoLog:e,utils:{safeStringify:t}}=this._core;e.info("_handlePushedConfig",t(s)),yield this._updateCloudConfig(s)})}_handleLoginSuccess(){return I(this,void 0,void 0,function*(){var e,{ssoLog:t,utils:{safeStringify:s}}=this._core;try{this._canFetch()&&(e=yield rr(this._version),t.info("_fetchCloudConfigIfLogin",s(e)),yield this._updateCloudConfig(e)),this._core.helper.taskScheduler.addTask({id:tr,intervalMs:1e3,callback:this._fetchCloudConfigIfReady,context:this})}catch(e){t.error("_fetchCloudConfigIfLogin",s(e))}})}_fetchCloudConfigIfReady(){return I(this,void 0,void 0,function*(){var{ssoLog:t,utils:{safeStringify:s}}=this._core;if(this._canFetch())try{var e=yield rr(this._version);t.info("_fetchCloudConfigIfReady",s(e)),yield this._updateCloudConfig(e)}catch(e){t.error("_fetchCloudConfigIfReady",s(e))}})}_updateCloudConfig(t){return I(this,void 0,void 0,function*(){var e=this._parseCloudConfig(t);e&&(this._core.store.set("cloudConfig",e),yield this._parseCmdFreqLimit(),this._core.notificationCenter.emitInnerEvent(this._core.InnerEvent.CLOUD_CONFIG_UPDATE,e),this._core.notificationCenter.emitOuterEvent(this._core.OuterEvent.SERVER_CONFIG_UPDATED,{name:this._core.OuterEvent.SERVER_CONFIG_UPDATED,data:{config:e}}))})}_canFetch(){var e=(this._core.store.get("login")||{})["isLoggedIn"];return e&&!this._isFetching&&Date.now()>=this._expirationTime}_parseCloudConfig(e){var{int32_error_code:t,str_json_config:s,uint32_expired_time:r,uint64_version:i}=e;let n=null;if(0===t){if(this._version!==i)try{n=JSON.parse(s),this._version=i}catch(e){}this._expirationTime=Date.now()+1e3*r}else this._expirationTime=void 0===t?Date.now()+36e5:Date.now()+12e4;return n}_parseCmdFreqLimit(){return I(this,void 0,void 0,function*(){var e,t=null==(e=yield this.getServerConfig("cmd_frequency_limit"))?void 0:e.data,s=this._core.utils["isEmpty"];if(!s(t))try{t=JSON.parse(t),this._updateCmdFreqLimitMap(t)}catch(e){console.warn(e)}})}_updateCmdFreqLimitMap(e){e.forEach(e=>{this._cmdFrequencyLimitMap.set(e.cmd,{interval:e.interval,count:e.count})})}_reset(){this._core.helper.taskScheduler.removeTask(tr),this._core.store.clear("cloudConfig"),this._updateCmdFreqLimitMap(Xs),this._methodCallFrequencyMap.clear(),this._expirationTime=0,this._version=0,this._isFetching=!1}_dispose(){var{notificationCenter:e,InnerEvent:t}=this._core;e.unSubscribeInnerEvent(er,this._handlePushedConfig,this),e.unSubscribeInnerEvent(t.LOGOUT,this._reset,this),e.unSubscribeInnerEvent(t.DESTROY,this._dispose,this),this._reset()}};class u{constructor(e=0,t=0){this.high=e,this.low=t}equal(e){return null!==e&&this.low===e.low&&this.high===e.high}toString(){var e=Number(this.high).toString(16);let t=Number(this.low).toString(16);if(t.length<8){let e=8-t.length;for(;e;)t="0"+t,e--}return e+t}}let nr={SEARCH_GRP_SNS:new u(0,Math.pow(2,1)).toString(),AV_HISTORY_MSG:new u(0,Math.pow(2,2)).toString(),GRP_COMMUNITY:new u(0,Math.pow(2,3)).toString(),MSG_TO_SPECIFIED_GRP_MBR:new u(0,Math.pow(2,4)).toString(),AV_MBR_LIST:new u(0,Math.pow(2,6)).toString(),USER_STATUS:new u(0,Math.pow(2,7)).toString(),CONV_MARK:new u(0,Math.pow(2,9)).toString(),CONV_GROUP:new u(0,Math.pow(2,10)).toString(),AV_BAN_MBR:new u(0,Math.pow(2,11)).toString(),MSG_EXT:new u(0,Math.pow(2,13)).toString(),GRP_COUNTER:new u(0,Math.pow(2,15)).toString(),PLUGIN_TRANSLATE:new u(Math.pow(2,6)).toString(),PLUGIN_VOICE_TO_TEXT:new u(Math.pow(2,7)).toString(),PLUGIN_CS:new u(Math.pow(2,8)).toString(),PLUGIN_PUSH:new u(Math.pow(2,9)).toString(),PLUGIN_BOT:new u(Math.pow(2,10)).toString(),MSG_REACTION:new u(Math.pow(2,16)).toString(),FOLLOW:new u(Math.pow(2,20)).toString()},or="CommercialConfig",ar="commercial-config";var lr,ur,cr=new class{constructor(){this._core=null,this._expirationTime=0,this._isFetching=!1,this._featureMap=new Map,this._methodKeyMap=new Map,this._purchaseBits="0"}install(e){var{helper:t,notificationCenter:s,constants:{WORKFLOW_NAME:r,WORKFLOW_STEP:i,InnerEvent:n}}=this._core=e;s.subscribeInnerEvent(n.COMMERCIAL_CONFIG_PUSH,this._handlePushedConfig,this),s.subscribeInnerEvent(n.LOGOUT,this._handleLogout,this),s.subscribeInnerEvent(n.DESTROY,this._dispose,this),t.registerWorkflowStep(r.SYNC_SERVER_INFO_AFTER_LOGIN,i.COMMERCIAL_CONFIG_UPDATE,this._syncCommercialConfig,this),e.helper.registerExperimentalAPI("isCommercialAbilityEnabled",this),e.helper.registerExperimentalAPI("queryCommercialAbility",this)}isCommercialAbilityEnabled(e){return I(this,void 0,void 0,function*(){var s=parseInt(e,10).toString(2),r=s["length"];let i,n=!0;for(let e=r-1,t=0;0<=e;e--,t++)if("1"===s.charAt(e)&&(i=(t<32?new u(0,2**t):new u(2**(t-32),0)).toString(),!this._featureMap.get(i))){n=!1;break}return this._core.ssoLog.debug("isFeatureEnabled",or+`.isFeatureEnabled decimalNumber:${e} key:${i} ret:`+n),{code:0,data:{enabled:n}}})}queryCommercialAbility(){return this._purchaseBits}_fetchAndParseCommercialConfig(){return I(this,void 0,void 0,function*(){let s,{ssoLog:e,helper:r,utils:{safeStringify:t}}=this._core;try{this._isFetching=!0;let e=r.generateProtocolData({servcmd:"im_sdk_config_mgr.fetch_imsdk_purchase_bitsv2",data:{uint32_sdkappid:null==(s=this._core.store.get("instance"))?void 0:s.sdkAppId}}),t=yield this._core.channel.sendPacket(e);null!=t&&t.body&&(this._parseCommercialConfig(t.body),this._core.store.set("commercialConfig",this._methodKeyMap))}catch(s){e.error("_fetchAndParseCommercialConfig",t(s))}finally{this._isFetching=!1}})}_syncCommercialConfig(t){return I(this,void 0,void 0,function*(){var e=((null==t?void 0:t.data)||{})["purchaseBits"];e&&(this._parsePurchaseBits(e),this._core.store.set("commercialConfig",this._methodKeyMap)),this._canFetch()&&(yield this._fetchAndParseCommercialConfig()),this._core.helper.taskScheduler.addTask({id:ar,intervalMs:1e3,callback:this._fetchCommercialConfigIfReady,context:this})})}_canFetch(){var e=null==(e=this._core.store.get("login"))?void 0:e.isLoggedIn,t=Date.now()>=this._expirationTime;return e&&!this._isFetching&&t}_handlePushedConfig(e){null!=e&&e.body&&(this._parseCommercialConfig(e.body),this._core.store.set("commercialConfig",this._methodKeyMap))}_fetchCommercialConfigIfReady(){return I(this,void 0,void 0,function*(){this._canFetch()&&(yield this._fetchAndParseCommercialConfig())})}_parseCommercialConfig(e){var t,s,r,i,n=this._core["ssoLog"];"object"==typeof e&&({int32_error_code:t,str_error_message:s,str_purchase_bits:r,uint32_expired_time:i}=e,0===t?(this._parsePurchaseBits(r),this._expirationTime=Date.now()+1e3*i):void 0===t?(n.warn("_parseCommercialConfig",or+"._parseCommercialConfig failed. Invalid message format:",e),this._expirationTime=Date.now()+36e5):(n.warn("_parseCommercialConfig",or+`._parseCommercialConfig errorCode:${t} errorMessage:`+s),this._expirationTime=Date.now()+12e4))}_isValidPurchaseBits(e){return e&&"string"==typeof e&&1<=e.length&&e.length<=64&&/[01]{1,64}/.test(e)}_parsePurchaseBits(s){var{ssoLog:e,utils:{safeStringify:t}}=this._core;if(this._isValidPurchaseBits(s)){this._purchaseBits=s,this._featureMap.clear(),this._methodKeyMap.clear();var r;for(let e=s.length-1,t=0;0<=e;e--,t++)if(r=(t<32?new u(0,2**t):new u(2**(t-32),0)).toString(),"1"===s[e]){this._featureMap.set(r,!0);let e=this._getKeyByValue(nr,r);e&&this._methodKeyMap.set(e,!0)}else{this._featureMap.set(r,!1);let e=this._getKeyByValue(nr,r);e&&this._methodKeyMap.set(e,!1)}}else e.warn("_parsePurchaseBits",or+".parsePurchaseBits invalid purchases:"+t(s))}_getKeyByValue(e,t){e=Object.entries(e).find(([,e])=>e===t);return e?e[0]:void 0}_handleLogout(){this._reset()}_dispose(){this._reset(),this._core.notificationCenter.unSubscribeInnerEvent(this._core.InnerEvent.COMMERCIAL_CONFIG_PUSH,this._handlePushedConfig,this),this._core.notificationCenter.unSubscribeInnerEvent(this._core.InnerEvent.LOGOUT,this._reset,this),this._core.notificationCenter.unSubscribeInnerEvent(this._core.InnerEvent.DESTROY,this._dispose,this)}_reset(){this._core.helper.taskScheduler.removeTask(ar),this._core.store.set("commercialConfig",{}),this._expirationTime=0,this._isFetching=!1,this._featureMap.clear(),this._purchaseBits="0"}},dr=new class{constructor(){this._core=null,this._serverOverloadInfoMap=new Map}install(e){this._core=e;var{notificationCenter:e,InnerEvent:t,channel:s}=this._core;e.subscribeInnerEvent(t.OVERLOAD_PUSH,this._handleOverLoadPush,this),e.subscribeInnerEvent(t.LOGOUT,this._reset,this),e.subscribeInnerEvent(t.DESTROY,this._dispose,this),s.registerBeforeSendInterceptor(this.checkServerOverload,this)}checkServerOverload(e){if(this._serverOverloadInfoMap.has(e)){var{overloadStartTimestamp:t,delaySeconds:s}=this._serverOverloadInfoMap.get(e);if(Date.now()-t<=1e3*s)throw new this._core.helper.ChatError({functionName:e,message:"service is busy, please try again later"});this._serverOverloadInfoMap.delete(e)}}_handleOverLoadPush(e){var{OverLoadServCmd:e,DelaySecs:t}=e;this._serverOverloadInfoMap.set(e,{overloadStartTimestamp:Date.now(),delaySeconds:t})}_reset(){this._serverOverloadInfoMap.clear()}_dispose(){this._reset();var{notificationCenter:e,InnerEvent:t}=this._core;e.unSubscribeInnerEvent(t.OVERLOAD_PUSH,this._handleOverLoadPush,this),e.unSubscribeInnerEvent(t.LOGOUT,this._reset,this),e.unSubscribeInnerEvent(t.DESTROY,this._dispose,this)}},t=new class{constructor(){this.name="ConfigCenter"}install(e){sr.init(e),ir.install(e),cr.install(e),dr.install(e)}},hr=new class{constructor(){this.name="ErrorMessage",this._core=null}install(e){return I(this,void 0,void 0,function*(){if(this._core=e,this._canFetch()){let e=yield this._fetchErrorMessage();var t;e&&(t=this._parseResponse(e),this._saveErrorMessage(t))}})}_canFetch(){var e=this._core.store.getStorage("errorMessage");return!e||this._isExpired(e)}_saveErrorMessage(e){this._core.store.setStorage("errorMessage",{errorMessage:e,errorMessageSavedTime:(new Date).getTime()})}_fetchErrorMessage(){return I(this,void 0,void 0,function*(){try{return yield this._core.helper.httpRequest({method:"GET",url:"https://web.sdk.qcloud.com/im/download/error-message/v3/0.0.6/tim-error-message.txt"})}catch(e){console.error(e)}})}_isExpired(e){return!e||(e=e["errorMessageSavedTime"],e&&6048e5<=(new Date).getTime()-e)}_parseResponse(e){if("string"==typeof e){var s=e.split(";\n"),r={},i=new RegExp(/'/g);for(let t=0;t<s.length;t++){var n=s[t].indexOf(":"),o=s[t].slice(0,n);let e=s[t].slice(n+1);o.startsWith("//")||""!==e&&(e=e.replace(i,""),r[o]=e)}return r}}};(n=lr=lr||{})[n.START_SYNC=0]="START_SYNC",n[n.SYNCING=1]="SYNCING",n[n.SYNC_COMPLETE=2]="SYNC_COMPLETE",(S=ur=ur||{})[S.LOGIN_SUCCESS=0]="LOGIN_SUCCESS",S[S.NEW_MESSAGE_RECEIVED=1]="NEW_MESSAGE_RECEIVED";var gr=new class{constructor(){this.name="UnreadMessageSynchronizer",this._unreadDBMessageMap=new Map,this._cookie=""}install(e){var t=(this._core=e)["constants"];e.helper.registerWorkflowStep(t.WORKFLOW_NAME.SYNC_SERVER_INFO_AFTER_RE_ONLINE,t.WORKFLOW_STEP.UNREAD_MESSAGE_SYNC,this._syncUnreadDBMessageAfterReOnline,this),e.helper.registerWorkflowStep(t.WORKFLOW_NAME.RECEIVE_C2C_NEW_MESSAGE,t.WORKFLOW_STEP.UNREAD_MESSAGE_SYNC,this._syncUnreadDBMessageAfterNewMessageReceived,this),e.helper.registerWorkflowStep(t.WORKFLOW_NAME.SYNC_SERVER_INFO_AFTER_LOGIN,t.WORKFLOW_STEP.UNREAD_MESSAGE_SYNC,this._syncUnreadDBMessageAfterLogin,this),e.notificationCenter.subscribeInnerEvent(e.InnerEvent.LOGOUT,this._reset,this),e.notificationCenter.subscribeInnerEvent(e.InnerEvent.DESTROY,this._dispose,this)}_syncUnreadMessage(t){return I(this,void 0,void 0,function*(){let{isAfterReOnline:o=!1,isAfterNewMessageReceived:a=!1,isAfterLogin:e=!1}=t||{},l=lr.START_SYNC;for(var u=[],c=[],d=[],h=[];this._canContinueSync({cookie:this._cookie,syncFlag:l});){let e=yield this._fetchUnreadDBMessage({cookie:this._cookie,syncFlag:l,syncTriggerEvent:a?ur.NEW_MESSAGE_RECEIVED:ur.LOGIN_SUCCESS});if(!e)break;let{unreadMessageList:t=[],revokedMessageList:s=[],overflowUnreadCountList:r,unreadCountList:i,groupTipList:n}=e;if(this._cookie=(null==e?void 0:e.cookie)||"",l=null==e?void 0:e.syncFlag,this._parseAndSaveUnreadMessageList(t),d.push(...s),this._updateConversationUnreadOptions({unreadCountList:i,overflowUnreadCountList:r,conversationUpdateFieldList:u}),Array.isArray(n)&&c.push(...n),o){let e=this._handleNewMessageList(t)["messages"];h.push(...e)}}return o?{conversationUpdateFieldList:u,revokedMessageList:d,unreadMessageMap:this._unreadDBMessageMap,groupTipList:c,messages:h}:{conversationUpdateFieldList:u,isInstantMessage:!e,isUnreadC2CMessage:!0,revokedMessageList:d,unreadMessageMap:this._unreadDBMessageMap,groupTipList:c}})}_syncUnreadDBMessageAfterLogin(){return I(this,void 0,void 0,function*(){return this._cookie="",this._syncUnreadMessage({isAfterLogin:!0})})}_syncUnreadDBMessageAfterNewMessageReceived(e){return I(this,void 0,void 0,function*(){if(1===e.data.Flag)return this._syncUnreadMessage({isAfterNewMessageReceived:!0})})}_updateConversationUnreadOptions(e){let{unreadCountList:t,overflowUnreadCountList:s,conversationUpdateFieldList:r}=e,{OuterConstant:{CONV_C2C:i,CONV_SYSTEM:n}}=this._core["constants"];null!=t&&t.forEach(e=>{let{From_Account:t,UnreadCount:s}=e;if(t!==n){let e=r.find(({conversationID:e})=>e===""+i+t);e?e.unreadCount=s:r.push({conversationID:""+i+t,unreadCount:s,type:i})}}),null!=s&&s.forEach(e=>{let{From_Account:t,LastMsgTime:s}=e;t===n||r.find(({conversationID:e})=>e===""+i+t)||r.push({conversationID:""+i+t,type:i,lastMsgTime:s})})}_syncUnreadDBMessageAfterReOnline(){return I(this,void 0,void 0,function*(){return this._syncUnreadMessage({isAfterReOnline:!0})})}_updateMessageProfile(r){var e;let i=(this._core.message||{})["messageDataHandler"],t=null==(e=this._core.store.get("login"))?void 0:e.userId,{from:s,nick:n,avatar:o,conversationID:a=""}=r;if(s!==t){let s=i.getLatestMsgSentByPeer(a);if(s){let{nick:e,avatar:t}=s;n&&o?n===e&&o===t||i.updateNickAndAvatarOfSentMessage({conversationID:a,latestNick:n,latestAvatar:o,isSentByMe:!1}):(r.nick=e,r.avatar=t)}}else{let e=i.getLatestMsgSentByMe(a);!e||n===e.nick&&o===e.avatar||i.updateNickAndAvatarOfSentMessage({conversationID:a,latestNick:n,latestAvatar:o,isSentByMe:!0})}}_handleNewMessageList(e){let t=(this._core.message||{})["messageDataHandler"],l=new Map,s=[];return e.forEach(a=>{this._updateMessageProfile(a);let e=1===a.isModified;if(t.isMessageSentByCurrentInstance(a)?a.isModified=e:e=!1,a.isOnlineMessage())a._onlineOnlyFlag=!0,t.isMessageSentByCurrentInstance(a)||s.push(a);else if(!t.isInMessageList(a)){if(t.storeConversationMessage(a)){let{conversationID:e,conversationType:t,conversationSubType:s,flow:r,_isExcludedFromUnreadCount:i,_isExcludedFromLastMessage:n}=a,o=n?"":a;l.has(e)?(l.get(e).lastMessage=o,"in"!==r||i||l.get(e).unreadCount++):l.set(e,{conversationID:e,type:t,subType:s,unreadCount:i||"in"!==r?0:1,lastMessage:o})}t.isMessageSentByCurrentInstance(a)&&!e||s.push(a)}}),{messages:s,conversationOptions:l}}_fetchUnreadDBMessage(c){return I(this,void 0,void 0,function*(){var{ssoLog:e,utils:{safeStringify:t}}=this._core;try{e.debug("_fetchUnreadDBMessage","unread-message-synchronizer._fetchUnreadDBMessage options:"+t(c));var s,r,i,n,o,a,l,u=yield function(i,l){return I(this,void 0,void 0,function*(){let{cookie:e,syncFlag:t,syncTriggerEvent:s}=i,r="openim.getmsg",o=l.helper.generateProtocolData({servcmd:r,data:{Cookie:e,SyncFlag:t,IsOnlineSync:s,NeedAbstract:1,NeedSignaling:1,NeedCachedMsg:1}}),a=""+o.head.seq+r;try{let e=yield l.channel.sendPacket(o,{requestId:a});if(!e)return null;let{C2CPairUnreadCount:t,C2CRemainingUnreadCount:s,EventArray:r}=e,{unreadMessageList:i,revokedMessageList:n}=function(e,E){let r=[],i=[];return null!=e&&e.forEach(I=>{var e,t,s=function(){var{From_Account:e,From_AccountHeadurl:t,From_AccountNick:s,IsNeedReadReceipt:r,MsgBody:i,MsgClientTime:n,MsgRandom:o,MsgSeq:a,MsgTimeStamp:l,SendMsgControl:u,SupportMessageExtension:c,To_Account:d,TinyId:h,MsgCheckResult:g,CloudCustomData:p,IsPeerRead:_,MsgFlagBits:m,MsgVersion:v,EventArray:f}=I;return{from:e,avatar:t,nick:s,needReadReceipt:1===r,readReceiptSentByPeer:_,clientTime:n,messageFlagBits:m,random:o,sequence:a,time:l,messageControlInfo:u,isSupportExtension:c,to:d,tinyID:h,checkResult:g,cloudCustomData:p,messageVersion:v,eventArray:f,elements:E.message.messageHelper.parseServerPushMessageElement(i)}}();if(null!=(t=null==(e=null==(e=null==I?void 0:I.EventArray)?void 0:e[0])?void 0:e.hasOwnProperty)&&t.call(e,"C2cNotifyMsgArray"))i.push(...function(){let e,t=[];return null!=(e=I.EventArray)&&e.forEach(e=>{var e=e["C2cNotifyMsgArray"],e=null==(e=null==(e=null==e?void 0:e[0])?void 0:e.WithdrawC2cMsgNotify)?void 0:e.C2cWithdrawInfoArray;Array.isArray(e)&&t.push(...e)}),t}());else{let e=E.message.messageFactory.createMessage(Object.assign(Object.assign({},s),{conversationType:"C2C",flow:"in"})),t=s["elements"];e.setElement(t),r.push(e)}}),{unreadMessageList:r,revokedMessageList:i}}(e.MsgList,l);return{syncFlag:null==e?void 0:e.SyncFlag,unreadMessageList:i,revokedMessageList:n,unreadCountList:t,overflowUnreadCountList:s,cookie:null==e?void 0:e.Cookie,groupTipList:r}}catch(e){console.warn(e)}})}(c,this._core);return u?({syncFlag:s,unreadMessageList:r,revokedMessageList:i,cookie:n,unreadCountList:o,overflowUnreadCountList:a,groupTipList:l}=u,this._parseAndSaveUnreadMessageList(r),{syncFlag:s,cookie:n,unreadMessageList:r,revokedMessageList:i,unreadCountList:o,overflowUnreadCountList:a,groupTipList:l}):null}catch(e){console.log(e)}})}_canContinueSync({cookie:e,syncFlag:t}){return t===lr.START_SYNC||t===lr.SYNCING&&!(null!=(t=this._core)&&t.helper.isEmpty(e))}_parseAndSaveUnreadMessageList(e){e.forEach(e=>{var t=e["ID"];this._unreadDBMessageMap.set(t,e)})}_reset(){this._cookie="",this._unreadDBMessageMap.clear()}_dispose(){var e;null!=(e=this._core)&&e.notificationCenter.unSubscribeInnerEvent(this._core.InnerEvent.LOGOUT,this._reset,this),null!=(e=this._core)&&e.notificationCenter.unSubscribeInnerEvent(this._core.InnerEvent.DESTROY,this._dispose,this),this._reset()}},pr=new class{init(e){this._core=e,this._visibilityChangeHandler=this._handleVisibilityChange.bind(this),e.notificationCenter.subscribeInnerEvent(e.InnerEvent.DESTROY,this._dispose,this),null!==document&&void 0!==document&&document.addEventListener("visibilitychange",this._visibilityChangeHandler),null!=(e=this._core)&&e.store.set("activityMonitor",{isActive:!0})}_handleVisibilityChange(){var e,t="visible"===document.visibilityState;null!=(e=this._core)&&e.store.set("activityMonitor",{isActive:t}),null!=(e=this._core)&&e.notificationCenter.emitInnerEvent("activityStatusChange",{isActive:t})}_reset(){var e;null!=(e=this._core)&&e.store.clear("activityMonitor")}_dispose(){document.removeEventListener("visibilitychange",this._visibilityChangeHandler);var{notificationCenter:e,InnerEvent:t}=this._core;e.unSubscribeInnerEvent(t.DESTROY,this._dispose,this),this._reset()}},_r=new class{init(e){this._core=e,this._bindAppActivityEvent(),e.notificationCenter.subscribeInnerEvent(e.InnerEvent.DESTROY,this._dispose,this),null!=(e=this._core)&&e.store.set("activityMonitor",{isActive:!0})}_bindAppActivityEvent(){var{MINI_APP_NAMESPACE:e,IN_TT_MINI_GAME:t,IN_WX_MINI_GAME:s}=(null==(e=this._core)?void 0:e.utils)||{};t||s?(null!=(t=null==e?void 0:e.onShow)&&t.call(e,()=>{var e;null!=(e=this._core)&&e.store.set("activityMonitor",{isActive:!0}),null!=(e=this._core)&&e.notificationCenter.emitInnerEvent("activityStatusChange",{isActive:!0})}),null!=(s=null==e?void 0:e.onHide)&&s.call(e,()=>{var e;null!=(e=this._core)&&e.store.set("activityMonitor",{isActive:!1}),null!=(e=this._core)&&e.notificationCenter.emitInnerEvent("activityStatusChange",{isActive:!1})})):(null!=(t=null==e?void 0:e.onAppShow)&&t.call(e,()=>{var e;null!=(e=this._core)&&e.store.set("activityMonitor",{isActive:!0}),null!=(e=this._core)&&e.notificationCenter.emitInnerEvent("activityStatusChange",{isActive:!0})}),null!=(s=null==e?void 0:e.onAppHide)&&s.call(e,()=>{var e;null!=(e=this._core)&&e.store.set("activityMonitor",{isActive:!1}),null!=(e=this._core)&&e.notificationCenter.emitInnerEvent("activityStatusChange",{isActive:!1})}))}_reset(){var e;null!=(e=this._core)&&e.store.clear("activityMonitor")}_dispose(){var{notificationCenter:e,InnerEvent:t}=this._core;e.unSubscribeInnerEvent(t.DESTROY,this._dispose,this),this._reset()}},mr=new class{init(e){var{IN_MINI_APP:t,IN_WX_MINI_PLUGIN:s}=e.helper;s||(t?_r:pr).init(e)}};var vr=new class{init(e){this._core=e,this._activateNetworkMonitoring(),e.notificationCenter.subscribeInnerEvent(e.InnerEvent.DESTROY,this._dispose,this)}_activateNetworkMonitoring(){return I(this,void 0,void 0,function*(){navigator.onLine?this._onOnline():this._onOffline(),this._onOnlineCallback=this._onOnline.bind(this),this._onOfflineCallback=this._onOffline.bind(this),window.addEventListener("online",this._onOnlineCallback),window.addEventListener("offline",this._onOfflineCallback)})}_deactivateNetworkMonitoring(){null!==this._onOnlineCallback&&(window.removeEventListener("online",this._onOnlineCallback),this._onOnlineCallback=null),null!==this._onOfflineCallback&&(window.removeEventListener("offline",this._onOfflineCallback),this._onOfflineCallback=null)}_onNetworkStatusChange(e){var t,{isConnected:e,networkType:s}=e;null!=(t=this._core)&&t.store.set("netWorkMonitor",{isNetworkOnline:e,networkType:s}),null!=(t=this._core)&&t.notificationCenter.emitInnerEvent("networkStatusChange",{isNetworkOnline:e,networkType:s})}_onOnline(){this._onNetworkStatusChange({isConnected:!0,networkType:"online"})}_onOffline(){this._onNetworkStatusChange({isConnected:!1,networkType:"none"})}_reset(){var e;this._deactivateNetworkMonitoring(),null!=(e=this._core)&&e.store.clear("netWorkMonitor")}_dispose(){var e;null!=(e=this._core)&&e.notificationCenter.unSubscribeInnerEvent(null==(e=this._core)?void 0:e.InnerEvent.DESTROY,this._dispose,this),this._reset()}},fr=new class{init(e){this._core=e,this._activateNetworkMonitoring(),e.notificationCenter.subscribeInnerEvent(e.InnerEvent.DESTROY,this._dispose,this)}_activateNetworkMonitoring(){return I(this,void 0,void 0,function*(){try{var{MINI_APP_NAMESPACE:e}=this._core["utils"];this._mpNetworkStatusCallback=this._onNetworkStatusChange.bind(this),e.onNetworkStatusChange(this._onNetworkStatusChange.bind(this))}catch(e){console.error(e)}})}_deactivateNetworkMonitoring(){var e;null!==this._mpNetworkStatusCallback&&({MINI_APP_NAMESPACE:e}=this._core["utils"],e.offNetworkStatusChange&&e.offNetworkStatusChange(this._mpNetworkStatusCallback),this._mpNetworkStatusCallback=null)}_onNetworkStatusChange(e){var t,{isConnected:e,networkType:s}=e;null!=(t=this._core)&&t.store.set("netWorkMonitor",{isNetworkOnline:e,networkType:s}),null!=(t=this._core)&&t.notificationCenter.emitInnerEvent("networkStatusChange",{isNetworkOnline:e,networkType:s})}_reset(){var e;this._deactivateNetworkMonitoring(),null!=(e=this._core)&&e.store.clear("netWorkMonitor")}_dispose(){var e;null!=(e=this._core)&&e.notificationCenter.unSubscribeInnerEvent(null==(e=this._core)?void 0:e.InnerEvent.DESTROY,this._dispose,this),this._reset()}},Ir=new class{init(e){var t=e.utils["IN_MINI_APP"];(t?fr:vr).init(e)}},m=new class{constructor(){this.name="SystemStateMonitor"}install(e){mr.init(e),Ir.init(e)}};let Er=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.*"]),Sr="tui_room_svr.*",Cr=new class{constructor(){this.name="BusinessCommandTransfer",this._transferredCommands=Er}install(e){var{notificationCenter:e,InnerEvent:t,helper:s}=this._core=e;e.subscribeInnerEvent(t.CLOUD_CONFIG_UPDATE,this._onCloudConfigUpdate,this),e.subscribeInnerEvent(t.LOGOUT,this._reset,this),e.subscribeInnerEvent(t.DESTROY,this._dispose,this),e.subscribeInnerEvent("im_open_push.msg_push",e.InnerEventSubType.BUSINESS_COMMAND,this._onServerPushBusinessCommand,this),s.registerExperimentalAPI("sendTRTCCustomData",this,"transferBusinessCommand"),s.registerExperimentalAPI("sendRoomCustomData",this,"transferBusinessCommand")}transferBusinessCommand(s){return I(this,void 0,void 0,function*(){var t="transferBusinessCommand";try{var{serviceCommand:e=Sr}=s||{};if(this._isValidTransferredCommand(e))return{code:0,data:(yield function(n,o){return I(this,void 0,void 0,function*(){var{helper:e,channel:t}=o,{serviceCommand:s=Sr,data:r}=n||{};let i={};try{i="string"==typeof r?JSON.parse(r):r}catch(e){console.warn(e)}r=e.generateProtocolData({servcmd:s,data:i}),e=""+r.head.seq+s;return t.sendPacket(r,{requestId:e})})}(s,this._core))||{}};throw new this._core.helper.ChatError({code:2995,functionName:t})}catch(e){throw console.warn(e),new this._core.helper.ChatError({code:null==e?void 0:e.errorCode,message:null==e?void 0:e.errorInfo,data:{},functionName:t})}})}_onCloudConfigUpdate(e={}){try{var t;"string"==typeof e.rtc_cmd&&(t=JSON.parse(e.rtc_cmd),Array.isArray(t))&&(this._transferredCommands=new Set([...this._transferredCommands,...t]))}catch(e){console.log(e)}}_isValidTransferredCommand(e=""){e=`${null==e?void 0:e.split(".")[0]}.*`;return this._transferredCommands.has(e)}_onServerPushBusinessCommand(e){var{OuterEvent:t,notificationCenter:s}=this._core,e=(e||{})["MsgContent"],t=t["ROOM_CUSTOM_DATA_RECEIVED"];s.emitOuterEvent(t,{name:t,data:e})}_reset(){this._transferredCommands=Er}_dispose(){var{notificationCenter:e,InnerEvent:t}=this._core;this._reset(),e.unSubscribeInnerEvent(t.CLOUD_CONFIG_UPDATE,this._onCloudConfigUpdate,this),e.unSubscribeInnerEvent(t.LOGOUT,this._reset,this),e.unSubscribeInnerEvent(t.DESTROY,this._dispose,this),e.unSubscribeInnerEvent("im_open_push.msg_push",e.InnerEventSubType.BUSINESS_COMMAND,this._onServerPushBusinessCommand,this)}},Mr="signaling",yr="signaling-timeout";function Or(e){return e.filter(e=>{var t,s;return"TIMCustomElem"===e.type&&({cloudCustomData:e="",payload:{data:s=""}={}}=e,e=e.match(/"type":"tsignaling"/),t=s.match(/inviteID/),s=s.match(/actionType/),e||t&&s)})}function Ar(e){var t=e.payload["data"];try{return JSON.parse(t)}catch(e){return console.error(e),null}}function Tr(e,t){return e.toString(16).padStart(t,"0")}function Rr(e){if(e<0||53<e)throw new Error("Number of digits must be between 0 and 53");return e<=30?Math.floor(Math.random()*(1<<e)):(e=e-30,Math.floor(Math.random()*(1<<e))*(1<<30)+Math.floor(Math.random()*(1<<30)))}var Dr,br,Nr,v=new class{constructor(){this._onlineSignalingMap=new Map,this._isSignalingListening=!1}init(e){(this._core=e).notificationCenter.subscribeInnerEvent(e.InnerEvent.DESTROY,this._dispose,this),e.notificationCenter.subscribeInnerEvent(e.InnerEvent.LOGOUT,this._reset,this)}getOnlineSignalingMap(){return this._onlineSignalingMap}hasSignaling(e){return this._onlineSignalingMap.has(e)}getSignaling(e){return this._onlineSignalingMap.get(e)}saveSignaling(e,t){return this._onlineSignalingMap.set(e,t)}removeSignaling(e){return this._onlineSignalingMap.delete(e)}isInvitationValid(e){Mr;var{inviteID:e,groupID:t,inviter:s}=e,s=s===this._core.common.getCurrentUserID();if(!this._onlineSignalingMap.has(e))return!1;var r=this._onlineSignalingMap.get(e)["inviteeList"];if(console.log(`signaling.isInvitationValid inviteID:${e} inviteeList:${r} groupID:`+t),t){if(s)return 0<r.length;let e=this._core.common.getCurrentUserID();return r.includes(e)}return!0}updateSignaling(e){let s=Mr+".updateSignaling",{inviteID:r,inviter:t,inviteeList:i,groupID:n}=e;if(console.log(s+` inviteID:${r} inviter:${t} groupID:`+n),n&&this.hasSignaling(r)){let e=i[0],t=this._onlineSignalingMap.get(r)["inviteeList"];t.includes(e)&&(t.splice(t.indexOf(e),1),console.log(s+` remove ${e}. localInviteeList.length:`+t.length)),0===t.length&&this.removeSignaling(r)}else this.removeSignaling(r)}setSignalingListenStatus(e){this._isSignalingListening=e}getSignalingListenStatus(){return this._isSignalingListening}_dispose(){var e;this._reset(),null!=(e=this._core)&&e.notificationCenter.unSubscribeInnerEvent(this._core.InnerEvent.DESTROY,this._dispose,this),null!=(e=this._core)&&e.notificationCenter.unSubscribeInnerEvent(this._core.InnerEvent.LOGOUT,this._reset,this),this._isSignalingListening=!1}_reset(){this._onlineSignalingMap.clear()}},Lr=new class{init(e){this._core=e}createInviteSignaling(e){var t=this._generateInviteID(),t=this._createInviteSignalingData(Object.assign(Object.assign({},e),{inviteID:t})),{groupID:s,inviteeList:r}=t,s=s||r[0];return{signaling:this._createSignaling(t,s),signalingData:t,signalingExtensionOptions:this._createSignalingExtensionOptions(e)}}createAcceptSignaling(e){var t=this._createAcceptSignalingData(e),{groupID:s,inviter:r}=t;return{signaling:this._createSignaling(t,s||r),signalingData:t,signalingExtensionOptions:this._createSignalingExtensionOptions(e)}}createCancelSignaling(e){var t=this._createCancelSignalingData(e),{groupID:s,inviteeList:r}=t,s=s||r[0];return{signaling:this._createSignaling(t,s),signalingData:t,signalingExtensionOptions:this._createSignalingExtensionOptions(e)}}createRejectSignaling(e){var t=this._createRejectSignalingData(e),{groupID:s,inviter:r}=t;return{signaling:this._createSignaling(t,s||r),signalingData:t,signalingExtensionOptions:this._createSignalingExtensionOptions(e)}}createTimeoutSignaling(e){var{isInviter:t=!1}=e,e=this._createTimeoutSignalingData(e),{groupID:s,inviteeList:r,inviter:i}=e,s=s||(t?r[0]:i);return{signaling:this._createSignaling(e,s),signalingData:e,signalingExtensionOptions:this._createSignalingExtensionOptions(e)}}_createSignalingExtensionOptions(e){var{data:e="",onlineUserOnly:t,inviteID:s="",offlinePushInfo:r,actionType:i}=e,s=(null==(s=null==(s=v.getSignaling(s))?void 0:s.signaling)?void 0:s._onlineOnlyFlag)||!1;return{onlineUserOnly:t||s,offlinePushInfo:r,messageControlInfo:this._createMessageControlInfo(e,i)}}_createMessageControlInfo(e,t){t=5===t&&!!e.match(/excludeTimeoutSignalingFromHistoryMessage/),e=!!e.match(/excludeFromHistoryMessage/)||!!e.match(/excludeOriginalSignalingFromHistoryMessage/);return{excludedFromContentModeration:!0,excludedFromUnreadCount:t||e,excludedFromLastMessage:t||e}}_createInviteSignalingData(e){Mr;var{userID:t,timeout:s=0,groupID:r="",inviteeList:i=[]}=e,n=this._core.common.getCurrentUserID(),e=Object.assign(Object.assign({},this._generateBaseSignalData(e)),{actionType:1,inviter:n,inviteeList:r?i:[t],timeout:s});return console.log("signaling._createInviteSignalingData signalingData:",e),e}_createAcceptSignalingData(e){Mr;var t=e["inviteID"],s=this._core.common.getCurrentUserID(),{inviter:t,groupID:r}=v.getSignaling(t),e=Object.assign(Object.assign({},this._generateBaseSignalData(e)),{actionType:3,groupID:r,inviter:t,inviteeList:[s]});return console.log("signaling._createAcceptSignalingData signalingData:",e),e}_createCancelSignalingData(e){Mr;var t=e["inviteID"],s=this._core.common.getCurrentUserID(),{inviteeList:t,groupID:r}=v.getSignaling(t),e=Object.assign(Object.assign({},this._generateBaseSignalData(e)),{actionType:2,groupID:r,inviter:s,inviteeList:t});return console.log("signaling._createCancelSignalingData signalingData:",e),e}_createRejectSignalingData(e){Mr;var t=e["inviteID"],s=this._core.common.getCurrentUserID(),{inviter:t,groupID:r}=v.getSignaling(t),e=Object.assign(Object.assign({},this._generateBaseSignalData(e)),{actionType:4,groupID:r,inviter:t,inviteeList:[s]});return console.log("signaling._createRejectSignalingData signalingData:",e),e}_createTimeoutSignalingData(e){Mr;var{isInviter:t=!1,inviteID:s}=e,{inviteeList:s,inviter:r}=v.getSignaling(s),i=this._core.common.getCurrentUserID(),e=Object.assign(Object.assign({},this._generateBaseSignalData(e)),{actionType:5,inviter:r,inviteeList:t?s:[i]});return console.log("signaling._createTimeoutSignalingData signalingData:",e),e}_createSignaling(e,t){var{groupID:s=""}=e,t={to:t,conversationType:s?"GROUP":"C2C",priority:"High",payload:{data:JSON.stringify(e)}};return null==(s=null==(e=null==(s=this._core)?void 0:s.message)?void 0:e.messageFactory)?void 0:s.createCustomMessage(t)}_generateInviteID(){return[Tr(Rr(32),8),Tr(Rr(16),4),Tr(16384|Rr(12),4),Tr(32768|Rr(14),4),Tr(Rr(48),12)].join("-")}_generateBaseSignalData(e){var{data:e="",inviteID:t="",groupID:s=""}=e;return{businessID:1,timeout:0,data:e,inviteID:t,groupID:s}}},Pr=new class{constructor(){this._isProcessingSignaling=!1}init(e){(this._core=e).helper.registerApi({apiName:"invite",context:this}),e.helper.registerApi({apiName:"accept",context:this}),e.helper.registerApi({apiName:"cancel",context:this}),e.helper.registerApi({apiName:"reject",context:this}),e.helper.registerApi({apiName:"modifyInvitation",context:this}),e.helper.registerApi({apiName:"getSignalingInfo",context:this}),e.helper.registerApi({apiName:"addSignalingListener",context:this}),e.helper.registerApi({apiName:"removeSignalingListener",context:this}),e.notificationCenter.subscribeInnerEvent(e.InnerEvent.DESTROY,this._dispose,this),e.notificationCenter.subscribeInnerEvent(e.InnerEvent.LOGOUT,this._reset,this)}invite(t){return I(this,void 0,void 0,function*(){var s;try{this._validateBeforeInvite(t);var{signaling:r,signalingData:i,signalingExtensionOptions:e}=Lr.createInviteSignaling(t),n=yield this._sendSignaling(r,e);if(0!==(null==n?void 0:n.code))return n;{let{inviteID:e,timeout:t}=i;return v.saveSignaling(e,Object.assign(Object.assign({},i),{signaling:r})),0<t&&(null!=(s=this._core)&&s.helper.taskScheduler.addOnceTask({id:yr+"-"+e,intervalMs:1e3*(t+5),callback:this.handleInvitationExpiryTimer.bind(this,e)})),Object.assign(Object.assign({},n),{inviteID:e})}}catch(e){throw e}})}accept(n){return I(this,void 0,void 0,function*(){try{var e=n["inviteID"],{signaling:t,signalingData:s,signalingExtensionOptions:r}=(this._validateBeforeAccept(e),this._isProcessingSignaling=!0,Lr.createAcceptSignaling(n)),i=yield this._sendSignaling(t,r);return 0===(null==i?void 0:i.code)?(v.updateSignaling(s),Object.assign(Object.assign({},i),{inviteID:e})):i}catch(e){throw e}finally{this._isProcessingSignaling=!1}})}cancel(i){return I(this,void 0,void 0,function*(){try{var e=i["inviteID"],{signaling:t,signalingExtensionOptions:s}=(this._validateBeforeCancel(e),this._isProcessingSignaling=!0,Lr.createCancelSignaling(i)),r=yield this._sendSignaling(t,s);return 0===(null==r?void 0:r.code)?(v.removeSignaling(e),Object.assign(Object.assign({},r),{inviteID:e})):r}catch(e){throw e}finally{this._isProcessingSignaling=!1}})}reject(i){return I(this,void 0,void 0,function*(){try{var e=i["inviteID"],{signaling:t,signalingExtensionOptions:s}=(this._validateBeforeReject(e),this._isProcessingSignaling=!0,Lr.createRejectSignaling(i)),r=yield this._sendSignaling(t,s);return 0===(null==r?void 0:r.code)?(v.removeSignaling(e),Object.assign(Object.assign({},r),{inviteID:e})):r}catch(e){throw e}finally{this._isProcessingSignaling=!1}})}modifyInvitation(e){return I(this,void 0,void 0,function*(){var r,i,{inviteID:n,data:o}=e;let a="";try{this._validateBeforeModifyInvitation(n);let e=v.getSignaling(n),t=e["signaling"],s=f(e,["signaling"]);a=t.payload.data,s.data=o,t.payload.data=JSON.stringify(s);var l=yield null==(i=null==(r=this._core)?void 0:r.message.messageAction)?void 0:i.modifyMessage(t);return v.hasSignaling(n)&&v.saveSignaling(n,Object.assign(Object.assign({},s),{signaling:t})),l}catch(e){if(a){let e=v.getSignaling(n)["signaling"];e.payload.data=a}throw e}})}getSignalingInfo(e){var{ssoLog:t,utils:{safeStringify:s}}=this._core;if(0!==Or([e]).length)return e={businessID:(e=Ar(e)).businessID||1,inviteID:e.inviteID,groupID:e.groupID||"",inviter:e.inviter||"",inviteeList:e.inviteeList||[],data:e.data||"",actionType:e.actionType||1,timeout:e.timeout||0},t.debug(Mr+" getSignalingInfo "+s(e)),e}addSignalingListener(e,t,s){var r;e===(null==(r=this._core)?void 0:r.SignalingEvent.NEW_INVITATION_RECEIVED)&&v.setSignalingListenStatus(!0),null!=(r=this._core)&&r.notificationCenter.subscribeOuterEvent(e,t,s)}removeSignalingListener(e,t,s){var r;e===(null==(r=this._core)?void 0:r.SignalingEvent.NEW_INVITATION_RECEIVED)&&v.setSignalingListenStatus(!1),null!=(r=this._core)&&r.notificationCenter.unSubscribeOuterEvent(e,t,s)}handleInvitationExpiryTimer(e){var t=v.getOnlineSignalingMap(),s=this._core.common.getCurrentUserID();t.has(e)&&(t=t.get(e).inviter===s,this._sendTimeoutNotice({inviteID:e,isInviter:t}))}_sendSignaling(t,s){return I(this,void 0,void 0,function*(){var e;return null==(e=null==(e=null==(e=this._core)?void 0:e.message)?void 0:e.messageSender)?void 0:e.sendMessage(t,s)})}_sendTimeoutNotice(s){return I(this,void 0,void 0,function*(){var i;this._core.ssoLog.debug("_sendTimeoutNotice",Mr+"._sendTimeoutNotice params:"+JSON.stringify(s));let{isInviter:n,inviteID:o}=s,{signaling:a,signalingData:l,signalingExtensionOptions:e}=Lr.createTimeoutSignaling(s),t=yield this._sendSignaling(a,e);if(0===(null==t?void 0:t.code)){let{data:e,groupID:t,inviteeList:s,inviter:r}=l;null!=(i=this._core)&&i.notificationCenter.emitOuterEvent(null==(i=this._core)?void 0:i.SignalingEvent.INVITATION_TIMEOUT,{name:null==(i=this._core)?void 0:i.SignalingEvent.INVITATION_TIMEOUT,data:{data:e,groupID:t,inviteID:o,inviteeList:s,inviter:r,isSelfTimeout:!0,message:a}}),n?v.removeSignaling(o):v.updateSignaling(l)}})}_validateInviteId(e,t){if(!v.hasSignaling(t))throw new this._core.helper.ChatError({functionName:e,code:8010})}_validateProcessStatus(e){if(this._isProcessingSignaling)throw new this._core.helper.ChatError({functionName:e,message:"processing other signaling operations"})}_validateBeforeInvite(e){var e=e["userID"],t=this._core.common.getCurrentUserID();if(e===t)throw new this._core.helper.ChatError({functionName:"invite",message:`cannot invite yourself, currentUserId:${t}, inviteeId:`+e})}_validateBeforeAccept(t){var s="accept";this._validateInviteId(s,t),this._validateProcessStatus(s);let r=this._core.common.getCurrentUserID(),e=v.getSignaling(t)["inviteeList"];if(!e.includes(r)){let e=`userID:${r} not in inviteeList. inviteID:`+t;throw new this._core.helper.ChatError({functionName:s,message:e})}}_validateBeforeCancel(e){var t="cancel",s=(this._validateInviteId(t,e),this._validateProcessStatus(t),this._core.common.getCurrentUserID()),r=v.getSignaling(e)["inviter"];if(r!==s){let e=`unmatched inviter:${r} and my userID:`+s;throw new this._core.helper.ChatError({functionName:t,message:e})}}_validateBeforeReject(t){var s="reject";this._validateInviteId(s,t),this._validateProcessStatus(s);let r=this._core.common.getCurrentUserID(),e=v.getSignaling(t)["inviteeList"];if(!e.includes(r)){let e=`userID:${r} not in inviteeList. inviteID:`+t;throw new this._core.helper.ChatError({functionName:s,message:e})}}_validateBeforeModifyInvitation(e){this._validateInviteId("modifyInvitation",e)}_dispose(){var e;this._reset(),null!=(e=this._core)&&e.notificationCenter.unSubscribeInnerEvent(this._core.InnerEvent.DESTROY,this._dispose,this),null!=(e=this._core)&&e.notificationCenter.unSubscribeInnerEvent(this._core.InnerEvent.LOGOUT,this._reset,this)}_reset(){this._isProcessingSignaling=!1}},Gr=new class{constructor(){this._actionProcessor=new Map([[1,this._onNewInvitationReceived.bind(this)],[4,this._onInviteeRejected.bind(this)],[3,this._onInviteeAccepted.bind(this)],[2,this._onInvitationCancelled.bind(this)],[5,this._onInvitationTimeout.bind(this)]])}init(e){(this._core=e).notificationCenter.subscribeOuterEvent(e.OuterEvent.MESSAGE_RECEIVED,this._handleMessageReceived,this),e.notificationCenter.subscribeOuterEvent(e.OuterEvent.MESSAGE_MODIFIED,this._handleMessageModified,this),e.notificationCenter.subscribeInnerEvent(e.InnerEvent.DESTROY,this._dispose,this)}handleActionSignaling(e){e.forEach(e=>{var t,s=Ar(e);s&&null!=(t=this._actionProcessor.get(s.actionType))&&t(s,e)})}_handleMessageReceived(e){v.getSignalingListenStatus()&&0!==(e=Or(e.data)).length&&this.handleActionSignaling(e)}_handleMessageModified(e){v.getSignalingListenStatus()&&0<(e=Or(e.data)).length&&e.forEach(e=>{var t=Ar(e);t&&this._onInvitationModified(t,e)})}_onNewInvitationReceived(t,s){Mr;var{inviteID:r,inviteeList:i,groupID:n}=t,o=this._core.common.getCurrentUserID();if(this._core.ssoLog.debug("_onNewInvitationReceived",`signaling._onNewInvitationReceived signalingData:${JSON.stringify(t)}}`),!n||i.includes(o)){let e=t["timeout"];var n=Date.now()/1e3-s.time,o=(0<e&&0<n&&e>n&&(e-=n),v.getSignaling(r));o!==t&&(o||v.saveSignaling(r,Object.assign(Object.assign({},t),{signaling:s})),0<e&&(null!=(n=this._core)&&n.helper.taskScheduler.addOnceTask({id:yr+"-"+r,intervalMs:1e3*e,callback:Pr.handleInvitationExpiryTimer.bind(Pr,r)})),this._emitEvent({name:null==(o=this._core)?void 0:o.SignalingEvent.NEW_INVITATION_RECEIVED,data:Object.assign(Object.assign({},this._generateBaseEmitData(t)),{inviteeList:i})}))}}_onInviteeRejected(e){Mr;var{inviteID:t,inviter:s,groupID:r,inviteeList:i}=e,n=v.hasSignaling(t);this._core.ssoLog.debug("_onInviteeRejected",`signaling._onInviteeRejected inviteID:${t} hasInviteID:${n} inviter:${s} groupID:`+r),n&&(v.updateSignaling(e),this._emitEvent({name:null==(t=this._core)?void 0:t.SignalingEvent.INVITEE_REJECTED,data:Object.assign(Object.assign({},this._generateBaseEmitData(e)),{invitee:i[0]})}))}_onInviteeAccepted(e){Mr;var{inviteID:t,inviter:s,groupID:r,inviteeList:i}=e,n=v.hasSignaling(t);this._core.ssoLog.debug("_onInviteeAccepted",`signaling._onInviteeAccepted inviteID:${t} hasInviteID:${n} inviter:${s} groupID:`+r),n&&(v.updateSignaling(e),this._emitEvent({name:null==(t=this._core)?void 0:t.SignalingEvent.INVITEE_ACCEPTED,data:Object.assign(Object.assign({},this._generateBaseEmitData(e)),{invitee:i[0]})}))}_onInvitationCancelled(e){Mr;var{inviteID:t,inviter:s,groupID:r}=e,i=v.hasSignaling(t);this._core.ssoLog.debug("_onInvitationCancelled",`signaling._onInvitationCancelled inviteID:${t} hasInviteID:${i} inviter:${s} groupID:`+r),i&&(v.removeSignaling(t),this._emitEvent({name:null==(s=this._core)?void 0:s.SignalingEvent.INVITATION_CANCELLED,data:this._generateBaseEmitData(e)}))}_onInvitationTimeout(e){Mr;var{inviteID:t,inviteeList:s}=e,r=v.hasSignaling(t);this._core.ssoLog.debug("_onInvitationTimeout",`signaling._onInvitationTimeout inviteID:${t} hasInviteID:${r} data:`+e.data),r&&(v.updateSignaling(e),this._emitEvent({name:null==(t=this._core)?void 0:t.SignalingEvent.INVITATION_TIMEOUT,data:Object.assign(Object.assign({},this._generateBaseEmitData(e)),{inviteeList:s,isSelfTimeout:!1})}))}_onInvitationModified(e,t){Mr;var{inviteID:s,data:r}=e,i=v.hasSignaling(s);this._core.ssoLog.debug("_onInvitationModified",`signaling._onInvitationModified inviteID:${s} data:`+r),i&&(v.saveSignaling(s,Object.assign(Object.assign({},e),{signaling:t})),this._emitEvent({name:null==(i=this._core)?void 0:i.SignalingEvent.INVITATION_MODIFIED,data:{inviteID:s,data:r}}))}_emitEvent(e){var t;null!=(t=this._core)&&t.notificationCenter.emitOuterEvent(e.name,e)}_generateBaseEmitData(e){var{inviteID:e,inviter:t,groupID:s,data:r}=e;return{inviteID:e,inviter:t,groupID:s,data:r||""}}_dispose(){var e;null!=(e=this._core)&&e.notificationCenter.unSubscribeOuterEvent(this._core.OuterEvent.MESSAGE_RECEIVED,this._handleMessageReceived,this),null!=(e=this._core)&&e.notificationCenter.unSubscribeOuterEvent(this._core.OuterEvent.MESSAGE_MODIFIED,this._handleMessageModified,this),null!=(e=this._core)&&e.notificationCenter.unSubscribeOuterEvent(this._core.InnerEvent.DESTROY,this._dispose,this)}},wr=new class{constructor(){this._offlineSignalingMap=new Map}init(e){var{notificationCenter:e,helper:t,constants:{InnerEvent:s,WORKFLOW_STEP:r,WORKFLOW_NAME:i}}=this._core=e;e.subscribeInnerEvent(s.DESTROY,this._dispose,this),e.subscribeInnerEvent(s.LOGOUT,this._reset,this),t.registerWorkflowStep(i.SYNC_SERVER_INFO_AFTER_LOGIN,r.SIGNALING_MESSAGE_RECOVER,this._handleC2COfflineMessage,this)}_handleC2COfflineMessage(e){var{result:{unreadMessageMap:e}={}}=e||{};if(0!==(null==e?void 0:e.size)&&v.getSignalingListenStatus()){e=Or([...e.values()]);if(0!==e.length&&(e.forEach(e=>{this._handleC2CActionType(e)}),0<this._offlineSignalingMap.size)){let e=this._sortOfflineSignalingByTime();Gr.handleActionSignaling(e)}}}_handleC2CActionType(e){var t,s=Ar(e);s&&(t=s["actionType"],1===t?this._saveValidOfflineInvite(s,e):this._removeOfflineInvite(s))}_saveValidOfflineInvite(e,t){var{inviteID:s,inviteeList:r=[],timeout:i=0}=e,n=this._core.common.getCurrentUserID();r.includes(n)&&(r=Date.now()/1e3-t.time,0<i&&i<r&&0!==i||this._offlineSignalingMap.set(s,Object.assign(Object.assign({},e),{signalingList:[t]})))}_removeOfflineInvite(e){var{inviteID:e=""}=e;this._offlineSignalingMap.has(e)&&this._offlineSignalingMap.delete(e)}_sortOfflineSignalingByTime(){let t=[];return this._offlineSignalingMap.forEach(e=>{t=[...t,...e.signalingList]}),t.sort((e,t)=>e.time-t.time)}_dispose(){var e;this._reset(),null!=(e=this._core)&&e.notificationCenter.unSubscribeInnerEvent(this._core.InnerEvent.LOGOUT,this._reset,this),null!=(e=this._core)&&e.notificationCenter.unSubscribeInnerEvent(this._core.InnerEvent.DESTROY,this._dispose,this)}_reset(){this._offlineSignalingMap.clear()}};let Ur={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}}},kr={invite:!0,cancel:!0,accept:!0,reject:!0,modifyInvitation:!0},Fr=new class{constructor(){this.name="Signaling"}install(e){Pr.init(e),Gr.init(e),Lr.init(e),v.init(e),wr.init(e),e.helper.registerValidateConfig({auth:kr,params:Ur})}},E=new class{init(e){this.core=e}},qr=((L=Dr=Dr||{}).MSG_TEXT="TIMTextElem",L.MSG_CUSTOM="TIMCustomElem",L.MSG_LOCATION="TIMLocationElem",L.MSG_FACE="TIMFaceElem",(y=br=br||{})[y.FORWARD=0]="FORWARD",y[y.BACKWARD=1]="BACKWARD",{ZH_CN:"zh (cmn-Hans-CN)",EN_US:"en-US",YUE_HK:"yue-Hant-HK",JA_JP:"ja-JP",ZH_PY:"zh-PY"}),xr="16k_zh-PY",Vr={[qr.ZH_CN]:"16k_zh",[qr.EN_US]:"16k_en",[qr.YUE_HK]:"16k_yue",[qr.JA_JP]:"16k_ja",[qr.ZH_PY]:xr},Br=/\.(wav|pcm|ogg-opus|speex|silk|mp3|m4a|aac|amr)/,jr={READ:0,UNREAD:1},Kr=((n=Nr=Nr||{}).IN="in",n.OUT="out","C2C"),Hr="GROUP";function Wr(d){return I(this,void 0,void 0,function*(){var t,{appStore:s,utils:{isEmpty:r},common:{getCurrentUserID:i},notificationCenter:e,OuterEvent:n}=E.core,{messageList:o,conversationID:a}=d,l=s.conversationStore.getConversationMap();let u=null==(t=l.get(a))?void 0:t.peerReadTime;if(!u){let e=a.replace(Kr,""),t=yield function(t){return I(this,void 0,void 0,function*(){var e={To_Account:t};return E.core.common.buildAndSendPacket({servcmd:"openim.get_peer_read_time",data:e})})}([e]);if(t){let e=t["ReadTime"];u=null==e?void 0:e[0],l.has(a)&&(l.get(a).peerReadTime=u)}}if(l.has(a)){let e=null==(t=l.get(a))?void 0:t.lastMessage;r(e)||e.fromAccount===i()&&e.lastTime<=u&&!e.isPeerRead&&(e.isPeerRead=!0,s.conversationStore.updateConversation(a,{lastMessage:e}))}let c=[];o.forEach(e=>{e.time<=u&&!e.isPeerRead&&"out"===e.flow&&(e.isPeerRead=!0,c.push(e))}),e.emitOuterEvent(n.MESSAGE_READ_BY_PEER,{name:n.MESSAGE_READ_BY_PEER,data:c})})}function Yr(a){return I(this,void 0,void 0,function*(){var e;let{message:s,user:t,appStore:r,constants:{OuterConstant:i}}=E.core,n=r.conversationStore.getConversationMap();if(n.has(a)){let s=null==(e=n.get(a))?void 0:e.userProfile;if(s&&a.startsWith(i.CONV_C2C)){let{avatar:e,nick:t}=s;E.core.message.messageDataHandler.updateNickAndAvatarOfSentMessage({conversationID:a,latestAvatar:e,latestNick:t,isSentByMe:!1})}}var o=((yield t.userProfile.getMyProfile())||{})["data"];if(o){let{avatar:e,nick:t}=o;s.messageDataHandler.updateNickAndAvatarOfSentMessage({conversationID:a,latestAvatar:e,latestNick:t,isSentByMe:!0})}})}function $r(e){let t,s=E.core["message"],{conversationID:r,messageID:i}=e;return t=(t=s.messageDataHandler.getLocalMessageList(r).find(e=>e.ID===i))||s.messageDataHandler.getSparseMessageList(r).find(e=>e.ID===i)}function zr(e){return e.map(e=>{var{from:t,to:s,cloudCustomData:r,avatar:i,nick:n,ID:o,clientSequence:a,clientTime:l,messageRandom:u,messageSequence:c,time:d}=e;return{ClientSeq:a,CloudCustomData:r,From_Account:t,From_AccountHeadurl:i,From_AccountNick:n,Id:o,MsgBody:JSON.parse(JSON.stringify(e.transformElementsToServerFormat())),MsgClientTime:l,MsgRandom:u,Random:u,MsgSeq:c,MsgTimeStamp:d,ReceiverId:s,SenderId:t,To_Account:s}})}function Jr(e){var{From_Account:t,From_AccountHeadurl:s,From_AccountNick:r,GroupId:i,MsgClientTime:n,ClientSeq:o,To_Account:a,MsgTimeStamp:l,TinyId:u,MsgRandom:c,MsgSeq:d}=e;return{from:t,avatar:s,nick:r,clientTime:n,time:l,tinyID:u,random:c,sequence:d,to:a,groupID:i,clientSequence:o,_elements:null==(t=e.MsgBody)?void 0:t.map(e=>{var t=e["MsgType"];return E.core.message.messageFactory.getElementClass(t).parseServerPushElement(e)})}}var Qr=new class{constructor(){this._reactionsMap=new Map}init(e){var{helper:e,notificationCenter:t,InnerEvent:{MESSAGE_PUSH:s},InnerEventSubType:{MESSAGE_REACTION_UPDATED:r,MESSAGE_REACTION_UPDATED_SYNC:i}}=this._core=e;e.registerApi({apiName:"addMessageReaction",context:this}),e.registerApi({apiName:"removeMessageReaction",context:this}),e.registerApi({apiName:"getMessageReactions",context:this}),e.registerApi({apiName:"getAllUserListOfMessageReaction",context:this}),t.subscribeInnerEvent(s,r,this._handleReactionUpdated,this),t.subscribeInnerEvent(s,i,this._handleReactionSync,this)}addMessageReaction(d,h){return I(this,void 0,void 0,function*(){let{OuterConstant:e,helper:s}=this._core;this._validateMessageReactionBusinessCapability();var{conversationID:r,ID:i,conversationType:t,from:n,to:o,clientSequence:a,random:l,time:u,sequence:c}=d,r=`conversationID:${r} messageID:${i} reactionID:`+h;try{return this._recordMessageReactedByMe(i,h),t===e.CONV_C2C?yield function(o,a){return I(this,void 0,void 0,function*(){var{from:e,to:t,clientSequence:s,random:r,time:i,reactionID:n}=o,t={From_Account:e,To_Account:t,MsgKey:s+`_${r}_`+i,Reaction:n,Add_Account:[null==(e=a.store.get("login"))?void 0:e.userId]};return E.core.common.buildAndSendPacket({servcmd:"openim_msg_ext_http_svc.reaction_add",data:t})})}({from:n,to:o,clientSequence:a,random:l,time:u,reactionID:h},this._core):t===e.CONV_GROUP&&(yield function(r,i){return I(this,void 0,void 0,function*(){var{to:e,reactionID:t,sequence:s}=r,s={GroupId:e,MsgSeq:s,Reaction:t,Add_Account:[null==(e=i.store.get("login"))?void 0:e.userId]};return E.core.common.buildAndSendPacket({servcmd:"openim_msg_ext_http_svc.group_reaction_add",data:s})})}({to:o,reactionID:h,sequence:c},this._core)),{code:0,successLog:{message:r}}}catch(e){this._removeMyReactionRecord(i,h);let t=(e||{})["errorCode"];throw new s.ChatError({functionName:"addMessageReaction",code:t,moreMessage:r})}})}removeMessageReaction(d,h){return I(this,void 0,void 0,function*(){var{OuterConstant:e,helper:s}=this._core,{conversationID:r,ID:t,conversationType:i,from:n,to:o,clientSequence:a,random:l,time:u,sequence:c}=(this._validateMessageReactionBusinessCapability(),d),r=`conversationID:${r} messageID:${t} reactionID:`+h;try{return this._removeMyReactionRecord(t,h),i===e.CONV_C2C?yield function(o,a){return I(this,void 0,void 0,function*(){var{from:e,to:t,clientSequence:s,random:r,time:i,reactionID:n}=o,t={From_Account:e,To_Account:t,MsgKey:s+`_${r}_`+i,Reaction:n,Del_Account:[null==(e=a.store.get("login"))?void 0:e.userId]};return E.core.common.buildAndSendPacket({servcmd:"openim_msg_ext_http_svc.reaction_del",data:t})})}({from:n,to:o,clientSequence:a,random:l,time:u,reactionID:h},this._core):i===e.CONV_GROUP&&(yield function(r,i){return I(this,void 0,void 0,function*(){var{to:e,reactionID:t,sequence:s}=r,s={GroupId:e,MsgSeq:s,Reaction:t,Del_Account:[null==(e=i.store.get("login"))?void 0:e.userId]};return E.core.common.buildAndSendPacket({servcmd:"openim_msg_ext_http_svc.group_reaction_del",data:s},i)})}({to:o,reactionID:h,sequence:c},this._core)),{code:0,successLog:{message:r}}}catch(e){let t=(e||{})["errorCode"];throw new s.ChatError({functionName:"removeMessageReaction",code:t,moreMessage:r})}})}getAllUserListOfMessageReaction(l){return I(this,void 0,void 0,function*(){this._validateMessageReactionBusinessCapability();let{message:e,reactionID:t,nextSeq:r=0}=l,s=100<l.count?100:l.count,i=e["conversationID"],{helper:n,constants:o}=this._core;try{var a;if(a=i.startsWith(o.OuterConstant.CONV_C2C)?yield function(l){return I(this,void 0,void 0,function*(){var{message:e,nextSeq:t,reactionID:s,count:r}=l,{from:e,to:i,clientSequence:n,random:o,time:a}=e,s={Reaction:s,NextSeq:t,Count:r,From_Account:e,To_Account:i,MsgKey:n+`_${o}_`+a};return E.core.common.buildAndSendPacket({servcmd:"openim_msg_ext_http_svc.reaction_iterate",data:s})})}({message:e,reactionID:t,nextSeq:r,count:s}):yield function(n){return I(this,void 0,void 0,function*(){var{message:e,nextSeq:t,reactionID:s,count:r}=n,{sequence:e,to:i}=e,s={Reaction:s,NextSeq:t,GroupId:i,Count:r,MsgSeq:e};return E.core.common.buildAndSendPacket({servcmd:"openim_msg_ext_http_svc.group_reaction_iterate",data:s})})}({message:e,reactionID:t,nextSeq:r,count:s})){let{Reaction_Account:e,NextSeq:t}=a,s=yield this._getUserProfileList(e);return{code:0,data:{nextSeq:t,isCompleted:0===r,userList:s}}}}catch(e){let t=(e||{})["errorCode"];throw new n.ChatError({functionName:"getAllUserListOfMessageReaction",code:t})}})}getMessageReactions(g){return I(this,void 0,void 0,function*(){var e=this._core["constants"],{messageList:t,maxUserCountPerReaction:s=10}=(this._validateMessageReactionBusinessCapability(),g),r=t[0];let i=null,n=new Map,{from:o,to:a,conversationType:l}=r,u=this._generateMessageKeyList(t,n),{Results:c=[]}=(l===e.OuterConstant.CONV_C2C?i=yield function(i){return I(this,void 0,void 0,function*(){var{from:e,to:t,messageKeyList:s,maxUserCountPerReaction:r}=i,e={From_Account:e,To_Account:t,MsgKeyList:s,Count:r};return E.core.common.buildAndSendPacket({servcmd:"openim_msg_ext_http_svc.reaction_multi_stat",data:e})})}({from:o,to:a,messageKeyList:u,maxUserCountPerReaction:s}):l===e.OuterConstant.CONV_GROUP&&(i=yield function(r){return I(this,void 0,void 0,function*(){var{groupId:e,messageSequenceList:t,maxUserCountPerReaction:s}=r,e={GroupId:e,MsgSeqList:t,Count:s};return E.core.common.buildAndSendPacket({servcmd:"openim_msg_ext_http_svc.group_reaction_multi_stat",data:e})})}({groupId:a,messageSequenceList:u,maxUserCountPerReaction:s})),i||{}),d=this._extractUserIDsFromReactionResults(c),h=yield this._getUserProfileMap(d);return{code:0,data:{resultList:c.map(e=>{var{ReactionList:e,MsgSeq:t,MsgKey:s}=e;return{messageID:this._generateMessageID({messageSequence:t,messageKey:s,messageIDMap:n}),reactionList:e.map(e=>{var{Reaction:e,Count:t,Reaction_Account:s,ReactedByMe:r}=e;return{reactionID:e,totalUserCount:t,partialUserList:this._generatePartialUserInfo({userIDList:s,userProfileMap:h}),reactedByMyself:1===r}})}})}}})}dispose(){this._reactionsMap.clear()}_extractUserIDsFromReactionResults(e){let t=[];return null!=e&&e.forEach(e=>{var{ReactionList:e=[]}=e;e.forEach(e=>{e.Reaction_Account&&t.push(...e.Reaction_Account)})}),t}_getUserProfileList(s){return I(this,void 0,void 0,function*(){var e;try{var t=yield null==(e=this._core.user.userProfile)?void 0:e.getUserProfile({userIDList:s});return t?t.data:[]}catch(e){return[]}})}_getUserProfileMap(e){return I(this,void 0,void 0,function*(){let r=new Map;return(yield this._getUserProfileList(e)).forEach(e=>{var{nick:e,avatar:t,userID:s}=e;r.set(s,{nick:e,avatar:t,userID:s})}),r})}_recordMessageReactedByMe(e,t){e=e+"-"+t;this._reactionsMap.has(e)?this._reactionsMap.get(e).reactedByMe=!0:this._reactionsMap.set(e,{reactedByMe:!0})}_removeMyReactionRecord(e,t){e=e+"-"+t;this._reactionsMap.has(e)&&(this._reactionsMap.get(e).reactedByMe=!1)}_recordMessageReactionInfo(e){var{messageID:e,reactionID:t,reactionInfo:s}=e,e=e+"-"+t,t=this._reactionsMap.get(e)||{};this._reactionsMap.set(e,Object.assign(Object.assign({},t),s))}_validateMessageReactionBusinessCapability(){var{helper:e,constants:t}=this._core;if(!e.checkBusinessCapabilityBits("MSG_REACTION"))throw new e.ChatError({functionName:"addMessageReaction",code:t.ERROR_CODE.NO_USE,replacement1:"addMessageReaction"})}_handleReactionUpdated(e){let t=e["MsgReactionNotifyList"],{notificationCenter:d,constants:h}=this._core;t.forEach(c=>I(this,void 0,void 0,function*(){let{C2CMsgInfo:e,GroupMsgInfo:t,MsgReactionSummary:s}=c,{TinyId:r,MsgClientTime:i,MsgRandom:n}=Object.assign(Object.assign({},e),t),o=r+`-${i}-`+n,a=this._extractUserIDsFromReactionResults([{ReactionList:s}]),l=yield this._getUserProfileMap(a),u=s.map(e=>{var{Reaction:t,Reaction_Account:s}=e,r=this._generatePartialUserInfo({userIDList:s,userProfileMap:l}),s=s?e.Count:0,e=(null==(e=this._reactionsMap.get(o+"-"+t))?void 0:e.reactedByMe)||!1;return this._recordMessageReactionInfo({messageID:o,reactionID:t,reactionInfo:{reactionID:t,totalUserCount:s,partialUserList:r}}),{reactionID:t,totalUserCount:s,partialUserList:r,reactedByMyself:e}});d.emitOuterEvent(h.OuterEvent.MESSAGE_REACTIONS_UPDATED,{name:h.OuterEvent.MESSAGE_REACTIONS_UPDATED,data:{messageID:o,reactionList:u}})}))}_handleReactionSync(e){var{notificationCenter:t,constants:s}=this._core,{C2CMsgInfo:e={},GroupMsgInfo:r={},Reaction:i,OperateType:n}=e.MsgReactionNotify,{TinyId:e="",MsgClientTime:r=0,MsgRandom:o=0}=Object.assign(Object.assign({},e),r),r=e+`-${r}-`+o,o=r+"-"+i;if(1===n?this._recordMessageReactedByMe(r,i):this._removeMyReactionRecord(r,i),null!=(e=this._reactionsMap.get(o))&&e.reactionID){let e=this._reactionsMap.get(o);e.reactedByMyself=1===n,t.emitOuterEvent(s.OuterEvent.MESSAGE_REACTIONS_UPDATED,{name:s.OuterEvent.MESSAGE_REACTIONS_UPDATED,data:{messageID:r,reactionList:[e]}})}}_generatePartialUserInfo({userIDList:e,userProfileMap:t}){let s=[];return null!=e&&e.forEach(e=>{t.has(e)&&s.push(t.get(e))}),s}_generateMessageID(e){var{messageSequence:e,messageKey:t,messageIDMap:s}=e;return t?s.get(t):s.get(e)}_generateMessageKeyList(e,i){var t=this._core["constants"],s=e[0]["conversationType"];let r=[];return s===t.OuterConstant.CONV_C2C?r=e.map(e=>{var{clientSequence:e,random:t,time:s,ID:r}=e,e=e+`_${t}_`+s;return i.set(e,r),e}):s===t.OuterConstant.CONV_GROUP&&(r=e.map(e=>{var{ID:e,sequence:t}=e;return i.set(t,e),t})),r}},Xr=new class{init(e){var{helper:e,InnerEvent:{MESSAGE_PUSH:t},InnerEventSubType:{C2C_MESSAGE_READ_RECEIPT:s,GROUP_MESSAGE_READ_RECEIPT:r},notificationCenter:i}=this._core=e;e.registerApi({apiName:"sendMessageReadReceipt",context:this}),e.registerApi({apiName:"getMessageReadReceiptList",context:this}),e.registerApi({apiName:"getGroupMessageReadMemberList",context:this}),i.subscribeInnerEvent(t,s,this._handleC2CMessageReadReceipt,this),i.subscribeInnerEvent(t,r,this._handleGroupMessageReadReceipt,this)}sendMessageReadReceipt(e){return I(this,void 0,void 0,function*(){let{common:r,constants:t}=this._core,s=this._filterValidMessageSendByOther(e);if(0===s.length)throw new r.ChatError({code:t.ERROR_CODE.READ_RECEIPT_MSG_LIST_EMPTY});try{let e=s[0]["conversationType"];return e===t.OuterConstant.CONV_C2C?yield function(r){return I(this,void 0,void 0,function*(){var{common:e,constants:t}=E.core,t=r[0].conversationID.replace(t.OuterConstant.CONV_C2C,""),s=r.map(e=>{var{from:e,to:t,sequence:s,random:r,time:i,clientTime:n}=e;return{From_Account:e,To_Account:t,MsgSeq:s,MsgRandom:r,MsgTime:i,MsgClientTime:n}});return e.buildAndSendPacket({servcmd:"openim.c2c_msg_read_receipt",data:{Peer_Account:t,C2CMsgInfo:s}})})}(s):yield function(s){return I(this,void 0,void 0,function*(){var{common:e,constants:t}=E.core,t={GroupId:s[0].conversationID.replace(t.OuterConstant.CONV_GROUP,""),MsgSeqList:s.map(e=>({MsgSeq:e.sequence}))};return e.buildAndSendPacket({servcmd:"group_open_http_svc.group_msg_receipt",data:t})})}(s),{code:0,data:{}}}catch(e){let{errorCode:t,errorInfo:s}=e;throw new r.ChatError({code:t,message:s})}})}getMessageReadReceiptList(i){return I(this,void 0,void 0,function*(){let{common:r,constants:t}=this._core;try{let e=i[0]["conversationType"];if(e===t.OuterConstant.CONV_GROUP){let s=this._filterValidMessageSendByMe(i);if(0<(null==s?void 0:s.length)){let e=yield function(s){return I(this,void 0,void 0,function*(){var{common:e,constants:t}=E.core,t={GroupId:s[0].conversationID.replace(t.OuterConstant.CONV_GROUP,""),MsgSeqList:s.map(e=>({MsgSeq:e.sequence}))};return e.buildAndSendPacket({servcmd:"group_open_http_svc.get_group_msg_receipt",data:t})})}(s),t=(e||{})["GroupMsgReceiptList"];this._updateGroupMessagesReadReceiptInfo({messageList:i,readReceiptList:t})}}return{code:0,data:{messageList:i}}}catch(e){let{errorCode:t,errorInfo:s}=e;throw new r.ChatError({code:t,message:s})}})}getGroupMessageReadMemberList(n){return I(this,void 0,void 0,function*(){let{constants:e,common:r}=this._core,{message:t,filter:o=jr.READ,cursor:s=""}=n,{conversationID:i,sequence:a,ID:l}=t,u=i.replace(e.OuterConstant.CONV_GROUP,""),c=100<=n.count?100:n.count;try{let n=yield function(n){return I(this,void 0,void 0,function*(){var{sequence:e,groupID:t,filter:s,cursor:r,count:i}=n,e={MsgSeq:e,GroupId:t,Filter:s,Cursor:r,Num:i};return E.core.common.buildAndSendPacket({servcmd:"group_open_http_svc.get_group_msg_receipt_detail",data:e})})}({groupID:u,sequence:a,filter:o,cursor:s,count:c});if(n){let{Cursor:e,IsFinish:t,UnreadList:s,ReadList:r}=n,i={cursor:e,isCompleted:1===t,messageID:l,unreadUserIDList:[],readUserIDList:[]};return o===jr.READ?i.readUserIDList=r.map(e=>e.Read_Account):o===jr.UNREAD&&(i.unreadUserIDList=s.map(e=>e.Unread_Account)),{code:0,data:i}}}catch(e){let{errorCode:t,errorInfo:s}=e;throw new r.ChatError({code:t,message:s})}})}_handleC2CMessageReadReceipt(e){let i=[],{constants:t,helper:s}=this._core,{C2cMsgInfo:n,PeerReadTime:o,Peer_Account:a}=e;if(!s.isEmpty(n)){let r=""+t.OuterConstant.CONV_C2C+a;null!=n&&n.forEach(e=>{var{TinyId:e,MsgClientTime:t,MsgRandom:s}=e,e=e+`-${t}-`+s,t=$r({conversationID:r,messageID:e});t&&!t.readReceiptInfo.isPeerRead&&(t.readReceiptInfo.isPeerRead=!0,t.readReceiptInfo.timestamp=o,i.push({userID:a,messageID:e,isPeerRead:!0,timestamp:o}))}),this._emitReadReceiptEventIfNeed(i)}}_updateGroupMessagesReadReceiptInfo(e){let{messageList:t,readReceiptList:s}=e,r=new Map;t.forEach(e=>{r.set(e.sequence,e)}),null!=s&&s.forEach(e=>{var t,s;0===e.Code&&({MsgSeq:e,ReadNum:t,UnreadNum:s}=e,e=r.get(e))&&(e.readReceiptInfo.readCount=t,e.readReceiptInfo.unreadCount=s)})}_handleGroupMessageReadReceipt(e){let a=[],s=this._core["constants"],t=e["GroupTips"];t.forEach(e=>{let{MsgBody:{GroupMsgReceiptList:t},GroupInfo:{GroupId:n}}=e,o=""+s.OuterConstant.CONV_GROUP+n;null!=t&&t.forEach(e=>{var{TinyId:e,MsgClientTime:t,MsgRandom:s,ReadNum:r,UnreadNum:i}=e,e=e+`-${t}-`+s,t=$r({conversationID:o,messageID:e}),s={groupID:n,messageID:e,readCount:0,unreadCount:0};t&&("number"==typeof r&&(t.readReceiptInfo.readCount=r,s.readCount=r),"number"==typeof i&&(t.readReceiptInfo.unreadCount=i,s.unreadCount=i),a.push(s))})}),this._emitReadReceiptEventIfNeed(a)}_emitReadReceiptEventIfNeed(e){var{notificationCenter:t,OuterEvent:s}=this._core;0<e.length&&t.emitOuterEvent(s.MESSAGE_READ_RECEIPT_RECEIVED,{name:s.MESSAGE_READ_RECEIPT_RECEIVED,data:e})}_filterValidMessageSendByOther(e){return this._filterNeedReadReceiptMessages(e).filter(e=>{e=e.from;return e!==this._core.common.getCurrentUserID()})}_filterValidMessageSendByMe(e){let s=this._core.constants["OuterConstant"];return this._filterNeedReadReceiptMessages(e).filter(e=>{var{from:e,status:t}=e;return e===this._core.common.getCurrentUserID()&&t===s.MessageStatus.SUCCESS})}_filterNeedReadReceiptMessages(e){return e.filter(e=>!0===e.needReadReceipt)}dispose(){var{InnerEvent:{MESSAGE_PUSH:e},InnerEventSubType:{C2C_MESSAGE_READ_RECEIPT:t,GROUP_MESSAGE_READ_RECEIPT:s},notificationCenter:r}=this._core;r.unSubscribeInnerEvent(e,t,this._handleC2CMessageReadReceipt,this),r.unSubscribeInnerEvent(e,s,this._handleGroupMessageReadReceipt,this)}};function Zr(o,a,l){return I(this,void 0,void 0,function*(){var{buildAndSendPacket:e}=E.core["common"],{from:t,to:s,clientSequence:r,random:i,time:n}=o;return e({servcmd:"openim_msg_ext_http_svc.set_key_values",data:{From_Account:t,To_Account:s,MsgKey:r+`_${i}_`+n,OperateType:l,ExtensionList:a}})})}function ei(r,i,n){return I(this,void 0,void 0,function*(){var{buildAndSendPacket:e}=E.core["common"],{to:t,sequence:s}=r;return e({servcmd:"openim_msg_ext_http_svc.group_set_key_values",data:{GroupId:t,MsgSeq:s,OperateType:n,ExtensionList:i}})})}var ti=new class{constructor(){this._messageExtensionsMap=new Map,this._extensionsLatestSequenceMap=new Map,this._completedFetchExtensions=new Set}init(e){var{notificationCenter:e,helper:{registerApi:t},InnerEvent:{MESSAGE_PUSH:s,LOGOUT:r},InnerEventSubType:{MESSAGE_EXTENSIONS_UPDATED:i}}=this._core=e;t({apiName:"setMessageExtensions",context:this}),t({apiName:"getMessageExtensions",context:this}),t({apiName:"deleteMessageExtensions",context:this}),e.subscribeInnerEvent(s,i,this._handleMessageExtensionsNotify,this),e.subscribeInnerEvent(r,this.reset,this)}setMessageExtensions(c,d){return I(this,void 0,void 0,function*(){this._validateMessageExtensionBusinessCapability("setMessageExtensions");let{constants:{OuterConstant:e},ssoLog:t}=this._core,{ID:s,conversationID:r,sequence:i,time:n,conversationType:o}=c,a=d;20<d.length&&(a=d.slice(0,20),t.warn("setMessageExtensions","the length of extensions cannot exceed 20"));var l=this._generateServerExtensions(c,a),u=`convID:${r} messageID:${s} sequence:${i} time:${n} count:`+a.length;try{let r;if(o===e.CONV_C2C?r=yield Zr(c,l,1):o===e.CONV_GROUP&&(r=yield ei(c,l,1)),r){let{resultList:e,successCount:t,failureCount:s}=this._handleModifyMessageExtensions(c,r);return{code:0,data:{extensions:e},successLog:{message:u+` successCount:${t} failCount:`+s}}}return{code:0,data:{extensions:[]}}}catch(e){let t=e["errorCode"];throw new this._core.helper.ChatError({functionName:"setMessageExtensions",code:t,moreMessage:u})}})}getMessageExtensions(o){return I(this,void 0,void 0,function*(){let{isUndefined:s}=this._core["utils"],{conversationID:e,ID:r,sequence:t,time:i}=(this._validateMessageExtensionBusinessCapability("getMessageExtensions"),o),n=`convID:${e} messageID:${r} sequence:${t} time:`+i;try{let e,t=(this._completedFetchExtensions.has(r)&&(e=this._extensionsLatestSequenceMap.get(r)),yield this._fetchMessageExtensions(o,e));return s(e)&&1<t.length&&this._completedFetchExtensions.add(r),{code:0,data:{extensions:t},successLog:{message:n}}}catch(e){let{errorCode:t,errorInfo:s=""}=e||{};throw new this._core.common.ChatError({code:t,message:s,moreMessage:n})}})}deleteMessageExtensions(d,h){return I(this,void 0,void 0,function*(){this._validateMessageExtensionBusinessCapability("deleteMessageExtensions");let{utils:{isEmpty:e},constants:{OuterConstant:t}}=this._core,{conversationType:s,conversationID:r,sequence:i,ID:n,time:o}=d,a=3,l=[];e(h)||(a=2,null==h)||h.forEach(e=>{l.push({key:e,value:"",seq:0})});var u=`convID:${r} messageID:${n} sequence:${i} time:${o} operateType:`+a,c=this._generateServerExtensions(d,l);try{let r;if(s===t.CONV_C2C?r=yield Zr(d,c,a):s===t.CONV_GROUP&&(r=yield ei(d,c,a)),r){let{resultList:e,successCount:t,failureCount:s}=this._handleModifyMessageExtensions(d,r);return{code:0,data:{extensions:e},successLog:{message:u+`successCount:${t} failCount:`+s}}}return{code:0,data:{extensions:[]}}}catch(e){let t=e["errorCode"];throw new this._core.helper.ChatError({functionName:"deleteMessageExtensions",code:t,moreMessage:u})}})}reset(){this._messageExtensionsMap.clear(),this._extensionsLatestSequenceMap.clear(),this._completedFetchExtensions.clear()}dispose(){this.reset();var{notificationCenter:e,InnerEvent:{MESSAGE_PUSH:t,LOGOUT:s},InnerEventSubType:{MESSAGE_EXTENSIONS_UPDATED:r}}=this._core;e.unSubscribeInnerEvent(t,r,this._handleMessageExtensionsNotify,this),e.subscribeInnerEvent(s,this.reset,this)}_handleModifyMessageExtensions(e,t){let s=e["ID"],r=t["Seq"],i=t.ExtensionList||[],n=[],o=0,a=0,l=[];return i.forEach(e=>{var{ErrorCode:e,Extension:t}=e,{Key:t,Value:s,Seq:r}=t;n.push({code:e,key:t,value:s}),0===e?o++:a++,l.push({key:t,value:s,seq:r})}),this._extensionsLatestSequenceMap.set(s,r),0<l.length&&this._updateLocalExtensions(e.ID,l),{resultList:n,successCount:o,failureCount:a}}_updateLocalExtensions(e,t){this._messageExtensionsMap.has(e)||this._messageExtensionsMap.set(e,new Map);let r=this._messageExtensionsMap.get(e);null!=t&&t.forEach(e=>{var{key:e,seq:t,value:s=""}=e;null!=r&&r.set(e,{value:s,seq:t})})}_fetchMessageExtensions(l,s){return I(this,void 0,void 0,function*(){let{constants:{OuterConstant:e},utils:{isEmpty:o}}=this._core;try{let n;var{conversationType:t,ID:a}=l;if(t===e.CONV_C2C?n=yield function(e,t){var s=E.core["common"]["buildAndSendPacket"],{from:e,to:r,clientSequence:i,random:n,time:o}=e;return s({servcmd:"openim_msg_ext_http_svc.get_key_values",data:{From_Account:e,To_Account:r,MsgKey:i+`_${n}_`+o,StartSeq:t}})}(l,s):t===e.CONV_GROUP&&(n=yield function(e,t){var s=E.core["common"]["buildAndSendPacket"],{to:e,sequence:r}=e;return s({servcmd:"openim_msg_ext_http_svc.group_get_key_values",data:{GroupId:e,MsgSeq:r,StartSeq:t}})}(l,s)),n){let{LatestSeq:e,ClearSeq:t,CompleteFlag:s}=n,r=(n.ExtensionList||[]).map(e=>({key:e.Key,value:e.Value,seq:e.Seq}));if(this._updateLocalExtensions(a,r),this._clearLocationExtensions(a,t),this._extensionsLatestSequenceMap.set(a,e),1!==s){let e=r[r.length-1].seq+1;return this._fetchMessageExtensions(l,e)}let i=[];if(this._messageExtensionsMap.has(a)){let e=this._messageExtensionsMap.get(a);null!=e&&e.forEach((e,t)=>{e=e.value;o(e)||i.push({key:t,value:e})})}return i}}catch(e){throw e}})}_clearLocationExtensions(e,r){if(!(r<=0)&&this._messageExtensionsMap.has(e)){let s=this._messageExtensionsMap.get(e);null!=s&&s.forEach((e,t)=>{e.seq<=r&&s.delete(t)})}}_generateServerExtensions(e,t){var s=e["ID"];if(this._messageExtensionsMap.has(s)){let r=this._messageExtensionsMap.get(s);return t.map(e=>{var{key:e,value:t}=e;let s=0;return{Key:e,Value:t,Seq:s=null!=r&&r.has(e)?null==(t=r.get(e))?void 0:t.seq:s}})}return t.map(e=>({Key:e.key,Value:e.value,Seq:0}))}_validateMessageExtensionBusinessCapability(e){var{helper:t,constants:s}=this._core;if(!t.checkBusinessCapabilityBits("MSG_EXT"))throw new t.ChatError({functionName:e,code:s.ERROR_CODE.NO_USE,replacement1:e})}_handleMessageExtensionsNotify(e){var{SetKVInfo:e,DeleteKVInfo:t,ClearKVInfo:s,MsgOptType:r,TinyId:i,MsgLastSeq:n,ExtensionC2cMsgInfo:o,ExtensionGroupMsgInfo:a}=(null==e?void 0:e.MsgExtensionNotify)||{},{MsgClientTime:o,MsgRandom:a}=o||a||{},i=i+`-${o}-`+a;this._extensionsLatestSequenceMap.set(i,n),1===r?this._handleMessageExtensionsUpdated({messageID:i,updateMessageExtensionsInfo:e}):2===r?this._handleMessageExtensionsDeleted({messageID:i,deleteMessageExtensionsInfo:t}):3===r&&this._handleMessageExtensionsCleared({messageID:i,clearMessageExtensionsInfo:s})}_handleMessageExtensionsUpdated(e){let{notificationCenter:t,OuterEvent:s}=this._core,{messageID:r,updateMessageExtensionsInfo:i=[]}=e,n=[];i.forEach(e=>{var{MsgKeyValue:e=[]}=e,e=e.map(e=>(n.push({key:e.Key,value:e.Value}),{key:e.Key,value:e.Value,seq:e.Seq}));this._updateLocalExtensions(r,e)}),t.emitOuterEvent(s.MESSAGE_EXTENSIONS_UPDATED,{name:s.MESSAGE_EXTENSIONS_UPDATED,data:{messageID:r,extensions:n}})}_handleMessageExtensionsDeleted(e){let{notificationCenter:t,OuterEvent:s}=this._core,{messageID:r,deleteMessageExtensionsInfo:i=[]}=e,n=[];i.forEach(e=>{var{MsgKeyValue:e=[]}=e,e=e.map(e=>(n.push(e.Key),{key:e.Key,seq:e.Seq}));this._updateLocalExtensions(r,e)}),t.emitOuterEvent(s.MESSAGE_EXTENSIONS_DELETED,{name:s.MESSAGE_EXTENSIONS_DELETED,data:{messageID:r,keyList:n}})}_handleMessageExtensionsCleared(e){let{notificationCenter:t,OuterEvent:{MESSAGE_EXTENSIONS_DELETED:s},utils:{isEmpty:r}}=this._core,{messageID:i,clearMessageExtensionsInfo:n=[]}=e,o=[];n.forEach(e=>{let s=e["ClearMsgSeq"];this._messageExtensionsMap.has(i)&&(this._messageExtensionsMap.get(i)||[]).forEach((e,t)=>{e.seq<=s&&!r(e.value)&&o.push(t)}),this._clearLocationExtensions(i,s)}),t.emitOuterEvent(s,{name:s,data:{messageID:i,keyList:o}})}};let si={key:"message",required:!0,rules:["object"],allowEmpty:!1,customValidator:e=>{var{OuterConstant:t}=E.core["constants"];return e.status!==t.MessageStatus.SUCCESS?"message is not success":!0===e.isSupportExtension||"message is not support extension"}},ri={setMessageExtensions:[si,{key:"extensions",required:!0,rules:["array"],allowEmpty:!1}],getMessageExtensions:[si],deleteMessageExtensions:[si]},ii=Object.assign(Object.assign(Object.assign(Object.assign({deleteMessage:[{required:!0,rules:["array"],allowEmpty:!1}],revokeMessage:[{required:!0,rules:["object"],allowEmpty:!1}],resendMessage:[{key:"message",required:!0,rules:["object"],allowEmpty:!1},{key:"options",required:!1,rules:["object"],allowEmpty:!1}],getMessageList:{conversationID:{required:!0,rules:["string"],allowEmpty:!1},nextReqMessageID:{required:!1,rules:["string"],allowEmpty:!0},count:{required:!1,rules:["number"],allowEmpty:!0}},getMessageListHopping:{conversationID:{required:!0,rules:["string"],allowEmpty:!1},sequence:{required:!1,rules:["number"],allowEmpty:!0},direction:{required:!1,rules:["number"],allowEmpty:!0},count:{required:!1,rules:["number"],allowEmpty:!0}},createTextAtMessage:{to:{required:!0,rules:["string"],allowEmpty:!1},conversationType:{required:!0,rules:["string"],allowEmpty:!1,customValidator:e=>"GROUP"===e||"conversationType should be GROUP."},payload:{required:!0,rules:["object"],allowEmpty:!1,customValidator:e=>{var t="string"==typeof(null==e?void 0:e.text)&&("string"!=typeof e.text||0!==(null==(t=null==e?void 0:e.text)?void 0:t.length))||"payload.text is invalid.";return!0!==t?t:!(null!=e&&e.atUserList&&!Array.isArray(e.atUserList))||"atUserList should be an array or undefind."}}},findMessage:[{required:!0,rules:["string"],allowEmpty:!1}],translateText:{sourceTextList:{required:!0,rules:["array"],allowEmpty:!1},sourceLanguage:{required:!0,rules:["string"],allowEmpty:!1},targetLanguage:{required:!0,rules:["string"],allowEmpty:!1}},createForwardMessage:{to:{required:!0,rules:["string"],allowEmpty:!1},conversationType:{required:!0,rules:["string"],allowEmpty:!1,customValidator:e=>!(!e.startsWith("C2C")&&!e.startsWith("GROUP"))||"conversationType is invalid."},payload:{required:!0,rules:["object"],allowEmpty:!1}},createLocationMessage:{to:{required:!0,rules:["string"],allowEmpty:!1},conversationType:{required:!0,rules:["string"],allowEmpty:!1},payload:{required:!0,rules:["object"],allowEmpty:!1,customValidator:e=>{var{isString:t,isNumber:s}=E.core["utils"];return t(null==e?void 0:e.description)?s(null==e?void 0:e.longitude)?!!s(null==e?void 0:e.latitude)||"payload.latitude must be a number.":"payload.longitude must be a number.":"payload.description must be a string."}}}},{addMessageReaction:[{key:"message",required:!0,rules:["object"],allowEmpty:!1},{key:"reactionID",required:!0,rules:["string"],allowEmpty:!1}],removeMessageReaction:[{key:"message",required:!0,rules:["object"],allowEmpty:!1},{key:"reactionID",required:!0,rules:["string"],allowEmpty:!1}],getMessageReactions:{messageList:{required:!0,rules:["array"],allowEmpty:!1},maxUserCountPerReaction:{required:!1,rules:["number"],allowEmpty:!0,customValidator:e=>"number"!=typeof e?"maxUserCountPerReaction is invalid.":!(e<0||10<e)||"maxUserCountPerReaction should between [0, 10]."}},getAllUserListOfMessageReaction:{message:{required:!0,rules:["object"],allowEmpty:!1,customValidator:e=>"success"===e.status||"message is invalid."},reactionID:{required:!0,rules:["string"],allowEmpty:!1},nextSeq:{required:!1,rules:["number"],allowEmpty:!0},count:{required:!1,rules:["number"],allowEmpty:!0}}}),{sendMessageReadReceipt:[{required:!0,rules:["array"],allowEmpty:!1}],getMessageReadReceiptList:[{required:!0,rules:["array"],allowEmpty:!1}],getGroupMessageReadMemberList:{message:{required:!0,rules:["object"],allowEmpty:!1},filter:{required:!1,rules:["number"],allowEmpty:!0},count:{required:!1,rules:["number"],allowEmpty:!0},cursor:{required:!1,rules:["string"],allowEmpty:!0}}}),ri),{pinGroupMessage:{groupID:{required:!0,rules:["string"],allowEmpty:!1},message:{required:!0,rules:["object"],allowEmpty:!1},isPinned:{required:!0,rules:["boolean"],allowEmpty:!1}},getPinnedGroupMessageList:[{key:"groupID",required:!0,rules:["string"],allowEmpty:!1}]}),ni=Object.assign(Object.assign(Object.assign(Object.assign({deleteMessage:!0,revokeMessage:!0,resendMessage:!0,getMessageList:!0,getMessageListHopping:!0,createTextAtMessage:!0,findMessage:!0,translateText:!0,createForwardMessage:!0,createLocationMessage:!0},{addMessageReaction:!0,removeMessageReaction:!0,getMessageReactions:!0,getAllUserListOfMessageReaction:!0}),{sendMessageReadReceipt:!0,getMessageReadReceiptList:!0,getGroupMessageReadMemberList:!0}),{setMessageExtensions:!0,getMessageExtensions:!0,deleteMessageExtensions:!0}),{pinGroupMessage:!0,getPinnedGroupMessageList:!0});class oi{constructor(e){this._core=e}deleteMessage(s){return I(this,void 0,void 0,function*(){var{to:e,messageIdentifiers:t}=s,e={From_Account:this._core.common.getCurrentUserID(),To_Account:e,MsgKeyList:t};return this._core.common.buildAndSendPacket({servcmd:"openim.delete_c2c_msg_ramble",data:e})})}revokeMessage(n){return I(this,void 0,void 0,function*(){var{to:e,from:t,sequence:s,time:r,random:i}=n;return this._core.common.buildAndSendPacket({servcmd:"openim.msgwithdraw",data:{MsgInfo:{From_Account:t,To_Account:e,MsgSeq:s,MsgRandom:i,MsgTimeStamp:r}}})})}}class ai{constructor(e){this._core=e}deleteMessage(s){return I(this,void 0,void 0,function*(){var{to:e,messageIdentifiers:t}=s,e={GroupId:e,Deleter_Account:this._core.common.getCurrentUserID(),Seqs:t};return this._core.common.buildAndSendPacket({servcmd:"group_open_http_svc.delete_group_ramble_msg_by_seq",data:e})})}revokeMessage(s){return I(this,void 0,void 0,function*(){var{to:e,sequence:t}=s;return this._core.common.buildAndSendPacket({servcmd:"group_open_http_svc.group_msg_recall",data:{GroupId:e,MsgSeqList:[{MsgSeq:t}]}})})}}class li{constructor(e){this._core=e}generateRevokeMessage(e){var{conversationID:e,sequence:t,random:s,tinyID:r,clientTime:i,revokeReason:n,revoker:o}=e;let a={};var l=this._core.message["messageDataHandler"];return(a=l.revokeMessage({conversationID:e,sequence:t,random:s,revoker:o}))||(a={conversationID:e,sequence:t},r&&i&&s&&(a.ID=r+`-${i}-`+s)),a.revoker=o,a.revokeReason=n,a.revokerInfo={userID:o,nick:"",avatar:""},a}updateRevokerInfo(t){return I(this,void 0,void 0,function*(){var e=t.map(e=>e.revoker);try{let s=yield this._fetchUserInfos(e);s&&t.forEach(e=>{var t=e["revoker"];s[t]&&(e.revokerInfo.nick=s[t].nick||"",e.revokerInfo.avatar=s[t].avatar||"",e.revokerInfo.userID=t)})}catch(e){console.debug(e)}})}_fetchUserInfos(t){return I(this,void 0,void 0,function*(){var e=yield null==(e=this._core.user.userProfile)?void 0:e.getUserProfile({userIDList:t});return null!=e&&e.data?null==(e=e.data)?void 0:e.reduce((e,{userID:t,nick:s,avatar:r})=>(e[t]={nick:s||"",avatar:r||""},e),{}):null})}}var ui=new class{constructor(){this._core=null,this._c2cMessageAction=null,this._groupMessageAction=null}init(e){this._core=e,this._groupMessageAction=new ai(e),this._c2cMessageAction=new oi(e),this._messageHelper=new li(e);e=e.helper;e.registerApi({apiName:"deleteMessage",context:this}),e.registerApi({apiName:"revokeMessage",context:this}),e.registerApi({apiName:"resendMessage",context:this}),e.registerApi({apiName:"findMessage",context:this})}deleteMessage(t){return I(this,void 0,void 0,function*(){let l=[],u=[],{conversationID:c,conversationType:d}=t[0],e=c.replace(d,"");if("@TIM#SYSTEM"===d)throw new this._core.helper.ChatError({code:2116});if(t.forEach(e=>{var{conversationID:t,conversationType:s,status:r,_onlineOnlyFlag:i,sequence:n,random:o,time:a}=e||{};if("success"===r&&t===c&&s===d){if(!i){let e="C2C"===s?n+`_${o}_`+a:String(n);l.push(e)}u.push(e)}}),0===l.length)return this._handleDeleteMessageSuccess(u),{code:0,data:{messageList:u}};30<l.length&&(l=l.slice(0,30),u=u.slice(0,30));try{return"C2C"===d?yield this._c2cMessageAction.deleteMessage({to:e,messageIdentifiers:l}):yield this._groupMessageAction.deleteMessage({to:e,messageIdentifiers:l}),this._handleDeleteMessageSuccess(u),{code:0,data:{messageList:u}}}catch(e){let t=e["errorCode"];throw new this._core.helper.ChatError({functionName:"deleteMessage",code:t})}})}revokeMessage(u){return I(this,void 0,void 0,function*(){var s;let{conversationType:e,isRevoked:t,ID:r,type:i,from:n,to:o}=u;var a,l=`type:${i} from:${n} to:${o} ID:`+r;if("@TIM#SYSTEM"===e)throw new this._core.helper.ChatError({message:"system message cannot be revoked"});if(t)throw new this._core.helper.ChatError({message:"message has been revoked",moreMessage:l});try{if(a="C2C"===e?yield this._c2cMessageAction.revokeMessage(u):yield this._groupMessageAction.revokeMessage(u)){let e=a["RecallRetList"],t=(null==(s=null==e?void 0:e[0])?void 0:s.RetCode)||0;if(0!==t)throw new this._core.helper.ChatError({code:t,moreMessage:l});return u.isRevoked=!0,yield this._handleRevokeMessageSuccess(u),{code:0,data:{message:u},successLog:{message:l}}}}catch(e){let t=e["errorCode"];throw new this._core.helper.ChatError({functionName:"revokeMessage",code:t,moreMessage:l})}})}resendMessage(t,s){return I(this,void 0,void 0,function*(){var e;return t.isResend=!0,t.status="unSend",null==(e=null==(e=this._core)?void 0:e.apiMap)?void 0:e.sendMessage(t,s)})}findMessage(e){return this._core.message.messageDataHandler.findMessage(e)}_handleDeleteMessageSuccess(i){if(0!==i.length){let{message:{messageDataHandler:s},common:{isTopic:e},notificationCenter:t,InnerEvent:r}=this._core;i.forEach(t=>{t.isDeleted=!0;var e=s.getLocalMessageList(t.conversationID);null!=e&&e.forEach(e=>{e.ID===t.ID&&(e.isDeleted=!0)})});var{conversationID:i=""}=i[0];e(i)?t.emitInnerEvent(r.TOPIC_MESSAGE_DELETED,i):t.emitInnerEvent(r.MESSAGE_DELETED,i)}}_handleRevokeMessageSuccess(i){return I(this,void 0,void 0,function*(){var e=null==(e=this._core.store.get("login"))?void 0:e.userId,{conversationID:t,sequence:s,random:r}=i;this._core.message.messageDataHandler.revokeMessage({conversationID:t,sequence:s,random:r,revoker:e}),yield this._messageHelper.updateRevokerInfo([i])})}};class ci{static parseServerPushElement(e){var{MsgContent:e={}}=e,{Index:e,Data:t}=e;return new ci({index:e,data:t})}constructor(e){this.type=Dr.MSG_FACE;var{index:e,data:t}=e;this.content={index:e,data:t}}validateBeforeSend(){var e;return"number"==typeof(null==(e=this.content)?void 0:e.index)&&"string"==typeof(null==(e=this.content)?void 0:e.data)?{isValid:!0}:{isValid:!1,error:{message:"content is invalid"}}}transformToServerFormat(e){var{isMergerMessage:e=!1}=e||{},{index:e,data:t}=e?this.payload:this.content;return{MsgType:this.type,MsgContent:{Index:e,Data:t}}}}class di{static parseServerPushElement(e){var{MsgContent:e={}}=e,{Desc:e,Longitude:t,Latitude:s}=e;return new di({description:e,longitude:t,latitude:s})}constructor(e){this.type=Dr.MSG_LOCATION;var{description:e,longitude:t,latitude:s}=e;this.content={description:e,longitude:t,latitude:s}}validateBeforeSend(){return{isValid:!0}}transformToServerFormat(e){var{isMergerMessage:e=!1}=e||{},{description:e,longitude:t,latitude:s}=e?this.payload:this.content;return{MsgType:this.type,MsgContent:{Desc:e,Longitude:t,Latitude:s}}}}var hi=new class{init(e){(this._core=e).message.messageFactory.registerElementClass(Dr.MSG_FACE,ci),e.message.messageFactory.registerElementClass(Dr.MSG_LOCATION,di),e.helper.registerApi({apiName:"createFaceMessage",context:this}),e.helper.registerApi({apiName:"createTextAtMessage",context:this}),e.helper.registerApi({apiName:"createForwardMessage",context:this}),e.helper.registerApi({apiName:"createLocationMessage",context:this})}createFaceMessage(e){var t,s;return e?({index:t,data:s}=(null==e?void 0:e.payload)||{},t=new ci({index:t,data:s}),s=this._core.common.getCurrentUserID(),(e=this._core.message.messageFactory.createMessage(Object.assign(Object.assign({},e),{from:s}))).setElement(t),e):null}createTextAtMessage(e){let r=((null==e?void 0:e.payload)||{})["atUserList"],i=this._core.apiMap.createTextMessage(e),n=this._core["OuterConstant"];if(!i)return null;if(Array.isArray(r)){let t=[],s=[];r.forEach(e=>{e!==n.MSG_AT_ALL?(t.push({GroupAtAllFlag:0,GroupAt_Account:e}),s.push(e)):(t.push({GroupAtAllFlag:1}),s.push(n.MSG_AT_ALL))}),i._groupAtInfoList=t,i.atUserList=s}return i}createForwardMessage(e){var{helper:t,OuterConstant:s}=this._core,{to:e,conversationType:r,priority:i,payload:n,needReadReceipt:o,receiverList:a,cloudCustomData:l="",isSupportExtension:u=!1}=e;if(!Array.isArray(n._elements))throw new t.ChatError({functionName:"createForwardMessage",code:2454});if(n.type===s.MSG_GRP_TIP)throw new t.ChatError({functionName:"createForwardMessage",code:2453});s=this._core.common.getCurrentUserID(),t=this._core.message.messageFactory.createMessage({to:e,from:s,conversationType:r,isPlaceMessage:0,priority:i,payload:n,needReadReceipt:o,isSupportExtension:u,cloudCustomData:l,receiverList:a});return t.setRelayFlag(!0),t.setElement(n._elements[0]),t}createLocationMessage(e){var t,s,r;return e?({description:t,longitude:s,latitude:r}=(null==e?void 0:e.payload)||{},t=new di({description:t,longitude:s,latitude:r}),s=this._core.common.getCurrentUserID(),(r=this._core.message.messageFactory.createMessage(Object.assign(Object.assign({},e),{from:s}))).setElement(t),r):null}};let gi=class{init(e){this._messageHelper=new li(e);var{notificationCenter:e,InnerEvent:{MESSAGE_PUSH:t},InnerEventSubType:{C2C_REVOKED_MESSAGE:s},helper:{registerWorkflowStep:r},constants:{WORKFLOW_NAME:i,WORKFLOW_STEP:n}}=this._core=e;e.subscribeInnerEvent(t,s,this._handleC2CNotifyMessage,this),r(i.SYNC_SERVER_INFO_AFTER_RE_ONLINE,n.HANDLE_C2C_REVOKED_MESSAGE_FROM_SYNC_UNREAD,this._handleC2CRevokeMessagesFromUnreadMessageSync,this)}_handleC2CNotifyMessage(e){e=e.C2cNotifyMsgArray;null!=e&&e.forEach(e=>{Object.keys(e).includes("WithdrawC2cMsgNotify")&&this._handleC2CRevokeMessage(e)})}_handleC2CRevokeMessage(t){return I(this,void 0,void 0,function*(){try{var{C2cWithdrawInfoArray:e}=t["WithdrawC2cMsgNotify"];yield this._parseAndEmitC2CRevokedMessages(e)}catch(e){console.debug(e)}})}_parseAndEmitC2CRevokedMessages(s){return I(this,void 0,void 0,function*(){let a=[],{notificationCenter:e,OuterEvent:t,common:{getCurrentUserID:l}}=this._core;s.forEach(e=>{var{MsgRand:t,MsgSeq:s,To_Account:r,From_Account:i,RevokerInfo:{Revoker_Account:n,Revoke_Reason:o}}=e,r=l()===i?"C2C"+r:"C2C"+i,e=(null==(i=null==e?void 0:e.RevokerInfo)?void 0:i.Reason)||o,i=this._messageHelper.generateRevokeMessage({conversationID:r,sequence:s,random:t,revoker:n,revokeReason:e});a.push(i)}),0<a.length&&(yield this._messageHelper.updateRevokerInfo(a),e.emitOuterEvent(t.MESSAGE_REVOKED,{name:t.MESSAGE_REVOKED,data:a}))})}_handleC2CRevokeMessagesFromUnreadMessageSync(t){return I(this,void 0,void 0,function*(){var e=t.result["revokedMessageList"];yield this._parseAndEmitC2CRevokedMessages(e)})}dispose(){var{notificationCenter:e,InnerEvent:{MESSAGE_PUSH:t},InnerEventSubType:{C2C_REVOKED_MESSAGE:s}}=this._core;e.unSubscribeInnerEvent(t,s,this._handleC2CNotifyMessage,this)}},pi=class{init(e){this._messageHelper=new li(e);var{notificationCenter:e,InnerEvent:{MESSAGE_PUSH:t},InnerEventSubType:{GROUP_MESSAGE_REVOKED:s}}=this._core=e;e.subscribeInnerEvent(t,s,this._handleGroupNotifyMessage,this)}_handleGroupNotifyMessage(e){e=e.GroupTips;null!=e&&e.forEach(e=>{var t;Array.isArray(null==(t=null==e?void 0:e.MsgBody)?void 0:t.GroupWithdrawInfoArray)&&this._handleGroupRevokeMessage(e)})}_handleGroupRevokeMessage(n){return I(this,void 0,void 0,function*(){try{let{RevokerInfo:l,MsgBody:{GroupWithdrawInfoArray:e},GroupInfo:u}=n,c=[],d=[],{notificationCenter:t,OuterEvent:s,utils:{isEmpty:r},common:{isCommunity:i}}=this._core,h=!1;u&&(h=i({groupID:u.GroupId})||!r(u.TopicId)),e.forEach(e=>{var{Random:e,MsgSeq:t,GroupId:s,MsgClientTime:r,TinyId:i,TopicId:n,RevokerInfo:{Revoker_Account:o=(null==l?void 0:l.Revoker_Account)||"",Reason:a=(null==l?void 0:l.Reason)||""}}=e,n=this._messageHelper.generateRevokeMessage({conversationID:n?"GROUP"+n:"GROUP"+s,sequence:t,random:e,tinyID:i,clientTime:r,revoker:o,revokeReason:a});(h?(n.revokerInfo.nick=u.From_AccountNick,n.revokerInfo.avatar=u.From_AccountHeadurl,c):d).push(n)}),0<d.length&&(yield this._messageHelper.updateRevokerInfo(d),c.push(...d)),0!==c.length&&t.emitOuterEvent(s.MESSAGE_REVOKED,{name:s.MESSAGE_REVOKED,data:c})}catch(e){console.debug(e)}})}dispose(){var{notificationCenter:e,InnerEvent:{MESSAGE_PUSH:t},InnerEventSubType:{GROUP_MESSAGE_REVOKED:s}}=this._core;e.unSubscribeInnerEvent(t,s,this._handleGroupNotifyMessage,this)}};var _i=new class{constructor(){this._c2cMessageReceiver=new gi,this._groupMessageReceiver=new pi}init(e){this._c2cMessageReceiver.init(e),this._groupMessageReceiver.init(e)}dispose(){this._c2cMessageReceiver.dispose(),this._groupMessageReceiver.dispose()}};class mi{constructor(e){var t=(this._core=e)["constants"];this._messageHelper=new li(e),e.helper.registerWorkflowStep(t.WORKFLOW_NAME.SYNC_SERVER_INFO_AFTER_RE_ONLINE,t.WORKFLOW_STEP.GROUP_REVOKED_NOTICE_RECOVER,this._recoverGroupRevokeNotice,this)}getRoamingMessagesByAnchor(e){return this._core.message.messageHistory.getGroupRoamingMessagesByAnchor(e)}_recoverGroupRevokeNotice(e){let{recoverRevokeNoticeGroupIDList:t=[]}=e.result,r=this._filterValidGroupIDList(t);0!==r.length&&(e=Math.min(Math.ceil(r.length/10),5),Promise.all(Array.from({length:e},(e,t)=>{var t=10*t,s=Math.min(10+t,r.length);return this._fetchGroupRevokeNotice(r.slice(t,s))})).catch(e=>console.error(e)))}_fetchGroupRevokeNotice(s){return I(this,void 0,void 0,function*(){var e;try{var t=yield function(n){return I(this,void 0,void 0,function*(){let{appStore:e,constants:{OuterConstant:s},common:r}=E.core,i=e.groupStore.getGroupMap(),t={NotifyReqList:n.map(e=>{var t=i.get(e);return{NotifyType:1,Limit:20,Type:r.isCommunity({type:t.type,groupID:e})?s.GRP_COMMUNITY:void 0,GroupId:e,BeginTime:(null==t?void 0:t._lastRevokedTime)||0,EndTime:1e3*E.core.common.timeManager.getServerTimeMs()}})||[]};return r.buildAndSendPacket({servcmd:"group_open_http_svc.batch_get_group_notify",data:t})})}(s);if(t){let s=[];null!=(e=null==t?void 0:t.NotifyRspList)&&e.forEach(e=>{var{GroupId:e,NotifyMsgList:t}=e,e=this._parseServerRevokeMessageList({groupID:e,serverRevokeMessageList:t});s.push(...e)}),0!==s.length&&(yield this._emitMessageRevokedEvent(s))}}catch(e){console.error(e)}})}_parseServerRevokeMessageList(e){let{serverRevokeMessageList:t,groupID:o}=e,a=[];return null!=t&&t.forEach(e=>{var{ClientTime:e,MsgSeq:t,Random:s,RevokerInfo:{Revoker_Account:r="",Reason:i=""}}=e,n="GROUP"+o,n=this._messageHelper.generateRevokeMessage({conversationID:n,sequence:t,random:s,clientTime:e,revoker:r,revokeReason:i});a.push(n)}),a}_filterValidGroupIDList(e){let{OuterConstant:t}=this._core["constants"],s=this._core.appStore.groupStore.getGroupMap();return(null==e?void 0:e.filter(e=>{return!(!s.has(e)||(null==(e=s.get(e))?void 0:e.type)===t.GRP_AVCHATROOM||null!=e&&e.isSupportTopic)}))||[]}_emitMessageRevokedEvent(s){return I(this,void 0,void 0,function*(){var{notificationCenter:e,OuterEvent:t}=this._core;yield this._messageHelper.updateRevokerInfo(s),e.emitOuterEvent(t.MESSAGE_REVOKED,{name:t.MESSAGE_REVOKED,data:s})})}}class vi{constructor(e){this._historyMessageListFetchAnchors=new Map,this._core=e,this._messageHelper=new li(e)}getRoamingMessagesByAnchor(p){return I(this,void 0,void 0,function*(){var i;try{var{conversationID:n,count:e,messageID:r,time:o,direction:a}=p;let t=o,s="";if(!o){let e=r?this._core.message.messageDataHandler.findMessage(r):null;if(t=(null==e?void 0:e.time)||0,r&&this._historyMessageListFetchAnchors.has(n)){let e=this._historyMessageListFetchAnchors.get(n);t=e.lastMessageTime,s=e.messageKey}}var l=n.replace(Kr,""),u=yield function(n){return I(this,void 0,void 0,function*(){var{peerAccount:e,count:t,lastMessageTime:s,messageKey:r,direction:i}=n,e={Peer_Account:e,MaxCnt:t,WithRecalledMsg:1,LastMsgTime:s,MsgKey:r,GetDirection:i};return E.core.common.buildAndSendPacket({servcmd:"openim.getroammsg",data:e})})}({count:e,lastMessageTime:t,messageKey:s,peerAccount:l,direction:a});if(u){let{MsgList:t=[],Complete:e,MsgKey:s,LastMsgTime:r}=u;this._historyMessageListFetchAnchors.set(n,{messageKey:s,lastMessageTime:r});var c=[];for(let e=0;e<t.length;e++){var d=t[e],h=this._parseMessage(d);c.push(h)}var g=this._core.message.messageHelper.filterValidMessages(c);return{messageList:g,nextReqMessageIDFromServer:null==(i=g[0])?void 0:i.ID,lastMessageTime:r,hasNoMoreHistoryMessage:1===e}}}catch(e){throw new this._core.helper.ChatError({code:null==e?void 0:e.code})}})}clearHistoryMessageListFetchAnchors(e){this._historyMessageListFetchAnchors.delete(e)}reset(){this._historyMessageListFetchAnchors.clear()}_parseMessage(e){Kr;var e=this._core.message.messageHelper.parseServerPushMessage(e),t=this._core.message.messageFactory.createMessage(Object.assign(Object.assign({},e),{conversationType:"C2C",flow:"in"}));return t.setElement(e.elements),t}}var fi=new class{constructor(){this._clearedConversations=new Set,this._fetchedCompleteConversations=new Set}init(e){this._core=e,this._groupMessageHistory=new mi(e),this._c2cMessageHistory=new vi(e),this._messageHelper=new li(e),e.helper.registerApi({apiName:"getMessageList",context:this}),e.helper.registerApi({apiName:"getMessageListHopping",context:this}),e.helper.registerApi({apiName:"clearHistoryMessage",context:this})}getMessageList(e){return I(this,void 0,void 0,function*(){try{var{conversationID:t,nextReqMessageID:s}=e;if("@TIM#SYSTEM"===t)return{code:0,data:{messageList:[],isCompleted:!1,nextMessageSeq:""}};var r=this._getAvailableLocalMessagesCount({conversationID:t,nextReqMessageID:s});if(this._needFetchHistoryMessageList({conversationID:t,availableLocalMessagesCount:r,targetCount:20})){let e=null;if(t.startsWith(Hr)?e=yield this._groupMessageHistory.getRoamingMessagesByAnchor({conversationID:t,sequence:Number(s),count:20,direction:br.FORWARD}):t.startsWith(Kr)&&(e=yield this._c2cMessageHistory.getRoamingMessagesByAnchor({conversationID:t,messageID:s,count:20,direction:br.FORWARD})),e){var{nextReqMessageIDFromServer:i,hasNoMoreHistoryMessage:n,messageList:o}=e,a=this._core.message.messageDataHandler.prependLocalMessageList({messageList:o,conversationID:t}),l=t,{appStore:u,message:c,OuterConstant:d}=E.core,u=u.conversationStore.getConversation(l),h=c.messageDataHandler.getLocalMessageList(l);if(u&&0!==h.length&&l!==d.CONV_SYSTEM){var g=[];for(let e=0;e<h.length;e++)"in"!==h[e].flow?"out"!==h[e].flow||h[e].isRead||h[e].setIsRead(!0):g.push(h[e]);let t=0;if(u.type===d.CONV_C2C){let e=g.slice(-u.unreadCount).filter(e=>e.isRevoked).length;t=g.length-u.unreadCount-e}else t=g.length-u.unreadCount;for(let e=0;e<t&&!g[e].isRead;e++)g[e].setIsRead(!0)}yield Yr(t),t.startsWith(Kr)&&(yield Wr({messageList:o,conversationID:t}));var p=this._core.message.messageDataHandler.getLocalMessageList(t).slice(0,a.length+r),_=p.filter(e=>e.isRevoked),m=(yield this._messageHelper.updateRevokerInfo(_),n&&this._fetchedCompleteConversations.add(t),{nextReqMessageID:n?"":String(i),messageList:p,isCompleted:n}),v=p.map(e=>e.sequence);return{code:0,data:m,successLog:{message:`conversationID: ${t} nextReqMessageID: ${s} availableLocalMessagesCount: ${r} sequenceList: `+JSON.stringify(v)}}}return{code:0,data:{messageList:[],isCompleted:!1,nextReqMessageID:""}}}return{code:0,data:yield this._getMessageListFromMemory({conversationID:t,nextReqMessageID:s,count:20}),successLog:{message:`conversationID: ${t} nextReqMessageID: ${s} availableLocalMessagesCount: ${r}}`}}}catch(e){throw new this._core.helper.ChatError({code:null==e?void 0:e.code})}})}getMessageListHopping(r){return I(this,void 0,void 0,function*(){var n,o;let{conversationID:e,sequence:a,time:t,direction:l=br.FORWARD}=r,u=this._core.helper["isEmpty"];if(![br.BACKWARD,br.FORWARD].includes(l))throw new this._core.helper.ChatError({message:"direction must be 0 or 1"});let{count:s=20}=r,c=(s=20<s?20:s,null);if(e.startsWith(Hr)){if(c=yield this._groupMessageHistory.getRoamingMessagesByAnchor({conversationID:e,sequence:a,count:s,direction:l})){let{nextReqMessageIDFromServer:t,hasNoMoreHistoryMessage:s,messageList:r,invisibleSequenceList:i}=c;if(this._core.message.messageDataHandler.storeSparseMessageList(r),l===br.FORWARD){let e=s&&t<1;return{code:0,data:{messageList:r,isCompleted:e,nextMessageSeq:e?"":t}}}if(l!==br.BACKWARD)return{code:0,data:c};{if(u(r)&&u(i))return{code:0,data:{messageList:[],isCompleted:!0,nextMessageSeq:""}};let e=(null==(n=null==r?void 0:r[r.length-1])?void 0:n.sequence)||0,t=(null==(o=null==i?void 0:i[i.length-1])?void 0:o.sequence)||0;return{code:0,data:{messageList:r.filter(e=>e.sequence>=a),isCompleted:!s,nextMessageSeq:s?Math.max(e,t)+1:""}}}}}else if(e.startsWith(Kr)&&(c=yield this._c2cMessageHistory.getRoamingMessagesByAnchor({conversationID:e,count:s+1,time:t,direction:l}))){let{messageList:e,lastMessageTime:t,hasNoMoreHistoryMessage:s}=c;return s||(l===br.FORWARD?e.shift():e.pop()),this._core.message.messageDataHandler.storeSparseMessageList(e),{code:0,data:{messageList:e,isCompleted:s,nextMessageTime:s?"":t}}}})}clearHistoryMessage(d){return I(this,void 0,void 0,function*(){let t,{appStore:e,common:{ChatError:s,getCurrentUserID:r},OuterConstant:{CONV_C2C:i,CONV_GROUP:n},message:o,apiMap:a}=this._core,l=e.conversationStore.getConversation(d);if(!l)throw new s({code:2500});var u={fromAccount:r()},c=l["type"];c===i?(u.type=1,u.toAccount=d.replace(i,"")):c===n&&(u.type=2,u.toGroupID=d.replace(n,""));try{yield null==(t=null==a?void 0:a.setMessageRead)?void 0:t.call(a,{conversationID:d});let e=yield function(i){return I(this,void 0,void 0,function*(){var{fromAccount:e,type:t,toAccount:s,toGroupID:r}=i,e={From_Account:e,Type:t,To_Account:s,ToGroupid:r};return E.core.common.buildAndSendPacket({servcmd:"recentcontact.clear_msg",data:e})})}(u);return e&&(o.messageDataHandler.deleteConversationMessageList(d),this._clearedConversations.add(d),this._fetchedCompleteConversations.delete(d),this._c2cMessageHistory.clearHistoryMessageListFetchAnchors(d),this._updateConversationLastMessage(d)),{code:0,data:{conversationID:d},successLog:{message:"convID:"+d}}}catch(t){let e=t["errorCode"];throw new this._core.helper.ChatError({functionName:"clearHistoryMessage",code:e,moreMessage:"convID:"+d})}})}_updateConversationLastMessage(e){var t=this._core["appStore"];t.conversationStore.updateConversation(e,{lastMessage:this._generateLastMessage()},{needSort:!0})}_getAvailableLocalMessagesCount({conversationID:e,nextReqMessageID:t}){var s=this._core.message.messageDataHandler.getLocalMessageList(e),r=s["length"];if(!t)return r;let i=-1;return null!=e&&e.startsWith(Kr)?i=s.findIndex(e=>e.ID===t):null!=e&&e.startsWith(Hr)&&(i=s.findIndex(e=>t.includes("-")?e.ID===t:String(e.sequence)===t)),-1===i?0:i}_needFetchHistoryMessageList({conversationID:e,availableLocalMessagesCount:t,targetCount:s}){return!!this._clearedConversations.has(e)||t<s&&!this._fetchedCompleteConversations.has(e)}_getMessageListFromMemory(e){return I(this,arguments,void 0,function*({conversationID:t,nextReqMessageID:s,count:e}){var r=this._core.message.messageDataHandler.getLocalMessageList(t),i=r.length;let n=i,o={isCompleted:!1,nextReqMessageID:"",messageList:[]},a=0,l=i;return s?(l=r.findIndex(e=>t.startsWith(Kr)?e.ID===s:String(e.sequence)===s),a=l>e?l-e:0,n=l):a=e<i?i-e:0,o.nextReqMessageID=0===a?"":this._generateNextReqMessageID({conversationID:t,targetIndex:a}),o.messageList=r.slice(a,l),o.isCompleted=n<=e,t.startsWith(Kr)&&(yield Yr(t),yield Wr({messageList:o.messageList,conversationID:t})),o})}_generateNextReqMessageID({conversationID:e,targetIndex:t}){var s=this._core.message.messageDataHandler.getLocalMessageList(e);return e.startsWith("C2C")?s[t].ID:String(s[t].sequence)}_generateLastMessage(){return{lastTime:0,lastSequence:0,fromAccount:"",messageForShow:"",payload:null,type:"",isRevoked:!1,cloudCustomData:"",onlineOnlyFlag:!1,nick:"",nameCard:"",version:0,isPeerRead:!1,revoker:null}}reset(){this._clearedConversations.clear(),this._fetchedCompleteConversations.clear(),this._c2cMessageHistory.reset()}dispose(){this.reset()}},Ii=new class{constructor(){this._core=null}init(e){e=(this._core=e).helper;e.registerApi({apiName:"translateText",context:this})}translateText(i){return I(this,void 0,void 0,function*(){try{var{sourceLanguage:t,sourceTextList:s,targetLanguage:e}=i,r=yield function(n,o){return I(this,void 0,void 0,function*(){var{sourceTextList:s,sourceLanguage:e,targetLanguage:t}=n,{store:r,common:i}=o,t={SourceText:s,Source:e,Target:t,FromAccount:null==(s=r.get("login"))?void 0:s.tinyID,SDKAppID:null==(e=r.get("instance"))?void 0:e.sdkAppId},s=yield i.buildAndSendPacket({servcmd:"im_open_translate.ws_batch_trans_text",data:t});if(s){let{CmdErrorCode:e,TargetText:t}=s;return{cmdErrorCode:e,translatedTextList:t}}})}({sourceLanguage:t,sourceTextList:s,targetLanguage:e},this._core);if(r){let{cmdErrorCode:{ErrorCode:e,ErrorInfo:t},translatedTextList:s}=r;if(0===e)return{code:0,data:{translatedTextList:s}};throw{errorCode:e,errorInfo:t,message:t}}}catch(e){var{errorCode:t,errorInfo:s}=e||{};throw new this._core.helper.ChatError({functionName:"translateText",code:t,message:s})}})}},Ei=new class{init(e){(this._core=e).helper.registerApi({apiName:"convertVoiceToText",context:this})}convertVoiceToText(s){return I(this,void 0,void 0,function*(){let{message:e,language:t=qr.ZH_PY}=s,r=(e.payload||{})["url"];var i=this._core.common.getCurrentUserID(),i=(e.from===i&&"out"===e.flow&&(r=e.payload.remoteAudioUrl),this._validateVoiceFormat(r),(null==(n=Br.exec(r))?void 0:n[1])||"mp3"),n=Vr[t]||xr;try{let s=yield function(e){var{store:t,common:s}=E.core,{url:e,format:r,serverLanguageType:i}=e,i={BytesUrl:e,BytesEngServiceType:i,BytesVoiceFormat:r,Uint32Sdkappid:null==(e=t.get("instance"))?void 0:e.sdkAppId,Uint64SourceType:0};return s.buildAndSendPacket({servcmd:"im_open_speech.ws_sentence_recognition",data:i})}({url:r,format:i,serverLanguageType:n});if(s){let{CmdErrorCode:e,BytesResult:t}=s;if(0===e.ErrorCode)return{code:0,data:{result:t}};throw{code:e.ErrorCode,message:e.ErrorInfo}}}catch(e){let{code:t,message:s}=e||{};throw new this._core.common.ChatError({functionName:"convertVoiceToText",code:t,message:s})}})}_validateVoiceFormat(e){if(!Br.test(e))throw new this._core.common.ChatError({code:2119})}};class Si{constructor(e){var{constants:t,common:s,utils:r}=E.core,{CONV_C2C:t,CONV_GROUP:i}=t.OuterConstant,{ID:e,tinyID:n,from:o,to:a,clientTime:s=s.timeManager.getServerTimeSeconds()||0,random:l,sequence:u,cloudCustomData:c="",nick:d="",avatar:h="",clientSequence:g,conversationType:p,groupID:_,_elements:m,time:v}=e,n=(this.ID=e||n+`-${s}-`+l,this.messageRandom=l,this.from=o,this.messageSender=o,this.time=v,this.messageSequence=u,this.clientSequence=g||u,this.clientTime=s,this.cloudCustomData=c,this.messageReceiver=a,this.avatar=h,this.nick=d,r.deepCopyWithMethods(m));n.forEach(e=>{e.payload=e.content,delete e.content}),this.messageBody=n,e?p.startsWith(t)?this.receiverUserID=a:p.startsWith(i)&&(this.receiverGroupID=a):_?(this.receiverGroupID=_,this.messageReceiver=_):a&&(this.receiverUserID=a,this.messageReceiver=a)}transformElementsToServerFormat(){return this.messageBody?Array.isArray(this.messageBody)?this.messageBody.map(e=>e.transformToServerFormat({isMergerMessage:!0})):this.messageBody.transformToServerFormat({isMergerMessage:!0}):null}}class Ci{static parseServerPushElement(e){var e=e["MsgContent"],{MsgList:e=[],CompatibleText:t,AbstractList:s,Title:r,PbMsgKey:i,JsonMsgKey:n}=e||{},e=e.map(e=>Jr(e));return new Ci({messageList:e,title:r,abstractList:s,compatibleText:t,pbDownloadKey:i,downloadKey:n})}constructor(e){this.type=E.core.constants.OuterConstant.MSG_MERGER;let{messageList:t,title:s,abstractList:r,compatibleText:i,pbDownloadKey:n="",downloadKey:o="",version:a=0,layersOverLimit:l=!1}=e,u=[];t.forEach(e=>{e&&(e=new Si(e),u.push(e))}),this.content={messageList:u,title:s,abstractList:r,compatibleText:i,version:a,downloadKey:o,pbDownloadKey:n,layersOverLimit:l}}validateBeforeSend(){var e=E.core.helper["isEmpty"];return e(this.content.messageList)?{isValid:!1,error:{message:"content is invalid"}}:{isValid:!0}}transformToServerFormat(e){var{isMergerMessage:e=!1}=e||{},{abstractList:e,compatibleText:t,downloadKey:s,layersOverLimit:r,pbDownloadKey:i,title:n,version:o,messageList:a}=e?this.payload:this.content;return{MsgType:this.type,MsgContent:{AbstractList:e,CompatibleText:t,JsonMsgKey:s,LayersOverLimit:r,PbMsgKey:i,Title:n,Version:o,MsgList:zr(a)}}}}var Mi=new class{init(e){let{message:t,helper:s,constants:{OuterConstant:r}}=this._core=e;t.messageFactory.registerElementClass(r.MSG_MERGER,Ci),s.registerApi({apiName:"createMergerMessage",context:this}),s.registerApi({apiName:"sendMessage",context:this,matcher:e=>e[0].type===r.MSG_MERGER}),s.registerApi({apiName:"downloadMergerMessage",context:this})}createMergerMessage(e){var t,s=this._core["common"];return e?(t=new Ci(e.payload),s=s.getCurrentUserID(),(e=this._core.message.messageFactory.createMessage(Object.assign(Object.assign({},e),{from:s}))).setRelayFlag(!0),e.setElement(t),e):null}sendMessage(a,l){return I(this,void 0,void 0,function*(){var e,t,s;try{var n=function(t){let e="utf-8";E.core.helper.IN_BROWSER&&document&&(e=document.charset.toLowerCase());let s,r=0,i;if(i=t.length,"utf-8"===e||"utf8"===e)for(let e=0;e<i;e++)(s=t.codePointAt(e))<=127?r+=1:s<=2047?r+=2:s<=65535?r+=3:(r+=4,e++);else if("utf-16"===e||"utf16"===e)for(let e=0;e<i;e++)(s=t.codePointAt(e))<=65535?r+=2:(r+=4,e++);else r=t.replace(/[^\x00-\xff]/g,"aa").length;return r}(JSON.stringify(a));let r=a,i=null;if(11264<n){r=this._core.utils.deepCopyWithMethods(a);try{let{JsonMsgKey:e,PbMsgKey:t}=yield function(t){return I(this,void 0,void 0,function*(){var e=t["payload"]["messageList"],e={MsgList:zr(e)};return E.core.common.buildAndSendPacket({servcmd:"im_long_msg.save_relay_json_msg",data:e})})}(r),s=r["payload"];i=new Ci(Object.assign(Object.assign({},s),{messageList:[],downloadKey:e,pbDownloadKey:t})),r.setElement(i)}catch(e){console.error(e)}}var{message:o}=(yield null==(s=null==(t=null==(e=this._core)?void 0:e.message)?void 0:t.messageSender)?void 0:s.sendMessage(r,l))["data"];return i&&o.setElement(a._elements),{code:0,data:{message:o}}}catch(e){let t=e["errorCode"];throw new this._core.helper.ChatError({code:t})}})}downloadMergerMessage(o){return I(this,void 0,void 0,function*(){let r=this._core["ssoLog"],e=o.payload,{downloadKey:i,pbDownload:t,type:s}=e,n=f(e,["downloadKey","pbDownload","type","messageList"]);try{let e=yield function(e){return I(this,void 0,void 0,function*(){return E.core.common.buildAndSendPacket({servcmd:"im_long_msg.get_relay_json_msg",data:{JsonMsgKey:e}})})}(i),t=(e||{})["MsgList"],s=null==t?void 0:t.map(e=>{e=Jr(e);return new Si(e)});return"function"==typeof o.isOnlineMessage?o.setElement({type:o.type,content:Object.assign({messageList:s},n)}):(o.payload.messageList=s,o.payload.downloadKey="",o.payload.pbDownloadKey=""),r.info("downloadMergerMessage"," success downloadKey:"+i),o}catch(e){let t=e["errorCode"];throw new this._core.helper.ChatError({functionName:"downloadMergerMessage",code:t,moreMessage:i})}})}},yi=new class{init(e){this._core=e,this._core.helper.registerExperimentalAPI("sendComboMessage",this)}sendComboMessage(a){return I(this,void 0,void 0,function*(){let{appStore:t,message:e,common:{getCurrentUserID:s},utils:{isArray:r}}=this._core,{GroupId:i,To_Account:n}=a,o=(a.From_Account=a.From_Account||s(),null);if(i){o=this._generateGroupMessage(Object.assign(Object.assign({},a),{ToGroupId:i}));let e=t.userStore.getUserProfile(s());o.level=(null==e?void 0:e.level)||0,r(n)&&0<n.length&&(o._receiverList=n)}else n&&(o=this._generateC2CMessage(a));return e.messageSender.sendMessage(o,a)})}_generateC2CMessage(e){var{message:t,OuterConstant:{CONV_C2C:s}}=this._core,e=t.messageHelper.parseServerPushMessage(e),t=t.messageFactory.createMessage(Object.assign(Object.assign({},e),{conversationType:s,flow:Nr.OUT})),s=e["elements"];return t.setElement(s),t}_generateGroupMessage(e){var{message:t,OuterConstant:{CONV_GROUP:s}}=this._core,e=t.messageHelper.parseServerGroupMessage(e),t=t.messageFactory.createMessage(Object.assign(Object.assign({},e),{conversationType:s,flow:Nr.OUT})),s=e["elements"];return t.setElement(s),t}},Oi=new class{init(e){var{helper:e,notificationCenter:t,InnerEvent:{MESSAGE_PUSH:s},InnerEventSubType:{GROUP_MESSAGE_PINNED:r}}=this._core=e;t.subscribeInnerEvent(s,r,this._handleGroupMessagePinned,this),e.registerApi({apiName:"pinGroupMessage",context:this}),e.registerApi({apiName:"getPinnedGroupMessageList",context:this})}pinGroupMessage(o){return I(this,void 0,void 0,function*(){let{ssoLog:e,common:{isTopic:t},OuterConstant:{},helper:{ChatError:r}}=this._core;var{groupID:s,message:i,isPinned:n}=o,i=i["sequence"];try{return yield function(o){return I(this,void 0,void 0,function*(){var{buildAndSendPacket:e,getCurrentUserID:t}=E.core["common"],{groupID:s,sequence:r,isPinned:i}=o,t=t(),n=i?"group_open_http_svc.pin_message":"group_open_http_svc.unpin_message",s={GroupId:s,MsgSeq:r};return i?s.Pinner_Account=t:s.UnPinner_Account=t,e({servcmd:n,data:s})})}({groupID:s,sequence:i,isPinned:n}),{code:0,data:{}}}catch(e){let{errorCode:t,errorInfo:s}=e||{};throw new r({code:t,message:s})}})}getPinnedGroupMessageList(r){return I(this,void 0,void 0,function*(){let e=[];try{var t,s=yield function(s){return I(this,void 0,void 0,function*(){var e=s["groupID"],{buildAndSendPacket:t}=E.core["common"];return t({servcmd:"group_open_http_svc.get_pinned_messages",data:{GroupId:e}})})}({groupID:r});return s&&({PinnedMsgList:t=[]}=s,e=yield this._updatePinnedMessageInfo({serverPinnedMessageList:t,groupID:r})),{code:0,data:{messageList:e}}}catch(e){throw e}})}_handleGroupMessagePinned(e){let{message:{messageHelper:u,messageFactory:c},notificationCenter:d,OuterEvent:h,OuterConstant:g}=this._core;e.GroupTips.forEach(e=>{var{ToGroupId:e,MsgBody:{PinnedMsg:t,OpType:s,MsgOperatorMemberExtraInfo:r,SdkGroupMessageId:n}}=e,{UserId:r,NickName:i="",ImageUrl:o=""}=r;let a=null,l=!1;if(16===s){l=!0;let e=u.parseServerGroupMessage(t);(a=c.createMessage(Object.assign(Object.assign({},e),{conversationType:g.CONV_GROUP,flow:"in"}))).setElement(e.elements),a.pinnerInfo={userID:r,nick:i,avatar:o}}else if(17===s){let{ClientTime:e,Random:t,SenderTinyId:s,ServerTime:r,MsgSeq:i}=n;a={ID:`${s}-${e}-`+t,sequence:i,random:t,time:r,clientTime:e}}a&&d.emitOuterEvent(h.PINNED_GROUP_MESSAGE_UPDATED,{name:h.PINNED_GROUP_MESSAGE_UPDATED,data:{groupID:e,message:a,isPinned:l,operatorInfo:{userID:r,nick:i,avatar:o}}})})}_findMessageBySequence(e,t){var{messageDataHandler:s}=this._core["message"];return[...s.getLocalMessageList(e),...s.getSparseMessageList(e)].find(e=>e.sequence===t)}_updatePinnedMessageInfo(e){return I(this,arguments,void 0,function*({serverPinnedMessageList:n,groupID:e}){let{OuterConstant:{CONV_GROUP:t},utils:{isEmpty:s}}=this._core,o=[],a=[],l=[],u=new Map,c=""+t+e;for(let i=0;i<n.length;i++){let e=n[i],{Pinner_Account:t,MsgSeq:s}=e,r=this._findMessageBySequence(c,s);a.push(t),u.set(s,t),r?o.push(r):l.push(s)}let r=yield this._fetchPinnedMessageInfo({conversationID:c,messageSequenceList:l,pinnerIDList:a});if(r){let{pinnerInfoMap:s,messageList:e}=r;return o.push(...e),o.forEach(e=>{var t=e["sequence"],t=u.get(t),t=s[t]||{userID:t,nick:"",avatar:""};e.pinnerInfo=t}),o.sort((e,t)=>e.sequence-t.sequence),o}return[]})}_fetchPinnedMessageInfo(n){return I(this,void 0,void 0,function*(){var{message:{},user:{userProfile:e},utils:{isArray:t}}=this._core,{conversationID:s,messageSequenceList:i,pinnerIDList:r}=n,s=yield Promise.all([this._fetchMessageBySequence({conversationID:s,messageSequenceList:i}),null==e?void 0:e.getUserProfile({userIDList:r})]);if(t(s)){let r={};return((null==(i=s[1])?void 0:i.data)||[]).forEach(e=>{var{userID:e,nick:t="",avatar:s=""}=e;r[e]={userID:e,nick:t,avatar:s}}),{messageList:(null==(e=s[0])?void 0:e.messageList)||[],pinnerInfoMap:r}}})}_fetchMessageBySequence(i){return I(this,void 0,void 0,function*(){var{utils:{isEmpty:e},message:{messageHistory:t}}=this._core,{conversationID:s,messageSequenceList:r}=i;return e(r)?[]:t.getGroupRoamingMessagesByAnchor({conversationID:s,messageSequenceList:r,getType:3})})}},S=new class{constructor(){this.name="MessageEnhancer"}install(e){this._core=e,E.init(e),ui.init(e),hi.init(e),_i.init(e),fi.init(e),Qr.init(e),Ii.init(e),Ei.init(e),Xr.init(e),Mi.init(e),ti.init(e),yi.init(e),Oi.init(e),e.helper.registerValidateConfig({auth:ni,params:ii}),e.notificationCenter.subscribeInnerEvent(e.InnerEvent.LOGOUT,this._reset,this),e.notificationCenter.subscribeInnerEvent(e.InnerEvent.DESTROY,this.dispose,this)}dispose(){var{notificationCenter:e,InnerEvent:t}=this._core;e.unSubscribeInnerEvent(t.LOGOUT,this._reset,this),e.unSubscribeInnerEvent(t.DESTROY,this.dispose,this),_i.dispose(),fi.dispose(),Xr.dispose(),ti.dispose()}_reset(){fi.reset()}},Ai=new class{constructor(){this._name="WebRequest"}init(e){this._core=e}request(p,_){return I(this,void 0,void 0,function*(){let e,t=(null==(e=this._core)?void 0:e.utils).isEmpty,{downloadUrl:s="",method:r="PUT",url:i,qs:n,headers:o={},resources:a,dataType:l="text",uploadByIP:u,uploadIP:c}=p,d=i;if(n){let e=this._queryString(n);e&&(d+=(d.includes("?")?"&":"?")+e)}let h=new XMLHttpRequest;h.open(r.toUpperCase(),d,!0),h.responseType=l;var g=Object.assign({},o);if(u&&c&&(g.host=c),!t(g))for(let e in g)g.hasOwnProperty(e)&&!["content-length","user-agent","origin","host"].includes(e.toLowerCase())&&h.setRequestHeader(e,g[e]);return h.onload=()=>{var e=this._getResponseBody(h,s,u&&c),e=this._buildResponse(h,e);if(200===h.status)_(null,e);else{if(c&&!d.includes(c))return p.url=this._domainName2IP(d,c),p.uploadByIP=!0,this.request(p,_);_({code:h.status,message:JSON.stringify(h.responseText)},e)}},h.onerror=()=>{var e=this._getResponseBody(h,s,u&&c),e=this._buildResponse(h,e),t={code:h.status,message:0===h.status?"CORS blocked or network error":JSON.stringify(h.responseText)};_(t,e)},p.onProgress&&h.upload&&(h.upload.onprogress=e=>{var{total:e,loaded:t}=e,s=Math.min(Math.floor(100*t/e),100);p.onProgress({total:e,loaded:t,percent:s/100})}),h.send(a),h})}_buildResponse(e,t){let s={};return e.getAllResponseHeaders().trim().split("\n").forEach(e=>{var t;e&&([e,t]=e.split(":").map(e=>e.trim()),s[e.toLowerCase()]=t)}),{statusCode:e.status,statusMessage:e.statusText,headers:s,data:t}}_getResponseBody(e,t,s){return 200===e.status&&t?{location:t,uploadIP:s}:{response:e.responseText,uploadIP:s}}_queryString(s,r="&",i="="){var{isEmpty:e,isPlainObject:t}=null==(e=this._core)?void 0:e.utils;return e(s)?"":t(s)?Object.keys(s).map(e=>{let t=encodeURIComponent(e)+i;return Array.isArray(s[e])?s[e].map(e=>t+encodeURIComponent(e)).join(r):t+encodeURIComponent(s[e])}).filter(Boolean).join(r):void 0}_domainName2IP(e,t){return e.replace(/^http(s)?:\/\/(.*?)\//,`https://${t}/`)}};let Ti=["unknown","image","video","audio","log"];var Ri,Di=new class{init(e){this._core=e}request(s,r){let{MINI_APP_NAMESPACE:e,IN_ALIPAY_MINI_APP:i,isUniIOSApp:n}=null==(h=this._core)?void 0:h.utils,{resources:o="",headers:a={},url:l,downloadUrl:u=""}=s,c=l,d=null;var h=u?u.match(/^(https?:\/\/[^/]+\/)([^/]*\/?)(.*)$/):null;if(h){var h=decodeURIComponent(h[3]),h=h.includes("?")?h.split("?")[0]:h||"",h={key:s.fileKey||h,success_action_status:200,"Content-Type":""},g={};if(n()){let[e,t]=l.split("?sign=");t&&(c=e+"?sign="+encodeURIComponent(t),g.sign=decodeURIComponent(t),g.signature=decodeURIComponent(t))}let t={url:c,header:a,name:"file",filePath:o,formData:Object.assign(Object.assign({},h),g),timeout:s.timeout||3e5};if(i){let{}=t,e=f(t,["name"]);t=Object.assign(Object.assign({},e),{fileName:"file",fileType:s.fileType?Ti[s.fileType]:"image"})}return(d=e.uploadFile(Object.assign(Object.assign({},t),{success:e=>{this._handleResponse({response:e,downloadUrl:u,callback:r})},fail:e=>{this._handleResponse({response:e,downloadUrl:u,callback:r})}}))).onProgressUpdate&&d.onProgressUpdate(e=>{s.onProgress&&s.onProgress({total:e.totalBytesExpectedToSend||0,loaded:e.totalBytesSent||0,percent:e.progress?Math.floor(e.progress)/100:0})}),d}console.warn("message Invalid download URL format")}_handleResponse(e){var{downloadUrl:e,response:t,callback:s}=e,r={};if(t.header)for(let e in t.header)t.header.hasOwnProperty(e)&&(r[e.toLowerCase()]=t.header[e]);var i=+t.statusCode;200==i?s(null,{statusCode:i,headers:r,data:Object.assign(Object.assign({},t.data),{location:e})}):s({code:i,message:JSON.stringify(t.data)},{statusCode:i,headers:r,data:void 0})}};function bi(e){return"file"===Object.prototype.toString.call(e).match(/^\[object (.*)\]$/)[1].toLowerCase()}function Ni(e){e=e||99999999;return Math.round(Math.random()*e)}function Li(e,t=!0,s=!0){var r=Date.now();return t?s?r-e+" ms":Math.round((r-e)/1e3)+" s":s?r-e:Math.round((r-e)/1e3)}function Pi(e){return Array.from({length:8},()=>Math.floor(65536*(1+Math.random())).toString(16).substring(1)).join("")+"-"+e}function Gi(e,t){return Math.round(Number(e)*10**t)/10**t}function wi(e){return e<1024?e+"B":e<1048576?Math.floor(e/1024)+"KB":Math.floor(e/1048576)+"MB"}function Ui(e){return e<=1048576?Gi(e/1024,1)+"KB/s":Gi(e/1048576,1)+"MB/s"}let ki="TIMImageElem",Fi="TIMSoundElem",qi="TIMFileElem",xi="TIMVideoFileElem",Vi="RichMediaMessagePlugin",Bi=["rich.my-imcloud.com","imrich.qcloud.com"],ji=((L=Ri=Ri||{}).UNSENT="unSend",L.SUCCESS="success",L.FAIL="fail",{wechat:/^(wxfile:\/\/tmp_|http:\/\/temp\/|cloud:\/\/temp-)/,alipay:/^(https:\/\/resource\/|alipayfile:\/\/tmp\/)/,baidu:/^(http:\/\/tmp\/|swanfile:\/\/tmp_)/,bytedance:/^(ttfile:\/\/tmp_|\/(var|tmp)\/|tttemp:\/\/)/,qq:/^(qqfile:\/\/tmp_|http:\/\/qtemp\/)/}),Ki=Symbol("isCustomUpload");var Hi,M=new class{init(e){this._core=e}addAuthToUrl(e=""){return this._isMiniProgramTempFile(e)?e:(e=(e=e)?!e.startsWith("https://")&&e.startsWith("http://")?e.replace("http://","https://"):e:"",this.processResourceUrl(e))}removeAuthToUrl(s){{var[s,r]=s.split("?");if(!r)return s;let t=r.split("&").reduce((e,t)=>{var[t,s]=t.split("=");return t&&"authKey"!==t&&(e[t]=s||""),e},{}),e=Object.keys(t).map(e=>""+e+(t[e]?"="+t[e]:"")).join("&");return e?s+"?"+e:s}}_isMiniProgramTempFile(t){return!!this.getPlatformFlags().IN_MINI_APP&&Object.values(ji).some(e=>e.test(t))}extractFileFromInput(e){var{isArray:t}=this._core["utils"];return bi(e)?e:function(t){if("object"==typeof t&&null!==t){t=Object.getPrototypeOf(t);if(null===t)return 1;let e=t;for(;null!==Object.getPrototypeOf(e);)e=Object.getPrototypeOf(e);return t===e}}(e)&&"undefined"!=typeof uni?t(e.tempFiles)&&0<e.tempFiles.length?e.tempFiles[0]:t(e.files)?e.files[0]:e.tempFile||null:e instanceof HTMLInputElement&&e.files&&0<e.files.length?e.files[0]:null}probeImageWidthHeight(s){return I(this,void 0,void 0,function*(){var{IN_MINI_APP:e,IN_BROWSER:t}=(null==(e=this._core)?void 0:e.utils)||{};return this._shouldSkipProbing()?{width:0,height:0}:t?this._probeImageDimensionsWeb(s):e?this._probeImageDimensionsMiniApp(s):void 0})}isSimpleCos(){var e=((null==(e=this._core)?void 0:e.store.get("cloudConfig"))||{})["simple_cos"];return"0"!==e}getFileDNList(){let e,t=Bi;var s=((null==(e=this._core)?void 0:e.store.get("cloudConfig"))||{})["file_dn_list"];if(void 0!==s)try{JSON.parse(s).forEach(e=>{t.includes(e)||t.push(e)})}catch(e){console.warn(e),t=Bi}return t}getPlatform(){var e;return null==(e=this._core)?void 0:e.utils.platform}generateUUID(e,t){let s,r=`${this.getSDKAppID()}-${this.getCurrentUserID()}-`+(null==(s=this._core)?void 0:s.utils.randomString());return t?r+"."+t:(e=(t=e.name||e.value||e.url||e.tempFilePath)&&t.slice(t.lastIndexOf(".")+1),r=e?r+"."+e:r)}processResourceUrl(e){if(!e)return"";let t=e;var s=this.getFileDownloadProxy(),r=this.getAuthKey(),i=this.getFileDNList(),e=(s&&(e.startsWith("http://")?t=e.replace(/^http:\/\/[^/]+/,s):e.startsWith("https://")&&(t=e.replace(/^https:\/\/[^/]+/,s))),r&&-1===t.indexOf("authKey=")&&function(e,t){let s=!1;if(e){var e=e.match(/:\/\/([0-9]?\.)?(.[^/:]+)/),r=e&&e[2]||"";if(r.includes("rich-dev"))return!0;for(let e=0;e<t.length;e++)if(r.endsWith(t[e])){s=!0;break}}return s}(t,i));return t=e?-1<t.indexOf("?")?t+"&authKey="+r:t+"?authKey="+r:t}getCurrentUserID(){var e;return null==(e=null==(e=this._core)?void 0:e.store.get("login"))?void 0:e.userId}getSDKAppID(){var e;return null==(e=null==(e=this._core)?void 0:e.store.get("instance"))?void 0:e.sdkAppId}getFileDownloadProxy(){var e;return(null==(e=null==(e=this._core)?void 0:e.store.get("instance"))?void 0:e.fileDownloadProxy)||""}getFileUploadProxy(){var e;return(null==(e=null==(e=this._core)?void 0:e.store.get("instance"))?void 0:e.fileUploadProxy)||""}getAuthKey(){var e;return(null==(e=null==(e=this._core)?void 0:e.store.get("login"))?void 0:e.authKey)||""}isPrivateNetWork(){var e;return null==(e=null==(e=this._core)?void 0:e.store.get("instance"))?void 0:e.proxyServer}getPlatformFlags(){var{IN_BROWSER:e,IN_MINI_APP:t,IN_RN_APP:s,IN_UNI_NATIVE_APP:r}=null==(e=this._core)?void 0:e.utils;return{IN_BROWSER:e,IN_MINI_APP:t,IN_RN_APP:s,IN_UNI_NATIVE_APP:r}}isEmpty(e){var t=(null==(t=this._core)?void 0:t.utils)["isEmpty"];return t(e)}generateURL(e,t){var{needAddAuthToUrl:t=!0}=t||{};return t?this.addAuthToUrl(e):e}_probeImageDimensionsMiniApp(e){let t,s=((null==(t=this._core)?void 0:t.utils)||{}).MINI_APP_NAMESPACE;return new Promise(t=>{s.getImageInfo({src:e,success:e=>t({width:e.width,height:e.height}),fail:()=>t({width:0,height:0})})})}_shouldSkipProbing(){var{IN_RN_APP:e,IS_IE:t,IE_VERSION:s,IN_WX_MINI_GAME:r}=(null==(e=this._core)?void 0:e.utils)||{};return e||t&&9===s||r}_probeImageDimensionsWeb(r){return new Promise(e=>{let t=new Image,s=()=>{t.onload=null,t.onerror=null,t.src=""};t.onload=()=>{e({width:t.width,height:t.height}),s()},t.onerror=()=>{e({width:0,height:0}),s()},t.src=r})}},y=(Hi=["0","1","2","3","4","5","6","7","8","9","a","b","c","d","e","f"],Qi(Ji("hello")),"undefined"==typeof ArrayBuffer||ArrayBuffer.prototype.slice||(ArrayBuffer.prototype.slice=function(e,t){var s=this.byteLength,e=en(e,s),r=s;return(r=void 0!==t?en(t,s):r)<e?new ArrayBuffer(0):(t=r-e,s=new ArrayBuffer(t),r=new Uint8Array(s),e=new Uint8Array(this,e,t),r.set(e),s)}),O.prototype.append=function(e){return this.appendBinary(Xi(e)),this},O.prototype.appendBinary=function(e){this._buff+=e,this._length+=e.length;for(var t=this._buff.length,s=64;s<=t;s+=64)Yi(this._hash,$i(this._buff.substring(s-64,s)));return this._buff=this._buff.substring(s-64),this},O.prototype.end=function(e){for(var t,s=this._buff,r=s.length,i=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],n=0;n<r;n+=1)i[n>>2]|=s.charCodeAt(n)<<(n%4<<3);return this._finish(i,r),t=Qi(this._hash),e&&(t=Zi(t)),this.reset(),t},O.prototype.reset=function(){return this._buff="",this._length=0,this._hash=[1732584193,-271733879,-1732584194,271733878],this},O.prototype.getState=function(){return{buff:this._buff,length:this._length,hash:this._hash.slice()}},O.prototype.setState=function(e){return this._buff=e.buff,this._length=e.length,this._hash=e.hash,this},O.prototype.destroy=function(){delete this._hash,delete this._buff,delete this._length},O.prototype._finish=function(e,t){var s,r=t;if(e[r>>2]|=128<<(r%4<<3),55<r)for(Yi(this._hash,e),r=0;r<16;r+=1)e[r]=0;t=(t=8*this._length).toString(16).match(/(.*?)(.{0,8})$/),s=parseInt(t[2],16),t=parseInt(t[1],16)||0,e[14]=s,e[15]=t,Yi(this._hash,e)},O.hash=function(e,t){return O.hashBinary(Xi(e),t)},O.hashBinary=function(e,t){e=Qi(Ji(e));return t?Zi(e):e},(O.ArrayBuffer=function(){this.reset()}).prototype.append=function(e){s=this._buff.buffer,r=e,(i=new Uint8Array(s.byteLength+r.byteLength)).set(new Uint8Array(s)),i.set(new Uint8Array(r),s.byteLength);var t,s,r,i,n=i,o=n.length;for(this._length+=e.byteLength,t=64;t<=o;t+=64)Yi(this._hash,zi(n.subarray(t-64,t)));return this._buff=t-64<o?new Uint8Array(n.buffer.slice(t-64)):new Uint8Array(0),this},O.ArrayBuffer.prototype.end=function(e){for(var t,s=this._buff,r=s.length,i=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],n=0;n<r;n+=1)i[n>>2]|=s[n]<<(n%4<<3);return this._finish(i,r),t=Qi(this._hash),e&&(t=Zi(t)),this.reset(),t},O.ArrayBuffer.prototype.reset=function(){return this._buff=new Uint8Array(0),this._length=0,this._hash=[1732584193,-271733879,-1732584194,271733878],this},O.ArrayBuffer.prototype.getState=function(){var e,t=O.prototype.getState.call(this);return t.buff=(e=t.buff,String.fromCharCode.apply(null,new Uint8Array(e))),t},O.ArrayBuffer.prototype.setState=function(e){return e.buff=function(e,t){for(var s=e.length,r=new ArrayBuffer(s),i=new Uint8Array(r),n=0;n<s;n+=1)i[n]=e.charCodeAt(n);return t?i:r}(e.buff,!0),O.prototype.setState.call(this,e)},O.ArrayBuffer.prototype.destroy=O.prototype.destroy,O.ArrayBuffer.prototype._finish=O.prototype._finish,O.ArrayBuffer.hash=function(e,t){e=Qi(function(e){for(var t,s,r,i,n=e.length,o=[1732584193,-271733879,-1732584194,271733878],a=64;a<=n;a+=64)Yi(o,zi(e.subarray(a-64,a)));for(t=(e=a-64<n?e.subarray(a-64):new Uint8Array(0)).length,s=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],a=0;a<t;a+=1)s[a>>2]|=e[a]<<(a%4<<3);if(s[a>>2]|=128<<(a%4<<3),55<a)for(Yi(o,s),a=0;a<16;a+=1)s[a]=0;return i=(i=8*n).toString(16).match(/(.*?)(.{0,8})$/),r=parseInt(i[2],16),i=parseInt(i[1],16)||0,s[14]=r,s[15]=i,Yi(o,s),o}(new Uint8Array(e)));return t?Zi(e):e},O),Wi=(n=y)&&n.__esModule&&Object.prototype.hasOwnProperty.call(n,"default")?n.default:n;function Yi(e,t){var s=e[0],r=e[1],i=e[2],n=e[3],r=((r+=((i=((i+=((n=((n+=((s=((s+=(r&i|~r&n)+t[0]-680876936|0)<<7|s>>>25)+r|0)&r|~s&i)+t[1]-389564586|0)<<12|n>>>20)+s|0)&s|~n&r)+t[2]+606105819|0)<<17|i>>>15)+n|0)&n|~i&s)+t[3]-1044525330|0)<<22|r>>>10)+i|0;r=((r+=((i=((i+=((n=((n+=((s=((s+=(r&i|~r&n)+t[4]-176418897|0)<<7|s>>>25)+r|0)&r|~s&i)+t[5]+1200080426|0)<<12|n>>>20)+s|0)&s|~n&r)+t[6]-1473231341|0)<<17|i>>>15)+n|0)&n|~i&s)+t[7]-45705983|0)<<22|r>>>10)+i|0,r=((r+=((i=((i+=((n=((n+=((s=((s+=(r&i|~r&n)+t[8]+1770035416|0)<<7|s>>>25)+r|0)&r|~s&i)+t[9]-1958414417|0)<<12|n>>>20)+s|0)&s|~n&r)+t[10]-42063|0)<<17|i>>>15)+n|0)&n|~i&s)+t[11]-1990404162|0)<<22|r>>>10)+i|0,r=((r+=((i=((i+=((n=((n+=((s=((s+=(r&i|~r&n)+t[12]+1804603682|0)<<7|s>>>25)+r|0)&r|~s&i)+t[13]-40341101|0)<<12|n>>>20)+s|0)&s|~n&r)+t[14]-1502002290|0)<<17|i>>>15)+n|0)&n|~i&s)+t[15]+1236535329|0)<<22|r>>>10)+i|0,r=((r+=((i=((i+=((n=((n+=((s=((s+=(r&n|i&~n)+t[1]-165796510|0)<<5|s>>>27)+r|0)&i|r&~i)+t[6]-1069501632|0)<<9|n>>>23)+s|0)&r|s&~r)+t[11]+643717713|0)<<14|i>>>18)+n|0)&s|n&~s)+t[0]-373897302|0)<<20|r>>>12)+i|0,r=((r+=((i=((i+=((n=((n+=((s=((s+=(r&n|i&~n)+t[5]-701558691|0)<<5|s>>>27)+r|0)&i|r&~i)+t[10]+38016083|0)<<9|n>>>23)+s|0)&r|s&~r)+t[15]-660478335|0)<<14|i>>>18)+n|0)&s|n&~s)+t[4]-405537848|0)<<20|r>>>12)+i|0,r=((r+=((i=((i+=((n=((n+=((s=((s+=(r&n|i&~n)+t[9]+568446438|0)<<5|s>>>27)+r|0)&i|r&~i)+t[14]-1019803690|0)<<9|n>>>23)+s|0)&r|s&~r)+t[3]-187363961|0)<<14|i>>>18)+n|0)&s|n&~s)+t[8]+1163531501|0)<<20|r>>>12)+i|0,r=((r+=((i=((i+=((n=((n+=((s=((s+=(r&n|i&~n)+t[13]-1444681467|0)<<5|s>>>27)+r|0)&i|r&~i)+t[2]-51403784|0)<<9|n>>>23)+s|0)&r|s&~r)+t[7]+1735328473|0)<<14|i>>>18)+n|0)&s|n&~s)+t[12]-1926607734|0)<<20|r>>>12)+i|0,r=((r+=((i=((i+=((n=((n+=((s=((s+=(r^i^n)+t[5]-378558|0)<<4|s>>>28)+r|0)^r^i)+t[8]-2022574463|0)<<11|n>>>21)+s|0)^s^r)+t[11]+1839030562|0)<<16|i>>>16)+n|0)^n^s)+t[14]-35309556|0)<<23|r>>>9)+i|0,r=((r+=((i=((i+=((n=((n+=((s=((s+=(r^i^n)+t[1]-1530992060|0)<<4|s>>>28)+r|0)^r^i)+t[4]+1272893353|0)<<11|n>>>21)+s|0)^s^r)+t[7]-155497632|0)<<16|i>>>16)+n|0)^n^s)+t[10]-1094730640|0)<<23|r>>>9)+i|0,r=((r+=((i=((i+=((n=((n+=((s=((s+=(r^i^n)+t[13]+681279174|0)<<4|s>>>28)+r|0)^r^i)+t[0]-358537222|0)<<11|n>>>21)+s|0)^s^r)+t[3]-722521979|0)<<16|i>>>16)+n|0)^n^s)+t[6]+76029189|0)<<23|r>>>9)+i|0,r=((r+=((i=((i+=((n=((n+=((s=((s+=(r^i^n)+t[9]-640364487|0)<<4|s>>>28)+r|0)^r^i)+t[12]-421815835|0)<<11|n>>>21)+s|0)^s^r)+t[15]+530742520|0)<<16|i>>>16)+n|0)^n^s)+t[2]-995338651|0)<<23|r>>>9)+i|0,r=((r+=((n=((n+=(r^((s=((s+=(i^(r|~n))+t[0]-198630844|0)<<6|s>>>26)+r|0)|~i))+t[7]+1126891415|0)<<10|n>>>22)+s|0)^((i=((i+=(s^(n|~r))+t[14]-1416354905|0)<<15|i>>>17)+n|0)|~s))+t[5]-57434055|0)<<21|r>>>11)+i|0,r=((r+=((n=((n+=(r^((s=((s+=(i^(r|~n))+t[12]+1700485571|0)<<6|s>>>26)+r|0)|~i))+t[3]-1894986606|0)<<10|n>>>22)+s|0)^((i=((i+=(s^(n|~r))+t[10]-1051523|0)<<15|i>>>17)+n|0)|~s))+t[1]-2054922799|0)<<21|r>>>11)+i|0,r=((r+=((n=((n+=(r^((s=((s+=(i^(r|~n))+t[8]+1873313359|0)<<6|s>>>26)+r|0)|~i))+t[15]-30611744|0)<<10|n>>>22)+s|0)^((i=((i+=(s^(n|~r))+t[6]-1560198380|0)<<15|i>>>17)+n|0)|~s))+t[13]+1309151649|0)<<21|r>>>11)+i|0,r=((r+=((n=((n+=(r^((s=((s+=(i^(r|~n))+t[4]-145523070|0)<<6|s>>>26)+r|0)|~i))+t[11]-1120210379|0)<<10|n>>>22)+s|0)^((i=((i+=(s^(n|~r))+t[2]+718787259|0)<<15|i>>>17)+n|0)|~s))+t[9]-343485551|0)<<21|r>>>11)+i|0,e[0]=s+e[0]|0,e[1]=r+e[1]|0,e[2]=i+e[2]|0,e[3]=n+e[3]|0}function $i(e){for(var t=[],s=0;s<64;s+=4)t[s>>2]=e.charCodeAt(s)+(e.charCodeAt(s+1)<<8)+(e.charCodeAt(s+2)<<16)+(e.charCodeAt(s+3)<<24);return t}function zi(e){for(var t=[],s=0;s<64;s+=4)t[s>>2]=e[s]+(e[s+1]<<8)+(e[s+2]<<16)+(e[s+3]<<24);return t}function Ji(e){for(var t,s,r,i,n=e.length,o=[1732584193,-271733879,-1732584194,271733878],a=64;a<=n;a+=64)Yi(o,$i(e.substring(a-64,a)));for(t=(e=e.substring(a-64)).length,s=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],a=0;a<t;a+=1)s[a>>2]|=e.charCodeAt(a)<<(a%4<<3);if(s[a>>2]|=128<<(a%4<<3),55<a)for(Yi(o,s),a=0;a<16;a+=1)s[a]=0;return i=(i=8*n).toString(16).match(/(.*?)(.{0,8})$/),r=parseInt(i[2],16),i=parseInt(i[1],16)||0,s[14]=r,s[15]=i,Yi(o,s),o}function Qi(e){for(var t=0;t<e.length;t+=1)e[t]=function(e){for(var t="",s=0;s<4;s+=1)t+=Hi[e>>8*s+4&15]+Hi[e>>8*s&15];return t}(e[t]);return e.join("")}function Xi(e){return e=/[\u0080-\uFFFF]/.test(e)?unescape(encodeURIComponent(e)):e}function Zi(e){for(var t=[],s=e.length,r=0;r<s-1;r+=2)t.push(parseInt(e.substr(r,2),16));return String.fromCharCode.apply(String,t)}function O(){this.reset()}function en(e,t){return(e=0|e||0)<0?Math.max(e+t,0):Math.min(e,t)}var tn=new class{constructor(){this.uploadFileTryCount=0,this.maxRetries=1,this.systemClockOffset=0,this.httpRequest=null,this.uploadFileType="",this.duration=900,this.fetchCosTryCount=0}init(e){var t=(this._core=e).utils["IN_MINI_APP"];this.httpRequest=t?Di:Ai,null!=(t=this.httpRequest)&&t.init(e)}uploadToCOS(u){return I(this,void 0,void 0,function*(){let r=Vi+" uploadToCOS",{ssoLog:i,utils:{safeStringify:t}}=this._core,n=u["file"];this.uploadFileType=u.uploadFileType,i.debug("uploadToCOS",r+" options:"+t(u));try{let e=Date.now(),t=yield this._createCosOptions(u),s=t.fileExistsInCOS?{data:{location:t.downloadUrl}}:yield this._uploadFile(t);this._handleUploadError(s,u);var o=this._createUploadResult(n,s),a=Date.now()-e,l=`size:${wi(n.size)} time:${a}ms speed:`+Ui(1e3*n.size/a);return i.debug("uploadToCOS",r+` ok. name:${n.name} `+l),{uploadOptions:t,response:o}}catch(e){throw i.warn("uploadToCOS",r+" failed, error:"+t(e)),e}})}_handleUploadError(e,t){var s=(null==(s=this._core)?void 0:s.helper)["ChatError"];if(403===e.statusCode)throw t.url,null!=(t=null==e?void 0:e.data)&&t.uploadIP&&e.data.uploadIP,new s({message:"Upload failed with status 403"})}_createUploadResult(e,t){return{fileName:e.name,fileSize:e.size,fileType:e.type.slice(e.type.indexOf("/")+1).toLowerCase(),location:t.data.location||"",uploadTime:Li(Date.now(),!1),uploadSpeed:Ui(1e3*e.size/Li(Date.now(),!1))}}_createCosOptions(g){return I(this,void 0,void 0,function*(){var{fileName:e,resources:t,uploadMethod:s}=yield this._prepareUploadParams(g),r=this._isC2CConversation(g.message.conversationID)?1:2;try{var i=yield this._fetchCosSignatureUrl({fileType:this.uploadFileType,fileName:e,uploadMethod:s,duration:this.duration,userID:g.message.from,conversationType:r}),{uploadUrl:n,downloadUrl:o,requestSnapshotUrl:a,thumbUrl:l,largeUrl:u,fileKey:c,existFlag:d}=i,h=!M.isPrivateNetWork()&&i.uploadIP;return{url:this._getRawOrUploadProxyUrl(n),fileType:this.uploadFileType,fileName:e,resources:t,downloadUrl:o,requestSnapshotUrl:a,thumbUrl:l,largeUrl:u,fileKey:c,uploadIP:h||"",fileExistsInCOS:1===d,onProgress:e=>this._handleUploadProgress(e,g)}}catch(e){throw console.error("Failed to create COS pre-signed URL options:",e),e}})}_prepareUploadParams(o){return I(this,void 0,void 0,function*(){var{ssoLog:e,utils:{safeStringify:t,isEmpty:s}}=this._core,e=(e.debug("_prepareUploadParams"," prepareUploadParams:"+t(o)),o)["file"],{IN_MINI_APP:t,IN_RN_APP:r}=M.getPlatformFlags(),t=t||r,r=t&&o.message.type!==qi,i=e["name"],i=i.slice(i.lastIndexOf(".")),n=""+Ni(999999)+i,r=r?e.name:n,n=yield this._generateHashFileName(e);return{fileName:s(n)?Pi(r):""+n+i,resources:t?e.url:e,uploadMethod:t?1:0}})}_generateHashFileName(a){return I(this,void 0,void 0,function*(){var{utils:{IN_MINI_APP:e,IN_BROWSER:t,IN_UNI_NATIVE_APP:s,isArray:r},ssoLog:i}=this._core,n=Date.now();let o="";return t&&(o=yield this._generateHashFileNameInWeb(a)),e&&(r(a.tempFiles)&&(a=a.tempFiles[0]),s||(o=yield this._generateFileNameInMiniProgram(a)),s)&&(o=yield this._generateFileNameInUNINativeApp(a)),i.info("_generateHashFileName",`hashFileName:${o} costTime:`+(Date.now()-n)),o})}_generateHashFileNameInWeb(h){return I(this,void 0,void 0,function*(){let{ssoLog:d,utils:{safeStringify:t}}=this._core,e="";try{e=yield new Promise((t,s)=>{let r=File.prototype.slice||File.prototype.mozSlice||File.prototype.webkitSlice,i=(r||(d.warn("_generateHashFileNameInWeb","Browser does not support file slicing"),t("")),10485760),n=Math.ceil(h.size/i),o=0,a=new Wi.ArrayBuffer,l=new FileReader,u=setTimeout(()=>{l.abort(),d.warn("_generateHashFileNameInWeb","File hash generation timeout"),t("")},2e3);function c(){var e=o*i,t=e+i>=h.size?h.size:e+i;l.readAsArrayBuffer(r.call(h,e,t))}l.onload=e=>{d.debug("_generateHashFileNameInWeb",`read chunk nr ${o+1} of `+n),a.append(e.target.result),++o<n?c():(d.debug("_generateHashFileNameInWeb","finished loading"),clearTimeout(u),t(a.end()))},l.onerror=e=>{clearTimeout(u),s(e)},c()})}catch(e){d.warn("_generateHashFileNameInWeb",t(e))}return e})}_generateFileNameInMiniProgram(n){return I(this,void 0,void 0,function*(){let{utils:{MINI_APP_NAMESPACE:e,safeStringify:t,isEmpty:s},ssoLog:r}=this._core,i="";if(s(n.url))r.warn("_generateFileNameInMiniProgram","file.url is empty");else if("function"!=typeof(null==e?void 0:e.getFileSystemManager))r.warn("_generateFileNameInUNINativeApp","getFileSystemManager is not a function");else try{i=yield new Promise((t,s)=>{e.getFileSystemManager().getFileInfo({filePath:n.url,success:e=>{t(e.digest)},fail:e=>{s(e)}})})}catch(e){r.warn("_generateFileNameInMiniProgram",t(e))}return i})}_generateFileNameInUNINativeApp(i){return I(this,void 0,void 0,function*(){var{utils:{safeStringify:t,isEmpty:e},ssoLog:s}=this._core;let r="";if(e(i.url))s.warn("_generateFileNameInUNINativeApp","file.url is empty");else if("function"!=typeof(null==(e=null===plus||void 0===plus?void 0:plus.io)?void 0:e.getFileInfo))s.warn("_generateFileNameInUNINativeApp","plus.io.getFileInfo is not a function");else try{r=yield new Promise((t,s)=>{plus.io.getFileInfo({filePath:i.url,success:e=>{t(e.digest)},fail:e=>{s(e)}})})}catch(e){s.warn("_generateFileNameInMiniProgram",t(e))}return r})}_handleUploadProgress(e,t){if("function"==typeof t.onProgress)try{t.onProgress(e.percent)}catch(e){throw console.warn("Upload progress callback error:",e),e}}_fetchCosSignatureUrl(e){return I(this,void 0,void 0,function*(){var{ssoLog:t,utils:{safeStringify:s}}=this._core,r=M.isSimpleCos(),i=this._prepareCosRequestData(e),n=r?"im_cos_msg.simple_sig":"im_cos_msg.pre_sig";try{let e=yield function(i,n,o){return I(this,void 0,void 0,function*(){try{var{helper:e,channel:t}=o,s=e.generateCosSpecifiedData({servcmd:i,data:n}),r=s.head.seq+i;return yield t.sendPacket(s,{requestId:r})}catch(e){throw console.warn("getCosSig error:",e),e}})}(n,i,this._core);this.fetchCosTryCount=0;var o=this._processResponse(e);return t.debug("_fetchCosSignatureUrl",` ok. isSimpleCos:${r} data:`+s(o)),o||{}}catch(t){if(this.fetchCosTryCount<1)return this.fetchCosTryCount++,this._fetchCosSignatureUrl(e);throw this.fetchCosTryCount=0,t}})}_processResponse(e){var t;let s=M.isSimpleCos(),l=s?null==(t=null==e?void 0:e.rpt_pre_sig)?void 0:t[0]:e;if(!l)return{};if(s){let{str_final_ip:e,rpt_pre_sig:t,uint32_file_id:s,uint32_exist_flag:r,str_download_url:i,str_upload_url:n,str_snapshot_url:o,str_file_key:a}=l;return{uploadIP:e,preSig:t,fileID:s,existFlag:r,downloadUrl:i,uploadUrl:n,requestSnapshotUrl:o,fileKey:a}}let{upload_url:r,download_url:i,snapshot_url:n,thumb_url:o,large_url:a,file_key:u}=l;return{uploadUrl:r,downloadUrl:i,requestSnapshotUrl:n,thumbUrl:o,largeUrl:a,fileKey:u}}_prepareCosRequestData(e){return M.isSimpleCos()?{uint32_upload_method:e.uploadMethod,uint32_platform:M.getPlatform(),uint32_sdkappid:M.getSDKAppID(),str_user_id:e.userID,uint32_scene:e.conversationType,rpt_upload_object:[{uint32_file_id:1,uint32_file_type:e.fileType,str_file_name:e.fileName}]}:{file_type:e.fileType,file_name:e.fileName,upload_method:e.uploadMethod,Duration:e.duration}}_uploadFile(i){return I(this,void 0,void 0,function*(){return new Promise((s,r)=>{this.httpRequest.request(i,(e,t)=>{e&&this.uploadFileTryCount<this.maxRetries&&this.shouldRetry(e)?(this.uploadFileTryCount++,this._uploadFile(i).then(s).catch(r)):(this.uploadFileTryCount=0,e?r(e):s(t))})})})}shouldRetry(e){return!(!e||5!==Math.floor(e.statusCode/100)&&(!this.isTimeRelatedError(e)||!this._isClockOutOfSync(e)||(this._syncSystemClock(e),0)))}isTimeRelatedError(e){var t,s;try{var r=null==(t=e.error)?void 0:t.Code,i=null==(s=e.error)?void 0:s.Message;return"RequestTimeTooSkewed"===r||"AccessDenied"===r&&"Request has expired"===i}catch(e){return!1}}_isClockOutOfSync(e){var t,e=(null==(t=e.headers)?void 0:t.date)||(null==(t=e.headers)?void 0:t.Date)||(null==(t=e.error)?void 0:t.ServerTime);return!!e&&(t=Date.now(),e=Date.parse(e),3e4<=Math.abs(t+this.systemClockOffset-e))}_syncSystemClock(e){var t,s=(null==(t=e.headers)?void 0:t.date)||(null==(t=e.headers)?void 0:t.Date)||(null==(t=e.error)?void 0:t.ServerTime);if(s){let e=Date.now(),t=Date.parse(s);this.systemClockOffset=t-e}}_getRawOrUploadProxyUrl(e){var t=M.getFileUploadProxy();let s=e;return s=t?e.replace(/^https:\/\/[^/]+/,t):s}_isC2CConversation(e){return"C2C"===e.slice(0,3)}};let sn=["jpg","jpeg","gif","png","bmp","image","webp"],rn={JPG:1,JPEG:1,GIF:2,PNG:3,BMP:4,UNKNOWN:255};class nn{constructor(e,t){this.instanceID=Ni(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=M.addAuthToUrl(e.imageUrl||e.url||""),this.url=M.addAuthToUrl(e.url||t)}setSizeType(e){this.sizeType=e}setType(e){this.type=e}setImageUrl(e){e&&(this.imageUrl=M.addAuthToUrl(e))}getImageUrl(){return this.imageUrl}}function on(e){var{originUrl:t,originWidth:e,originHeight:s,min:r=198}=e,i=parseInt(e)||0,s=parseInt(s)||0,n={url:void 0,width:0,height:0};if((i<=s?i:s)<=r)n.url=t,n.width=i,n.height=s;else{s<=i?(n.width=Math.ceil(i*r/s),n.height=r):(n.width=r,n.height=Math.ceil(s*r/i));let e=t&&-1<t.indexOf("?")?t+"&":t+"?";n.url=198===r?e+"imageView2/3/w/198/h/198":e+"imageView2/3/w/720/h/720"}if(void 0!==t)return n;return f(n,["url"])}class an{constructor(e){this._imageMemoryURL="",this._percent=0,this.type=ki;var{uuid:e,file:t,imageFormat:s,imageInfoArray:r=[],isCustomUpload:i=!1}=e;this._imageMemoryURL=this.createImageDataAsURL(t),this.content={imageFormat:s,uuid:e,imageInfoArray:[]},this[Ki]=i,this.initImageInfoArray(r),this.autoFixUrl()}static parseServerPushElement(e){let t=e["MsgContent"],{ImageFormat:s,ImageInfoArray:r,UUID:i}=t,n=r.map(e=>({size:e.Size,type:e.Type,width:e.Width,height:e.Height,url:e.URL}));return new an({imageFormat:s,imageInfoArray:n,uuid:i})}createImageDataAsURL(e){let t="";var{IN_MINI_APP:s,IN_RN_APP:r,IN_BROWSER:i}=M.getPlatformFlags();return t=e&&((s||r)&&(t=e.url),i)?window.URL.createObjectURL(e):t}initImageInfoArray(t=[]){var s={type:0,size:0,width:0,height:0,url:""};for(let e=0;e<3;e++){var r=t[e]||Object.assign({},s),r=new nn(r,this._imageMemoryURL);r.setSizeType(e+1),r.setType(e),this.addImageInfo(r)}this.updateAccessSideImageInfoArray()}autoFixUrl(){let r=["http","https"];this.content.imageInfoArray.forEach(e=>{var t,s;e.url&&""!==e.imageUrl&&([t,...s]=e.imageUrl.split("://"),s=s.join("://"),r.includes(t)||e.setImageUrl("https://"+s))})}updatePercent(e){this._percent=Math.min(e,1)}updateImageFormat(e){this.content.imageFormat=rn[e.toUpperCase()]||rn.UNKNOWN}addImageInfo(e){3<=this.content.imageInfoArray.length||this.content.imageInfoArray.push(e)}updateImageInfoArray(t){var s,r=this.content.imageInfoArray.length;for(let e=0;e<r;e++)s=this.content.imageInfoArray[e],t[e].size&&(s.size=t[e].size),t[e].url&&s.setImageUrl(t[e].url),t[e].width&&(s.width=t[e].width),t[e].height&&(s.height=t[e].height)}updateAccessSideImageInfoArray(){var[e]=this.content.imageInfoArray;if(e&&0!==e.width&&0!==e.height){var t=this.content.imageInfoArray,s=t[2];t[2]=t[1],t[1]=s;for(let e=0;e<t.length;e++)t[e].setType(e);Object.assign(this.content.imageInfoArray[2],on({originWidth:e.width,originHeight:e.height,min:720}))}}validateBeforeSend(){var e;return this[Ki]?(delete this[Ki],{isValid:!0}):([e]=this.content.imageInfoArray,{isValid:e=!!e&&""!==e.imageUrl&&0!==e.size,error:e?null:{message:"content can not be empty"}})}transformToServerFormat(e){var{isMergerMessage:e=!1}=e||{},{uuid:e,imageFormat:t,imageInfoArray:s}=e?this.payload:this.content;return{MsgType:this.type,MsgContent:{ImageFormat:t,ImageInfoArray:this.parseImageInfoArray(s),UUID:e}}}parseImageInfoArray(e){return e.map(e=>({InstanceId:e.instanceID,Type:e.sizeType,MsgType:e.type,Size:e.size,Width:e.width,Height:e.height,URL:M.removeAuthToUrl(e.imageUrl)}))}}var ln=new class{constructor(){this._messageOptionsMap=new Map}init(e){var{notificationCenter:e,helper:t,InnerEvent:s,message:r}=this._core=e;t.registerApi({apiName:"createImageMessage",context:this}),t.registerExperimentalAPI("createImageMessage",this,"createCustomUploadImageMessage"),null!=(t=null==r?void 0:r.messageFactory)&&t.registerElementClass(ki,an),e.subscribeInnerEvent(s.DESTROY,this._dispose,this)}createImageMessage(e){var t,s,r;try{var i=null==(t=this._core.store.get("login"))?void 0:t.userId,n=null==(r=null==(s=this._core)?void 0:s.message.messageFactory)?void 0:r.createMessage(Object.assign(Object.assign({},e),{from:i})),o=this._processImage(e),a=(e.payload.file=o,{imageFormat:rn.UNKNOWN,uuid:M.generateUUID(o),file:o,imageInfoArray:[]}),l=new an(a);return n.setElement(l),this._messageOptionsMap.set(n.clientSequence,e),n}catch(e){throw e}}createCustomUploadImageMessage(e){var{store:t,utils:{isEmpty:s}}=this._core,t=null==(t=t.get("login"))?void 0:t.userId,r=null==(r=null==(r=this._core)?void 0:r.message.messageFactory)?void 0:r.createMessage(Object.assign(Object.assign({},e),{from:t})),{largeImageUuid:t,largeFileSize:i,largeImageWidth:n,largeImageHeight:o,largeImageUrl:a,originImageUuid:l,originFileSize:u,originImageWidth:c,originImageHeight:d,originImageUrl:h,thumbImageUuid:g,thumbFileSize:p,thumbImageWidth:_,thumbImageHeight:m,thumbImageUrl:v}=(null==(t=null==e?void 0:e.payload)?void 0:t.file)||{};if(s(h)||s(l))throw new Error("createImageMessageExperimental originImageUrl or originImageUuid is empty");s=new an({imageFormat:rn.UNKNOWN,uuid:l,imageInfoArray:[{instanceID:l,size:u,width:c,height:d,imageUrl:h,url:h},{instanceID:t,size:i,width:n,height:o,imageUrl:a,url:a},{instanceID:g,size:p,width:_,height:m,imageUrl:v,url:v}],isCustomUpload:!0});return r.setElement(s),this._messageOptionsMap.set(r.clientSequence,e),r._skipUpload=!0,r}upload(r){return I(this,void 0,void 0,function*(){var e=r.getElements()[0],t=this._messageOptionsMap.get(r.clientSequence).payload["file"],t=(this._validateBeforeUploadImage(t),yield this._performImageUpload(e,r,t)),s=this._generateImageInfo(t);return e.updateImageFormat(null==t?void 0:t.fileType),e.updateImageInfoArray(s),r})}_performImageUpload(r,i,s){return I(this,void 0,void 0,function*(){var e=i["to"],{uploadOptions:e,response:t}=yield tn.uploadToCOS({uploadFileType:1,file:s,to:e,message:i,onProgress:e=>{var t,s;r.updatePercent(e),null!=(s=null==(t=this._messageOptionsMap.get(i.clientSequence))?void 0:t.onProgress)&&s.call(t,e)}});return this._parseResponse(e,t)})}_generateImageInfo(e){var{location:e,fileSize:t,width:s,height:r,smallImageUrl:i,smallImageWidth:n,smallImageHeight:o,largeImageUrl:a,largeImageWidth:l,largeImageHeight:u,imageInfoArray:c}=e,e=M.addAuthToUrl(e),d={size:t,url:e,width:s,height:r};return 0<(null==c?void 0:c.length)?this._processImageInfoArray(c,t):i&&a?[Object.assign({},d),{largeImageUrl:a,largeImageWidth:l,largeImageHeight:u},{smallImageUrl:i,smallImageWidth:n,smallImageHeight:o}]:[Object.assign({},d),this._generateThumbInfo(e,s,r,720),this._generateThumbInfo(e,s,r,198)]}_generateThumbInfo(e,t,s,r){return on({originUrl:e,originWidth:t,originHeight:s,min:r})}_processImageInfoArray(e,t){let s,r,i;for(var n of e)1===n.type?(r=n,r.size=t):2===n.type?(i=n,i.size=t):(s=n,s.size=t);return[Object.assign({},s),Object.assign({},i),Object.assign({},r)]}_parseResponse(r,i){return I(this,void 0,void 0,function*(){try{var{thumbUrl:e,largeUrl:t,downloadUrl:s}=r;if(e&&t&&(yield this._getImageInfoByUrl(e,i,"thumb"),yield this._getImageInfoByUrl(t,i,"large")),M.isSimpleCos()&&!M.isPrivateNetWork()&&(yield this._getImageInfoArray(s,i),null!=i)&&i.uploadIP){let e=this._extractDomainFromUrl(s);e&&(yield this._getDownloadIP(e,i))}return i}catch(e){throw e}})}_extractDomainFromUrl(t){var e;try{let e=t.match(/:\/\/([^\/]+)/);return e?e[1]:null}catch(t){return null!=(e=this._core)&&e.ssoLog.warn("_extractDomainFromUrl","Failed to extract domain from URL:"+t.message),null}}_getImageInfoByUrl(r,i,n){return I(this,void 0,void 0,function*(){var t;try{let e=M.addAuthToUrl(r),{width:t=0,height:s=0}=yield M.probeImageWidthHeight(e);i.width=t,i.height=s,"thumb"===n?(i.smallImageUrl=r,i.smallImageWidth=t,i.smallImageHeight=s):(i.largeImageUrl=r,i.largeImageWidth=t,i.largeImageHeight=s)}catch(e){null!=(t=this._core)&&t.ssoLog.warn("_getImageInfoByUrl",`Failed to get ${n} image info:`+e.message)}})}_validateBeforeUploadImage(e){var t=(null==(t=this._core)?void 0:t.helper)["ChatError"];if(!e)throw new t({code:2251});this._checkImageType(e),this._checkImageSize(e)}_processImage(e){var t;try{var s=(null==(t=this._core)?void 0:t.utils)["IN_MINI_APP"],r=e.payload["file"];return s?this._processMiniAppImageFile(r):this._processWebImageFile(r)}catch(e){throw e}}_processMiniAppImageFile(e){bi(e)&&console.warn("FileUnsupportedInMiniApp","createImageMessage");var t=e.tempFiles[0].path||e.tempFiles[0].tempFilePath;return{url:t,name:t.slice(t.lastIndexOf("/")+1),size:e.tempFiles&&e.tempFiles[0].size||1,type:t.slice(t.lastIndexOf(".")+1).toLowerCase()}}_processWebImageFile(e){var t=(null==(t=this._core)?void 0:t.helper)["ChatError"],e=M.extractFileFromInput(e);if(e)return e;throw new t({message:"Invalid file. Pass either `e.target` (from file input) or a File object"})}_getDownloadIP(r,i){return I(this,void 0,void 0,function*(){var e=Vi+" getDownloadIP domainName: "+r;try{var t,s=yield function(o,a){return I(this,void 0,void 0,function*(){try{var{helper:e,channel:t}=a,s="im_cos_msg.get_final_ip",r={str_domain:o},i=e.generateProtocolData({servcmd:s,data:r}),n=i.head.seq+s;return yield t.sendPacket(i,{requestId:n})}catch(e){throw console.warn("getFinalIP error:",e),e}})}(r,this._core);s&&s.str_final_ip&&(console.log(e+" ok. downloadIP:"+s),(t=i.location.split("/"))[0]=s.str_final_ip,i.location=t.join("/"))}catch(e){console.warn(e)}})}_getImageInfoArray(t,s){return I(this,void 0,void 0,function*(){try{var e=yield function(o,a){return I(this,void 0,void 0,function*(){try{var{helper:e,channel:t}=a,s="im_cos_msg.get_imageinfo",r={str_image_url:o},i=e.generateProtocolData({servcmd:s,data:r}),n=i.head.seq+s;return yield t.sendPacket(i,{requestId:n})}catch(e){throw console.warn("getImageInfo error:",e),e}})}(t,this._core);return s.imageInfoArray=this._processImageInfoResponse(e),s}catch(e){throw s.imageInfoArray=void 0,e}})}_processImageInfoResponse(e){return e?(e=e["rpt_msg_image_info"],e.map(e=>({type:e.uint32_image_type,url:e.str_url,width:e.uint32_width,height:e.uint32_height,imageFormat:e.str_image_format}))):[]}_checkImageType(e){var{utils:t,helper:s}=this._core;let r="";if(t.IN_MINI_APP&&(r=e.url.slice(e.url.lastIndexOf(".")+1)),t.IN_BROWSER&&(r=e.name.slice(e.name.lastIndexOf(".")+1)),sn.indexOf(r.toLowerCase())<0)throw new s.ChatError({code:2252})}_checkImageSize(e){var{utils:t,helper:s}=this._core,r=0;if(t.IN_MINI_APP,0===(r=e.size))throw new s.ChatError({code:2108});if(20971520<=r)throw new s.ChatError({message:"File size exceeds limit: "+wi(20971520)})}_reset(){this._messageOptionsMap.clear()}_dispose(){this._reset();var{notificationCenter:e,InnerEvent:t}=this._core;e.unSubscribeInnerEvent(t.DESTROY,this._dispose,this)}};let un=104857600;function cn(e,t){let r=e.split("."),i=t.split("."),n=Math.max(r.length,i.length);for(;r.length<n;)r.push("0");for(;i.length<n;)i.push("0");for(let s=0;s<n;s++){let e=parseInt(r[s]),t=parseInt(i[s]);if(e>t)return 1;if(e<t)return-1}return 0}let dn=new class{init(e){this.core=e}};class hn{constructor(e){this.type=qi,this.uploadProgress=0,this[gn]=!1;var t=this._getFileInfo(e);this[Ki]=e.isCustomUpload||!1,this.content={downloadFlag:2,fileUrl:M.generateURL(e.url||e.fileUrl,{needAddAuthToUrl:!this[Ki]})||"",uuid:e.uuid,fileName:t.name||"",fileSize:t.size||0}}static parseServerPushElement(e){var e=e["MsgContent"],{Download_Flag:e,Url:t,FileName:s,FileSize:r,UUID:i}=e;return new hn({downloadFlag:e,url:t,fileName:s,fileSize:r,uuid:i})}updatePercent(e){this.uploadProgress=Math.min(e,1)}updateFileUrl(e){this.content.fileUrl=e}validateBeforeSend(){var e;return this[Ki]?{isValid:!0}:{isValid:e=""!==this.content.fileUrl&&""!==this.content.fileName&&0<this.content.fileSize,error:e?null:{message:"content can not be empty"}}}transformToServerFormat(e){var{isMergerMessage:e=!1}=e||{},{uuid:e,downloadFlag:t,fileUrl:s,fileName:r,fileSize:i}=e?this.payload:this.content;return{MsgType:this.type,MsgContent:{Download_Flag:t,Url:M.removeAuthToUrl(s),FileName:r,FileSize:i,UUID:e}}}_getFileInfo(e){var t=dn.core["utils"]["IN_UNI_NATIVE_APP"];return e.fileName&&e.fileSize?{size:e.fileSize,name:e.fileName}:(e=e["file"],e?(t&&this._processNativeAppFile(e),{size:e.size,name:e.name}):{size:0,name:""})}_processNativeAppFile(e){var t;e.path&&e.path.includes(".")&&(t=e.path.slice(e.path.lastIndexOf(".")+1).toLowerCase(),e.type=t,e.name||(e.name=Ni(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 gn=Ki,pn=new class{constructor(){this._messageOptionsMap=new Map}init(e){var{notificationCenter:e,helper:t,InnerEvent:s,message:r}=this._core=e;t.registerApi({apiName:"createFileMessage",context:this}),t.registerExperimentalAPI("createFileMessage",this,"createCustomUploadFileMessage"),null!=(t=null==r?void 0:r.messageFactory)&&t.registerElementClass(qi,hn),e.subscribeInnerEvent(s.DESTROY,this._dispose,this)}createFileMessage(e){var t,s,r;try{this._checkVersion();var i=this._processFile(e.payload.file),n=(e.payload.file=i,null==(t=this._core.store.get("login"))?void 0:t.userId),o=null==(r=null==(s=this._core)?void 0:s.message.messageFactory)?void 0:r.createMessage(Object.assign(Object.assign({},e),{from:n})),a={uuid:M.generateUUID(i),file:i},l=new hn(a);return o.setElement(l),this._messageOptionsMap.set(o.clientSequence,e),o}catch(e){throw e}}createCustomUploadFileMessage(e){var t,s,r;try{var{store:i,message:n,utils:{isEmpty:o}}=this._core,a=null==(t=i.get("login"))?void 0:t.userId,{url:l,uuid:u,fileSize:c,fileName:d=""}=(null==(s=null==e?void 0:e.payload)?void 0:s.file)||{};if(o(l))throw new Error("url is required");var h=null==(r=n.messageFactory)?void 0:r.createMessage(Object.assign(Object.assign({},e),{from:a})),g=new hn({url:l,uuid:u,file:{size:c,name:d},isCustomUpload:!0});return h.setElement(g),h}catch(e){throw e}}upload(s){return I(this,void 0,void 0,function*(){var e=this._messageOptionsMap.get(s.clientSequence).payload["file"],t=(this._validateBeforeUploadFile(e),s.getElements()[0]),e=yield this._performFileUpload(t,s,e),e=M.addAuthToUrl(null==e?void 0:e.location);return t.updateFileUrl(e),s})}_validateBeforeUploadFile(e){var t=(null==(t=this._core)?void 0:t.helper)["ChatError"];if(!e)throw new t({code:2401});if(e.size>un)throw new t({message:"File size exceeds limit: "+wi(un)});if(0===e.size)throw new t({code:2108})}_performFileUpload(r,i,t){return I(this,void 0,void 0,function*(){var e=i["to"],e=(yield tn.uploadToCOS({uploadFileType:255,file:t,to:e,message:i,onProgress:e=>{var t,s;r.updatePercent(e),null!=(s=null==(t=this._messageOptionsMap.get(i.clientSequence))?void 0:t.onProgress)&&s.call(t,e)}}))["response"];return e})}_processFile(t){var{IN_BROWSER:e,IN_RN_APP:s,IN_WX_MINI_APP:r,IN_QQ_MINI_APP:i,IN_UNI_NATIVE_APP:n}=null==(e=this._core)?void 0:e.utils,o=(null==(o=this._core)?void 0:o.helper)["ChatError"];if(e||n){let e=M.extractFileFromInput(t);if(e)return e;throw new o({message:"Invalid file. Pass either `e.target` (from file input) or a File object"})}if(r||i){let e=t["tempFiles"];return Object.assign(Object.assign({},e[0]),{url:e[0].path})}return s?Object.assign(Object.assign({},t),{url:t.uri}):t}_checkVersion(){var{MINI_APP_NAMESPACE:t,IN_MINI_APP:e,IN_WX_MINI_APP:s,IN_QQ_MINI_APP:r,IN_UNI_NATIVE_APP:i}=null==(e=this._core)?void 0:e.utils,n=(null==(n=this._core)?void 0:n.helper)["ChatError"];if(e){if(!(s||r||i))throw new n({message:"Unsupported mini app environment"});let e=t.getSystemInfoSync().SDKVersion;if(s&&cn(e,"2.5.0")<0)throw new n({message:"WXChooseMessageFile requires SDK version 2.5.0 or higher"});if(r&&cn(e,"1.18.0")<0)throw new n({message:"QQChooseMessageFile requires SDK version 1.18.0 or higher"})}}_reset(){this._messageOptionsMap.clear()}_dispose(){this._reset();var{notificationCenter:e,InnerEvent:t}=this._core;e.unSubscribeInnerEvent(t.DESTROY,this._dispose,this)}};let _n=["mp4","quicktime","mov"],mn=104857600;class vn{constructor(e){this.type=xi,this.uploadProgress=0,this[In]=!1;var t="number"==typeof(null==e?void 0:e.videoSecond)?null==e?void 0:e.videoSecond:0;this[Ki]=e.isCustomUpload||!1,this.content={remoteVideoUrl:M.addAuthToUrl(e.remoteVideoUrl||e.videoUrl||""),videoFormat:e.videoFormat,videoSecond:parseInt(null==t?void 0:t.toString(),10),videoSize:e.videoSize,videoUrl:M.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:M.addAuthToUrl(e.thumbUrl),snapshotUrl:M.addAuthToUrl(e.thumbUrl)}}static parseServerPushElement(e){var e=e["MsgContent"],{VideoUrl:e,VideoFormat:t,VideoSecond:s,VideoSize:r,VideoDownloadFlag:i,VideoUUID:n,ThumbUUID:o,ThumbFormat:a,ThumbWidth:l,SnapshotWidth:u,ThumbHeight:c,SnapshotHeight:d,ThumbSize:h,SnapshotSize:g,ThumbDownloadFlag:p,ThumbUrl:_,SnapshotUrl:m}=e;return new vn({videoUrl:e,videoFormat:t,videoSecond:s,videoSize:r,videoDownloadFlag:i,videoUUID:n,thumbUUID:o,thumbFormat:a,thumbWidth:l,snapshotWidth:u,thumbHeight:c,snapshotHeight:d,thumbSize:h,snapshotSize:g,thumbDownloadFlag:p,thumbUrl:_,snapshotUrl:m})}updatePercent(e){this.uploadProgress=Math.min(e,1)}updateVideoUrl(e){e&&(this.content.remoteVideoUrl=e)}updateSnapshotInfo(e){var{snapshotUrl:e,snapshotWidth:t,snapshotHeight:s}=e;M.isEmpty(e)||(this.content.thumbUrl=this.content.snapshotUrl=e),M.isEmpty(t)||(this.content.thumbWidth=this.content.snapshotWidth=Number(t)),M.isEmpty(s)||(this.content.thumbHeight=this.content.snapshotHeight=Number(s))}validateBeforeSend(){var e;return this[Ki]?{isValid:!0}:{isValid:e=""!==this.content.remoteVideoUrl,error:e?null:{message:"content can not be empty"}}}transformToServerFormat(e){var{isMergerMessage:e=!1}=e||{},{remoteVideoUrl:e,videoFormat:t,videoSecond:s,videoSize:r,videoDownloadFlag:i,videoUUID:n,thumbUUID:o,thumbFormat:a,thumbWidth:l,snapshotWidth:u,thumbHeight:c,snapshotHeight:d,thumbSize:h,snapshotSize:g,thumbDownloadFlag:p,thumbUrl:_,snapshotUrl:m}=e?this.payload:this.content;return{MsgType:this.type,MsgContent:{VideoUrl:M.removeAuthToUrl(e),VideoFormat:t,VideoSecond:s,VideoSize:r,VideoDownloadFlag:i,VideoUUID:n,ThumbUUID:o,ThumbFormat:a,ThumbWidth:l,SnapshotWidth:u,ThumbHeight:c,SnapshotHeight:d,ThumbSize:h,SnapshotSize:g,ThumbDownloadFlag:p,ThumbUrl:M.removeAuthToUrl(_),SnapshotUrl:M.removeAuthToUrl(m)}}}}var fn,In=Ki,En=new class{constructor(){this._messageOptionsMap=new Map}init(e){var{notificationCenter:e,helper:t,InnerEvent:s,message:r}=this._core=e;t.registerApi({apiName:"createVideoMessage",context:this}),t.registerExperimentalAPI("createVideoMessage",this,"createCustomUploadVideoMessage"),null!=(t=null==r?void 0:r.messageFactory)&&t.registerElementClass(xi,vn),e.subscribeInnerEvent(s.DESTROY,this._dispose,this)}createVideoMessage(e){var t,s,r;try{var i=this._processVideo(e),n=(e.payload.file=i,null==(t=this._core.store.get("login"))?void 0:t.userId),o=null==(r=null==(s=this._core)?void 0:s.message.messageFactory)?void 0:r.createMessage(Object.assign(Object.assign({},e),{from:n})),a={videoFormat:i.videoFile.type,videoSecond:Gi(i.videoFile.second,0),videoSize:i.videoFile.size,remoteVideoUrl:"",videoUrl:i.videoFile.url,videoUUID:M.generateUUID(i.videoFile),thumbUUID:M.generateUUID(i.videoFile,"jpg"),thumbWidth:i.width||200,thumbHeight:i.height||200,thumbUrl:i.thumbUrl,thumbSize:i.thumbSize,thumbFormat:"jpg"},l=new vn(a);return o.setElement(l),this._messageOptionsMap.set(o.clientSequence,e),o}catch(e){throw e}}createCustomUploadVideoMessage(e){var t,s,r;try{var{store:i,message:n}=this._core,o=(this._validateCustomUploadVideoMessage(e),null==(t=i.get("login"))?void 0:t.userId),{videoUrl:a,videoUuid:l,duration:u,snapshotUrl:c,snapshotUuid:d,videoFileSize:h,videoType:g,snapshotWidth:p,snapshotHeight:_,snapshotFileSize:m,snapshotType:v="jpg"}=(null==(s=null==e?void 0:e.payload)?void 0:s.file)||{},f=null==(r=n.messageFactory)?void 0:r.createMessage(Object.assign(Object.assign({},e),{from:o})),I=new vn({videoFormat:g,videoSecond:u||0,videoSize:h,remoteVideoUrl:a,videoUrl:a,videoUUID:l,thumbUUID:d,thumbWidth:p||200,thumbHeight:_||200,thumbUrl:c,thumbSize:m,thumbFormat:v,isCustomUpload:!0});return f.setElement(I),this._messageOptionsMap.set(f.clientSequence,e),f}catch(e){throw e}}upload(r){return I(this,void 0,void 0,function*(){var e=r.getElements()[0],t=this._messageOptionsMap.get(r.clientSequence).payload["file"],t=(this._validateBeforeUploadVideo(t),yield this._performVideoUpload(e,r,t)),{location:t,snapshotInfo:s}=t,t=M.addAuthToUrl(t);return e.updateVideoUrl(t),M.isEmpty(s)||e.updateSnapshotInfo(s),r})}_validateBeforeUploadVideo(e){var t=(null==(t=this._core)?void 0:t.helper)["ChatError"];if(e.videoFile.size>mn)throw new t({message:"File size exceeds limit: "+wi(mn)});if(0===e.videoFile.size)throw new t({code:2108});if(-1===_n.indexOf(e.videoFile.type))throw new t({code:2352})}_validateCustomUploadVideoMessage(e){var{isEmpty:t,isNumber:s}=this._core["utils"],{videoUrl:e,videoUuid:r,duration:i,snapshotUrl:n,snapshotUuid:o}=(null==(e=null==e?void 0:e.payload)?void 0:e.file)||{};if(t(e)||t(r)||!s(i)||t(n)||t(o))throw new Error("Invalid video message options: missing required fields (videoUrl, videoUuid, duration, snapshotUrl, snapshotUuid)")}_performVideoUpload(r,i,s){return I(this,void 0,void 0,function*(){var e=i["to"],{response:e,uploadOptions:t}=yield tn.uploadToCOS({uploadFileType:2,file:s,to:e,message:i,onProgress:e=>{var t,s;r.updatePercent(e),null!=(s=null==(t=this._messageOptionsMap.get(i.clientSequence))?void 0:t.onProgress)&&s.call(t,e)}});return{snapshotInfo:yield this._getSnapshotInfoByUrl(t.requestSnapshotUrl),location:e.location}})}_processVideo(e){var r,i;try{var n=(null==(r=this._core)?void 0:r.helper)["ChatError"],{IN_MINI_APP:o,IN_BROWSER:a}=null==(i=this._core)?void 0:i.utils;let t=e.payload["file"],s={};if(o&&(s=this._processMiniVideoFile(t),t.name=s.name,t.url=s.url,t.type=s.type),a){let e=M.extractFileFromInput(t);if(!e)throw new n({message:"Invalid file. Pass either `e.target` (from file input) or a File object"});t=e,s=this._processWebVideoFile(t)}return t.videoFile=s,t.thumbUrl="",t.thumbSize=0,t}catch(e){throw console.warn(Vi+" _processFile error:",e),e}}_processMiniVideoFile(e){var{IN_ALIPAY_MINI_APP:t,IN_UNI_NATIVE_APP:s}=null==(t=this._core)?void 0:t.utils,r=(null==(r=this._core)?void 0:r.helper)["ChatError"];if(t)throw new r({message:"VideoUnsupportedInAlipay"});if(bi(e))throw new r({message:"FileUnsupportedInMiniApp"});let i=(e=Array.isArray(e.tempFiles)?e.tempFiles[0]:e).tempFilePath.slice(e.tempFilePath.lastIndexOf(".")+1).toLowerCase();return s&&(i=e.fileType||i),{url:e.tempFilePath,name:e.tempFilePath.slice(e.tempFilePath.lastIndexOf("/")+1),size:e.size||1,second:e.duration||0,type:i}}_processWebVideoFile(e){var{name:t,size:s=1,duration:r=0,type:i}=e,i=i.split("/")[1];return{url:window.URL.createObjectURL(e),name:t,size:s,second:r,type:i}}_getSnapshotInfoByUrl(n){return I(this,void 0,void 0,function*(){var e=this._core["ssoLog"];try{e.debug("_getSnapshotInfoByUrl",Vi+" _getSnapshotInfoByUrl url:"+n);var t,s,r,i=((yield function(n,o){return I(this,void 0,void 0,function*(){try{var e="im_cos_msg.video_cover",{helper:t,channel:s}=o,r=t.generateCosSpecifiedData({servcmd:e,data:n}),i=r.head.seq+e;return yield s.sendPacket(r,{requestId:i})}catch(e){throw console.warn("getSnapshotInfo error:",e),e}})}({version:1,platform:M.getPlatform(),cover_name:Pi(Ni(99999)),snapshot_url:n},this._core))||{})["download_url"];return(e.debug("_getSnapshotInfoByUrl",Vi+" _getSnapshotInfoByUrl OK snapshotUrl:"+i),M.isEmpty(i))?{}:(t=M.addAuthToUrl(i),{width:s=0,height:r=0}=yield M.probeImageWidthHeight(t),{snapshotUrl:t,snapshotWidth:s,snapshotHeight:r})}catch(e){throw e}})}_reset(){this._messageOptionsMap.clear()}_dispose(){this._reset();var{notificationCenter:e,InnerEvent:t}=this._core;e.unSubscribeInnerEvent(t.DESTROY,this._dispose,this)}};class Sn{constructor(e){this.uploadProgress=0,this.type=Fi,this[fn]=!1,this[Ki]=e.isCustomUpload||!1,this.content={downloadFlag:2,second:e.second,size:e.size,url:M.generateURL(e.url,{needAddAuthToUrl:!this[Ki]}),remoteAudioUrl:M.addAuthToUrl(e.url||""),uuid:e.uuid}}static parseServerPushElement(e){var e=e["MsgContent"],{Url:e,Download_Flag:t,Second:s,Size:r,UUID:i}=e;return new Sn({url:e,downloadFlag:t,second:s,size:r,uuid:i})}updatePercent(e){this.uploadProgress=Math.min(e,1)}updateAudioUrl(e){this.content.remoteAudioUrl=e}validateBeforeSend(){var e;return this[Ki]?{isValid:!0}:{isValid:e=""!==this.content.remoteAudioUrl,error:e?null:{message:"content can not be empty"}}}transformToServerFormat(e){var{isMergerMessage:e=!1}=e||{},{uuid:e,downloadFlag:t,remoteAudioUrl:s,size:r,second:i}=e?this.payload:this.content;return{MsgType:this.type,MsgContent:{Url:M.removeAuthToUrl(s),Download_Flag:t,Second:i,Size:r,UUID:e}}}}fn=Ki;var Cn,Mn,yn,On=new class{constructor(){this._messageOptionsMap=new Map}init(e){var{notificationCenter:e,helper:t,InnerEvent:s,message:r}=this._core=e;t.registerApi({apiName:"createAudioMessage",context:this}),t.registerExperimentalAPI("createAudioMessage",this,"createCustomUploadAudioMessage"),null!=(t=null==r?void 0:r.messageFactory)&&t.registerElementClass(Fi,Sn),e.subscribeInnerEvent(s.DESTROY,this._dispose,this)}createAudioMessage(e){var t,s,r;try{var i=e.payload["file"],i=this._processAudioFile(e.payload.file),n=(e.payload.file=i,null==(t=this._core.store.get("login"))?void 0:t.userId),o=null==(r=null==(s=this._core)?void 0:s.message.messageFactory)?void 0:r.createMessage(Object.assign(Object.assign({},e),{from:n})),a={second:Math.floor((i.duration||i.second)/1e3),size:i.fileSize||i.size||1,url:i.tempFilePath||i.uri||i.url,uuid:M.generateUUID(i)},l=new Sn(a);return o.setElement(l),this._messageOptionsMap.set(o.clientSequence,e),o}catch(e){throw e}}createCustomUploadAudioMessage(e){var t,s,r;try{this._validateCustomUploadOptions(e);var{store:i,message:n}=this._core,o=null==(t=i.get("login"))?void 0:t.userId,{url:a,uuid:l,duration:u,fileSize:c}=(null==(s=null==e?void 0:e.payload)?void 0:s.file)||{},d=null==(r=n.messageFactory)?void 0:r.createMessage(Object.assign(Object.assign({},e),{from:o})),h=new Sn({second:u,size:c||1,url:a,uuid:l,isCustomUpload:!0});return d.setElement(h),this._messageOptionsMap.set(d.clientSequence,e),d}catch(e){throw e}}upload(s){return I(this,void 0,void 0,function*(){var{ssoLog:e,utils:{safeStringify:t}}=this._core,e=(e.debug("upload",Vi+" uploadAudio message:"+t(s)),this._messageOptionsMap.get(s.clientSequence).payload)["file"],t=(this._validateBeforeUploadAudio(e),s.getElements()[0]),e=yield this._performAudioUpload(t,s,e),e=M.addAuthToUrl(null==e?void 0:e.location);return t.updateAudioUrl(e),s})}_validateBeforeUploadAudio(e){var t=(null==(t=this._core)?void 0:t.helper)["ChatError"];if(!e)throw new t({code:2300});if(20971520<e.size)throw new t({message:"File size exceeds limit: "+wi(20971520)});if(0===e.size)throw new t({code:2108})}_performAudioUpload(r,i,t){return I(this,void 0,void 0,function*(){var e=i["to"],e=(yield tn.uploadToCOS({uploadFileType:3,file:t,to:e,message:i,onProgress:e=>{var t,s;r.updatePercent(e),null!=(s=null==(t=this._messageOptionsMap.get(i.clientSequence))?void 0:t.onProgress)&&s.call(t,e)}}))["response"];return e})}_processAudioFile(e){var{IN_MINI_APP:t,IN_BROWSER:s}=null==(t=this._core)?void 0:t.utils;return t?this._processMiniFile(e):s?this._processWebFile(e):void 0}_processMiniFile(e){return{url:e.tempFilePath,name:e.tempFilePath.slice(e.tempFilePath.lastIndexOf("/")+1),size:e.fileSize,second:e.duration,type:e.tempFilePath.slice(e.tempFilePath.lastIndexOf(".")+1).toLowerCase()}}_processWebFile(e){var t;return e.tempFilePath||e.uri||(t=URL.createObjectURL(e),e.tempFilePath=t),e}_validateCustomUploadOptions(e){var t=this._core["utils"]["isEmpty"],{url:e,uuid:s,duration:r}=(null==(e=null==e?void 0:e.payload)?void 0:e.file)||{};if(t(e)||t(s)||t(r))throw new Error("Invalid audio message options")}_reset(){this._messageOptionsMap.clear()}_dispose(){this._reset();var{notificationCenter:e,InnerEvent:t}=this._core;e.unSubscribeInnerEvent(t.DESTROY,this._dispose,this)}};let An={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}},Tn={createImageMessage:An,createAudioMessage:An,createVideoMessage:An,createFileMessage:An},Rn={createImageMessage:!0,createAudioMessage:!0,createVideoMessage:!0,createFileMessage:!0},Dn={TIMImageElem:ln,TIMFileElem:pn,TIMVideoFileElem:En,TIMSoundElem:On},bn=new class{constructor(){this.name="RichMediaMessage"}install(e){let{OuterConstant:{MSG_AUDIO:t,MSG_FILE:s,MSG_IMAGE:r,MSG_VIDEO:i}}=(this._core=e)["constants"];dn.init(e),ln.init(e),pn.init(e),En.init(e),On.init(e),tn.init(e),M.init(e),e.helper.registerApi({apiName:"sendMessage",context:this,matcher:e=>[t,s,r,i].includes(e[0].type)}),e.helper.registerValidateConfig({auth:Rn,params:Tn})}sendMessage(r,i){return I(this,void 0,void 0,function*(){var e,t,s;try{return this._isCustomUpload(r)||(yield this._upload(r)),yield null==(s=null==(t=null==(e=this._core)?void 0:e.message)?void 0:t.messageSender)?void 0:s.sendMessage(r,i)}catch(e){throw e}})}_upload(s){return I(this,void 0,void 0,function*(){let{ssoLog:t,utils:{safeStringify:e}}=this._core;if(t.debug("_upload"," uploadFile message:"+e(s)),!0!==s._relayFlag)try{let e=Dn[s.type];e&&(yield e.upload(s),t.info("_upload"," type:"+s.type))}catch(t){throw s.status=Ri.FAIL,t instanceof Error&&(t.data={message:s}),this._core.message.messageDataHandler.storeConversationMessage(s),t}})}_isCustomUpload(e){return!0===(null==(e=null==(e=e._elements)?void 0:e[0])?void 0:e[Ki])}},A=new class{init(e){this.core=e}},Nn=e=>{var{OuterConstant:t,utils:{isString:s}}=A["core"];return s(e)&&e.slice(0,3)===t.CONV_C2C},Ln=e=>{var{OuterConstant:t,utils:{isString:s}}=A["core"];return s(e)&&e.slice(0,5)===t.CONV_GROUP},Pn=e=>{var{OuterConstant:t,utils:{isString:s}}=A["core"];return s(e)&&e===t.CONV_SYSTEM},Gn=e=>({lastTime:(null==e?void 0:e.time)||(null==e?void 0:e.lastTime)||0,lastSequence:(null==e?void 0:e.sequence)||(null==e?void 0:e.lastSequence)||0,fromAccount:(null==e?void 0:e.from)||(null==e?void 0:e.fromAccount)||"",messageForShow:A.core.common.getMessagePreviewText(null==e?void 0:e.type,null==e?void 0:e.payload),payload:(null==e?void 0:e.payload)||null,type:(null==e?void 0:e.type)||"",isRevoked:(null==e?void 0:e.isRevoked)||!1,cloudCustomData:(null==e?void 0:e.cloudCustomData)||"",onlineOnlyFlag:(null==e?void 0:e._onlineOnlyFlag)||!1,nick:(null==e?void 0:e.nick)||"",nameCard:(null==e?void 0:e.nameCard)||"",version:(null==e?void 0:e.version)||0,isPeerRead:(null==e?void 0:e.isPeerRead)||!1,revoker:(null==e?void 0:e.revoker)||null});function wn(e){var t=A.core["OuterConstant"];let s="";return 0===e?s=t.MSG_REMIND_ACPT_AND_NOTE:1===e?s=t.MSG_REMIND_DISCARD:2===e?s=t.MSG_REMIND_ACPT_NOT_NOTE:3===e&&(s=t.NOT_RECEIVE_OFFLINE_PUSH_EXCEPT_AT),s}function Un(e,t){var s=A.core["helper"],s=new s.ChatError({functionName:e,code:(null==t?void 0:t.errorCode)||(null==t?void 0:t.code),message:(null==t?void 0:t.errorInfo)||(null==t?void 0:t.message)});throw console.error(e+" fail:",s),s}class kn{constructor(e){this.conversationID=e.conversationID||"",this.unreadCount=e.unreadCount||0,this.type=e.type||"",this.lastMessage=Gn(e.lastMessage),this.peerReadTime=e.peerReadTime||0,this.groupAtInfoList=[],this.remark=e.remark||"",this.isPinned=e.isPinned||!1,this.messageRemindType=e.messageRemindType,this.markList=e.markList||[],this.customData=e.customData||"",this.conversationGroupList=e.conversationGroupList||[],this.draftText=e.draftText||"",this.userProfile=e.userProfile,this.groupProfile=e.groupProfile,this.subType=e.subType||"",this._isInfoCompleted=!1,this._init()}_init(){var{OuterConstant:e,utils:{isUndefined:t}}=A["core"];t(this.userProfile)&&this.type===e.CONV_C2C?this.userProfile={}:t(this.groupProfile)&&this.type===e.CONV_GROUP&&(this.groupProfile={}),this.subType&&this.type===e.CONV_GROUP&&(this.subType=this.groupProfile.type||"")}updateUnreadCount(e){var{OuterConstant:t,utils:{isUndefined:s}}=A["core"],{nextUnreadCount:e,isFromGetConversations:r,isUnreadC2CMessage:i}=e;s(e)||(this.subType!==t.GRP_AVCHATROOM?r&&this.type===t.CONV_GROUP||i&&this.type===t.CONV_C2C?this.unreadCount=e:this.unreadCount+=e:this.unreadCount=0)}updateLastMessage(e){this.lastMessage=Gn(e)}reduceUnreadCount(){return 1<=this.unreadCount&&(--this.unreadCount,!0)}isLastMessageRevoked(e){var t=A["core"]["OuterConstant"],{sequence:e,time:s}=e;return this.type===t.CONV_C2C&&e===this.lastMessage.lastSequence&&s===this.lastMessage.lastTime||this.type===t.CONV_GROUP&&e===this.lastMessage.lastSequence}setLastMessageRevoked(e){this.lastMessage.isRevoked=e}setLastMessageRevoker(e){this.lastMessage.revoker=e}setDraftText(e){this.draftText=e}updateGroupAtInfoList(e){var{common:{updateGroupAtInfo:t}}=A["core"];t(e,this.groupAtInfoList)}clearGroupAtInfoList(){this.groupAtInfoList.length=0}getProfileCompleted(){return this._isInfoCompleted}setProfileCompleted(){this._isInfoCompleted=!0}}(L=Cn=Cn||{})[L.OFF=0]="OFF",L[L.ON=1]="ON",Mn=Mn||{},Mn[Mn.ONLY_CONVERSATIONID=1]="ONLY_CONVERSATIONID",(y=yn=yn||{})[y.CONV_NOT_FOUND=2500]="CONV_NOT_FOUND",y[y.USER_OR_GRP_NOT_FOUND=2501]="USER_OR_GRP_NOT_FOUND",y[y.CONV_UN_RECORDED_TYPE=2502]="CONV_UN_RECORDED_TYPE";var T=new class{constructor(){this._name="ConversationDataHandler",this._totalUnreadCount=0,this._groupAtTipsList=[]}init(e){var{helper:t,notificationCenter:s,appStore:{conversationStore:r},constants:{WORKFLOW_NAME:i,WORKFLOW_STEP:n},InnerEvent:{SYNC_CONVERSATION_LIST:o,MESSAGE_PUSH:a,NEW_MESSAGE:l,MESSAGE_DELETED:u,MESSAGE_REVOKED:c,MESSAGE_MODIFIED:d,CONVERSATION_UPDATED:h,LOGOUT:g,DESTROY:p},InnerEventSubType:{C2C_MESSAGE_PEER_READ:_}}=this._core=e,r=(this._conversationStore=r,t.registerWorkflowStep(i.SYNC_SERVER_INFO_AFTER_LOGIN,n.CONVERSATION_UPDATE_AFTER_UNREAD_SYNC_FINISHED,this._handleUnreadSyncFinished,this),t.registerWorkflowStep(i.SYNC_SERVER_INFO_AFTER_LOGIN,n.CONVERSATION_UPDATE_AFTER_GROUP_LIST_SYNC_FINISHED,this._handleGroupListSyncFinished,this),t.registerWorkflowStep(i.RECEIVE_C2C_NEW_MESSAGE,n.CREATE_OR_UPDATE_CONVERSATION_BY_RECEIVE_NEW_MESSAGE,this._handleNewMessage,this),t.registerWorkflowStep(i.RECEIVE_C2C_NEW_MESSAGE,n.CONVERSATION_UPDATE_AFTER_UNREAD_SYNC_FINISHED,this._handleUnreadSyncFinished,this),t.registerWorkflowStep(i.RECEIVE_GROUP_NEW_MESSAGE,n.CREATE_OR_UPDATE_CONVERSATION_BY_RECEIVE_NEW_MESSAGE,this._handleNewMessage,this),t.registerWorkflowStep(i.SYNC_SERVER_INFO_AFTER_RE_ONLINE,n.CONVERSATION_UPDATE_AFTER_UNREAD_SYNC_FINISHED,this._handleUnreadSyncFinished,this),t.registerWorkflowStep(i.RECEIVE_GROUP_TIPS_NOTIFICATION,n.CREATE_OR_UPDATE_CONVERSATION_BY_RECEIVE_NEW_MESSAGE,this._handleNewMessage,this),s)["InnerEventSubType"]["GROUP_AT_TIPS"];s.subscribeInnerEvent(o,this._handleConversationSynced,this),s.subscribeInnerEvent(l,this._handleNewMessage,this),s.subscribeInnerEvent(a,r,this._handleNewGroupAtTips,this),s.subscribeInnerEvent(u,this._handleMessageDeleted,this),s.subscribeInnerEvent(c,this._handleMessageRevoked,this),s.subscribeInnerEvent(d,this._handleMessageModified,this),s.subscribeInnerEvent(h,this._handleConversationUpdated,this),s.subscribeInnerEvent(a,_,this._handleMessageRead,this),s.subscribeInnerEvent(g,this._reset,this),s.subscribeInnerEvent(p,this._dispose,this),e.ssoLog.debug(this._name+".init")}_handleConversationSynced(e){this.updateLocalConversationList({conversationUpdateFieldList:e.conversationUpdateFieldList||[],isFromGetConversations:!0,updateUnreadCount:!0}),this.emitConversationListUpdate()}_handleUnreadSyncFinished(e){let{WORKFLOW_STEP:t}=this._core["constants"],{conversationUpdateFieldList:s=[],groupTipList:r=[],isUnreadC2CMessage:i}=e.result[t.UNREAD_MESSAGE_SYNC]||{},n=!1;s.forEach(e=>{var{conversationID:e,unreadCount:t}=e,e=this.getLocalConversation(e);e&&e.unreadCount!==t&&(e.updateUnreadCount({nextUnreadCount:t,isUnreadC2CMessage:i}),n=!0)}),n&&this.emitConversationListUpdate(),this._handleGroupAtTipsSynced(r)}_handleGroupAtTipsSynced(t){var s;for(let e=0;e<t.length;e++)if(12===t[e].Event){if(null!=(s=t[e].GroupTips[0].MsgBody)&&s.TopicId)continue;this._handleNewGroupAtTips(t[e])}}_handleGroupListSyncFinished(e){let r,{WORKFLOW_STEP:t}=this._core.constants,i=e.result[t.GROUP_LIST_SYNC]||[],{CONV_GROUP:n}=this._core.OuterConstant,o=!1;for(let s=0;s<i.length;s++){let e=i[s],t=""+n+e.groupID;var a;this.hasLocalConversation(t)&&((a=this.getLocalConversation(t)).groupProfile=JSON.parse(JSON.stringify(e)),a.lastMessage.lastSequence<e.nextMessageSeq&&(a.lastMessage.lastSequence=e.nextMessageSeq-1),a.subType||(a.subType=e.type),0<(null==(r=e._groupAtInfoList)?void 0:r.length)&&this._handleNewGroupAtTips({GroupTips:e._groupAtInfoList}),o=!0)}o&&this.emitConversationListUpdate()}_handleNewMessage(e){var t,{conversationUpdateFieldList:e=[],isInstantMessage:s=!0,isUnreadC2CMessage:r=!1,updateUnreadCount:i=!0}=e.result||{};0===e.length||({isTopic:t}=this._core["common"],t(e[0].conversationID))||(this.updateLocalConversationList({conversationUpdateFieldList:e,isInstantMessage:s,isUnreadC2CMessage:r,isFromGetConversations:!1,updateUnreadCount:i}),0<e.filter(e=>this._isConversationNeedShow(e.conversationID)).length&&this.emitConversationListUpdate())}_handleNewGroupAtTips(e){var{GroupTips:e=[]}=e;e.forEach(e=>{var{GroupAtTips:t,MsgBody:s,MsgRandom:r,ClientSeq:i}=e;let n={};t?n=this._convertGroupAtTipsKey(t):s?n=Object.assign({},this._convertGroupAtTipsKey(s)):e.groupAtType&&(n=Object.assign({},e)),n.__random=r,n.__sequence=i,this._groupAtTipsList.push(n)}),console.log(this._name+"._handleNewGroupAtTips groupAtTipsList: "+JSON.stringify(this._groupAtTipsList)),this._updateGroupAtInfoList()}_convertGroupAtTipsKey(e){var{From_Account:e,GroupId:t,MsgSeq:s,GroupAtType:r}=e;return{from:e,groupID:t,sequence:s,groupAtType:r}}_updateGroupAtInfoList(){if(0!==this._groupAtTipsList.length){let{common:e,OuterConstant:r}=this._core,i=e.getCurrentUserID(),n=!1;this._groupAtTipsList.forEach(t=>{var{groupID:s,from:e}=t;if(e!==i){let e=this.getLocalConversation(""+r.CONV_GROUP+s);e&&(e.updateGroupAtInfoList(t),n=!0)}}),n&&this.emitConversationListUpdate(),this._groupAtTipsList.length=0}}_handleMessageDeleted(t){console.log(this._name+"._handleMessageDeleted, conversationID:",t);var s,{message:{messageDataHandler:r},OuterConstant:i}=this._core,n=(null==r?void 0:r.getLocalMessageList(t))||[];let o={};for(let e=(n.length||0)-1;0<=e;e--)if(!n[e].isDeleted){o=n[e];break}r=this.getLocalConversation(t);if(r){let e=!1;r.lastMessage.lastSequence===o.sequence&&r.lastMessage.lastTime===o.time||(null!=(s=null==(s=this._core)?void 0:s.helper)&&s.isEmpty(o)&&(o=void 0),r.updateLastMessage(o),e=!0),t.startsWith(i.CONV_C2C)&&this.updateUnreadCount(t),e&&(this.emitConversationListUpdate(),console.log(this._name+`._handleMessageDeleted. update conversationID:${t} with lastMessage:`,r.lastMessage))}}_handleMessageRevoked(e){let{messageList:r=[],updateUnreadCount:i=!0}=e;if(console.log(this._name+"._handleMessageRevoked messageList:"+r.length),0!==r.length){let t=null,s=!1;r.forEach(e=>{(t=this.getLocalConversation(e.conversationID))&&(i&&t.reduceUnreadCount()&&(s=!0),t.isLastMessageRevoked({sequence:e.sequence,time:e.time}))&&(t.setLastMessageRevoked(!0),t.setLastMessageRevoker(e.revoker),s=!0)}),s&&this.emitConversationListUpdate()}}_handleMessageModified(e){console.log(this._name+"._handleMessageModified",JSON.stringify(e));var{conversationID:t,messageList:s}=e,e=this.getLocalConversation(t),{utils:{isEmpty:r},common:{getMessagePreviewText:i}}=this._core;if(!r(e)){r=e["lastMessage"];if(r){let e=(null==s?void 0:s[0])||{};r.lastTime===e.time&&r.lastSequence===e.sequence&&r.version!==e.version&&(r.type=e.type,r.payload=e.payload,r.messageForShow=i(e.type,e.payload),r.cloudCustomData=e.cloudCustomData,r.version=e.version,this.emitConversationListUpdate(),console.log(this._name+` conversationID:${t} lastMessage updated`))}}}_handleConversationUpdated(e){this.emitConversationListUpdate(null==e?void 0:e.needSort)}updateLocalConversationList(e){var t=e["isFromGetConversations"],e=this._getTmpConversationListMapping(e)["newConversationList"];this._sortConversationList(),t||this._updateNewConversationProfile(e),this._core.ssoLog.debug("updateLocalConversationList"," newConversationList: "+e.length)}_getTmpConversationListMapping(e){let n=this._core["OuterConstant"],{conversationUpdateFieldList:o,isFromGetConversations:a,isInstantMessage:l,isUnreadC2CMessage:u=!1,updateUnreadCount:c}=e,d=[],t=null==o?void 0:o.length;for(let i=0;i<t;i++){let t=new kn(o[i]),{conversationID:s,type:r}=t;if(!function(e){var t=A.core["OuterConstant"];let s;return"@TLS#ERROR"===(s=e.startsWith(t.CONV_C2C)?e.replace(t.CONV_C2C,""):s)||"@TLS#NOT_FOUND"===s}(s))if(this.hasLocalConversation(s)){let e=this.getLocalConversation(s);a?(this.setLocalConversation(s,t),r===n.CONV_C2C?t.unreadCount=(null==e?void 0:e.unreadCount)||0:r===n.CONV_GROUP&&(t.groupProfile=JSON.parse(JSON.stringify(null==e?void 0:e.groupProfile)))):(this._mergeConversationInfo({conversationID:s,tmpConversation:t,lastMessage:o[i].lastMessage,isFromGetConversations:a,isInstantMessage:l}),this._patchLastMessage({conversationID:s,lastMessage:o[i].lastMessage,isInstantMessage:l}),!0===c&&null!=e&&e.updateUnreadCount({nextUnreadCount:t.unreadCount,isFromGetConversations:a,isUnreadC2CMessage:u}))}else d.push(t),this.setLocalConversation(s,t)}return{newConversationList:d}}_mergeConversationInfo(e){var{conversationID:e,tmpConversation:t,lastMessage:s,isFromGetConversations:r,isInstantMessage:i}=e,e=this.getLocalConversation(e),n=["unreadCount","allowType","adminForbidType","payload"],{utils:{isUndefined:r,isEmpty:o},common:{deepMerge:a}}=(!1===i&&n.push("lastMessage"),r&&n.push("isPinned"),this._core);r(i)&&s&&null===(null==e?void 0:e.lastMessage.payload)&&(e.lastMessage.payload=s.payload),o(null==e?void 0:e.lastMessage.revoker)||(e.lastMessage.revoker=null),a(e,t,n,[null,void 0,"",0,NaN])}_patchLastMessage(e){let i=this._core["OuterConstant"],{conversationID:t,lastMessage:n,isInstantMessage:o}=e,a=this.getLocalConversation(t);if(a&&n){let{payload:e,nameCard:t,nick:s,cloudCustomData:r=""}=n;o&&(e&&(a.lastMessage.payload=e),a.type===i.CONV_GROUP)&&(a.lastMessage.nameCard=t,a.lastMessage.nick=s),a.lastMessage.cloudCustomData!==r&&(a.lastMessage.cloudCustomData=r)}}_sortConversationList(){let{isEmpty:t}=this._core["utils"],e=[...this._conversationStore.getConversationMap()],s=[],r=[],i=[],n=[];e.forEach(e=>{(!0===e[1].isPinned?t(e[1].lastMessage.lastTime)?r:s:t(e[1].lastMessage.lastTime)?n:i).push(e)});var o=s.sort((e,t)=>t[1].lastMessage.lastTime-e[1].lastMessage.lastTime).concat(r).concat(i.sort((e,t)=>t[1].lastMessage.lastTime-e[1].lastMessage.lastTime)).concat(n);this._updateConversationMapFromList(o)}_updateNewConversationProfile(e){if(0!==e.length){let s=[],r=[],{CONV_GROUP:i,CONV_C2C:n}=this._core["OuterConstant"];e.forEach(e=>{var{conversationID:t,type:e}=e;if(e===n){let e=t.replace(n,"");s.push(e)}else if(e===i){let e=t.replace(i,"");r.push(e)}}),0<s.length&&this._updateC2CConversation(s),0<r.length&&this._updateGroupConversation(r)}}_updateC2CConversation(e){let t,{OuterConstant:{CONV_C2C:i},appStore:{userStore:n},user:s}=this._core,o=!1;null!=(t=s.userProfile)&&t.getUserProfile({userIDList:e}).then(e=>{((null==e?void 0:e.data)||[]).forEach(t=>{var s=t["userID"],r=this.getLocalConversation(""+i+s);if(r){let e=(null==(s=n.getFriend(s))?void 0:s.remark)||"";r.remark=e,r.userProfile=t,o=!0}}),o&&this.emitConversationListUpdate()}).catch(e=>{})}_updateGroupConversation(e){let{OuterConstant:{CONV_GROUP:s},appStore:{groupStore:r}}=this._core,i=!1;e.forEach(e=>{var t=r.getGroup(e),e=this.getLocalConversation(""+s+e);t&&e&&(e.groupProfile=t,i=!0)}),i&&this.emitConversationListUpdate()}_handleMessageRead(e){let{CONV_C2C:r}=this._core["OuterConstant"],{C2cNotifyMsgArray:t=[]}=e||{};t.forEach(e=>{let{To_Account:s,UinPairReadArray:t=[]}=(null==e?void 0:e.C2cReadedReceipt)||{};null!=t&&t.forEach(e=>{var e=e["LastReadTime"],t=""+r+s;this._updateConversationReadInfo({conversationID:t,peerReadTime:e}),this._updateMessageListPeerRead({conversationID:t,peerReadTime:e})})})}_updateConversationReadInfo(e){var{appStore:t,utils:{isEmpty:s},common:{getCurrentUserID:r}}=this._core,{conversationID:i,peerReadTime:n}=e,o=t.conversationStore.getConversationMap();if(o.has(i)){let e=o.get(i);e.peerReadTime=n;o=null==e?void 0:e.lastMessage;s(o)||o.fromAccount===r()&&o.lastTime<=n&&!o.isPeerRead&&(o.isPeerRead=!0,t.conversationStore.updateConversation(i,{lastMessage:o}))}}_updateMessageListPeerRead(e){let{notificationCenter:t,OuterEvent:s,message:r}=this._core,{conversationID:i,peerReadTime:n}=e,o=r.messageDataHandler.getLocalMessageList(i),a=r.messageDataHandler.getSparseMessageList(i),l=[];o.forEach(e=>{e.time<=n&&!e.isPeerRead&&"out"===e.flow&&(e.isPeerRead=!0,l.push(e))}),a.forEach(e=>{e.time<=n&&!e.isPeerRead&&"out"===e.flow&&(e.isPeerRead=!0,l.push(e))}),t.emitOuterEvent(s.MESSAGE_READ_BY_PEER,{name:s.MESSAGE_READ_BY_PEER,data:l})}_isConversationNeedShow(e){var{OuterConstant:{CONV_GROUP:t,GRP_ROOM:s,GRP_LIVE:r},utils:{isUndefined:i}}=this._core,e=this.getLocalConversation(e);return!(!i(e)&&(i=e.type===t&&(null==(i=e.groupProfile)?void 0:i.type)===s,t=e.type===t&&(null==(s=e.groupProfile)?void 0:s.type)===r,i||t))}updateUnreadCount(e,t=!0){let s,r,i=!1;var n,o=this.getLocalConversation(e),a=null==(r=null==(s=this._core)?void 0:s.message.messageDataHandler)?void 0:r.getLocalMessageList(e);return o&&(n=o.unreadCount,a=null==a?void 0:a.filter(e=>!e.isRead&&!e._onlineOnlyFlag&&!e.isDeleted).length,console.log(this._name+`._updateUnreadCount conversationID:${e} currentUnreadCount:${n} newUnreadCount:`+a),n!==a)&&(o.unreadCount=a,(i=!0)===t)&&this.emitConversationListUpdate(),i}emitConversationListUpdate(e=!1){e&&this._sortConversationList();var e=this._core["OuterEvent"]["CONVERSATION_LIST_UPDATED"],t=this.getLocalConversationList();this._emitEvent({name:e,data:t}),this._emitTotalUnreadCountUpdate()}_emitTotalUnreadCountUpdate(){var e,t=this.getTotalUnreadMessageCount();this._totalUnreadCount!==t&&(this._core.ssoLog.debug("_emitTotalUnreadCountUpdate",` from ${this._totalUnreadCount} to `+t),this._totalUnreadCount=t,this._emitEvent({name:null==(e=this._core)?void 0:e.OuterEvent.TOTAL_UNREAD_MESSAGE_COUNT_UPDATED,data:t}))}_emitEvent(e){var t;null!=(t=this._core)&&t.notificationCenter.emitOuterEvent(e.name,e)}getTotalUnreadMessageCount(){let{OuterConstant:t,utils:{isEmpty:s}}=this._core,e=this.getLocalConversationList(),r=0;return e.forEach(e=>{e.type===t.CONV_SYSTEM||!s(e.messageRemindType)&&e.messageRemindType!==t.MSG_REMIND_ACPT_AND_NOTE||(r+=e.unreadCount)}),r}getLocalConversationList(){return[...this._conversationStore.getConversationMap().values()].filter(e=>this._isConversationNeedShow(e.conversationID))}hasLocalConversation(e){return this._conversationStore.getConversationMap().has(e)}getLocalConversation(e){return this._conversationStore.getConversationMap().get(e)}setLocalConversation(e,t){return this._conversationStore.getConversationMap().set(e,t)}deleteLocalConversation(e){this._conversationStore.getConversationMap().delete(e)}_updateConversationMapFromList(e){this._clearConversationMap();for(var[t,s]of e)this.setLocalConversation(t,s)}_clearConversationMap(){this._conversationStore.getConversationMap().clear()}patchMessageRemindType(e,t){let s=!1;e.forEach(e=>{e=this.getLocalConversation(e);(null==e?void 0:e.messageRemindType)!==t&&(e.messageRemindType=t,s=!0)}),console.log(this._name+`.patchMessageRemindType conversationIDList:${e} messageRemindType:${t} hasUpdated:`+s),s&&this.emitConversationListUpdate()}markMessageAsRead(e){let{messageDataHandler:t}=this._core["message"],{conversationID:s,lastReadTime:i=0,lastReadSequence:n=0}=e,o=null==t?void 0:t.getLocalMessageList(s);if(0!==o.length){let e=o["length"];for(let r=e-1;0<=r;r--){let e=o[r],t=i&&e.time>i,s=n&&e.sequence>n;if(!t&&!s){if("in"===e.flow&&e.isRead)break;e.setIsRead(!0)}}}}appendToPinnedConversation(e){var t=[...this._conversationStore.getConversationMap().entries()],s=t.findIndex(e=>!1===e[1].isPinned);t.splice(s,0,[e.conversationID,e]),this._updateConversationMapFromList(t),this.emitConversationListUpdate()}_reset(){this._clearConversationMap(),this._totalUnreadCount=0,this._groupAtTipsList=[]}_dispose(){var{notificationCenter:e,InnerEvent:{NEW_MESSAGE:t,MESSAGE_DELETED:s,MESSAGE_REVOKED:r,MESSAGE_MODIFIED:i,CONVERSATION_UPDATED:n,LOGOUT:o,DESTROY:a,SYNC_CONVERSATION_LIST:l}}=this._core,{GROUP_AT_TIPS:u}=e["InnerEventSubType"];e.unSubscribeInnerEvent(t,this._handleNewMessage,this),e.unSubscribeInnerEvent(t,u,this._handleNewGroupAtTips,this),e.unSubscribeInnerEvent(s,this._handleMessageDeleted,this),e.unSubscribeInnerEvent(r,this._handleMessageRevoked,this),e.unSubscribeInnerEvent(i,this._handleMessageModified,this),e.unSubscribeInnerEvent(n,this._handleConversationUpdated,this),e.unSubscribeInnerEvent(l,this._handleConversationSynced,this),e.unSubscribeInnerEvent(o,this._reset,this),e.unSubscribeInnerEvent(a,this._dispose,this)}},Fn=new class{constructor(){this._name="GetConversationList"}init(e){e=(this._core=e).helper;e.registerApi({apiName:"getConversationList",context:this})}getConversationList(e){return I(this,void 0,void 0,function*(){return{code:0,data:{conversationList:this._getConversationList(e),isSyncCompleted:this._core.conversation.syncConversationHandler.isSyncCompleted()}}})}_getConversationList(o){let{isUndefined:e,isArray:t,isPlainObject:s}=this._core["utils"];if(e(o))return T.getLocalConversationList();if(t(o))return 0===o.length?[]:T.getLocalConversationList().filter(e=>o.includes(e.conversationID));if(s(o)){let{type:t,markType:s,groupName:r,hasUnreadCount:i,hasGroupAtInfo:n}=o;return T.getLocalConversationList().filter(e=>this._filterType(e,t)&&this._filterMarkType(e,s)&&this._filterGroupName(e,r)&&this._filterUnreadCount(e,i)&&this._filterGroupAtInfo(e,n))}return[]}_filterType(e,t){var s=this._core["OuterConstant"];return t!==s.CONV_C2C&&t!==s.CONV_GROUP||e.type===t}_filterGroupName(e,t){var{isString:s}=this._core["utils"];return!s(t)||(""===t?0===e.conversationGroupList.length:e.conversationGroupList.includes(t))}_filterMarkType(e,t){var{isNumber:s}=this._core["utils"];return!s(t)||(0===t?0===e.markList.length:e.markList.includes(t))}_filterUnreadCount(e,t){let s=!0;return!0===t?s=1<=e.unreadCount:!1===t&&(s=0===e.unreadCount),s}_filterGroupAtInfo(e,t){let s=!0;return!0===t?s=1<=e.groupAtInfoList.length:!1===t&&(s=0===e.groupAtInfoList.length),s}},qn=new class{constructor(){this._name="GetC2CMessageRemindType"}init(e){this._core=e}get(r){return I(this,void 0,void 0,function*(){try{var e=this._core["common"],t=yield function(s,r){return I(this,void 0,void 0,function*(){var{toAccount:e,userIDList:t}=s;return r.common.buildAndSendPacket({servcmd:"openim.get_c2c_peer_mute_notifications",data:{To_Account:e,Peer_Account:t}})})}({toAccount:e.getCurrentUserID(),userIDList:r},this._core),{MuteNotificationsList:s=[]}=t||{};s.forEach(e=>{var{Peer_Account:e,MuteNotifications:t}=e,e=""+this._core.OuterConstant.CONV_C2C+e,t=wn(t);T.patchMessageRemindType([e],t)})}catch(e){console.error(this._name+".get fail:",e)}})}},xn=new class{constructor(){this._name="GetGroupMessageRemindType"}init(e){this._core=e}get(s){return I(this,void 0,void 0,function*(){if(0!==s.length)try{var e=yield function(s,r){return I(this,void 0,void 0,function*(){var{groupIDList:e,responseFilter:t}=s;return r.common.buildAndSendPacket({servcmd:"group_open_http_svc.get_group_self_member_info",data:{GroupIdList:e,ResponseFilter:t}})})}({groupIDList:s,responseFilter:{MemberInfoFilter:["MsgFlag"]}},this._core),{GroupInfo:t=[]}=e||{};t.forEach(e=>{var{GroupId:e,MemberList:t}=e,t=(null==(t=t[0])?void 0:t.MsgFlag)||"",e=""+this._core.OuterConstant.CONV_GROUP+e;T.patchMessageRemindType([e],t)})}catch(e){console.error(this._name+".get fail:",e)}})}},Vn=new class{constructor(){this._name="GetConversationProfile"}init(e){e=(this._core=e).helper;e.registerApi({apiName:"getConversationProfile",context:this})}getConversationProfile(u){return I(this,void 0,void 0,function*(){let{OuterConstant:{CONV_C2C:s,CONV_GROUP:r,GRP_AVCHATROOM:i},appStore:{groupStore:n},utils:{isEmpty:e}}=this._core,o={code:0,data:{}},a=T.getLocalConversation(u);if(Pn(u))o.data.conversation=a;else{let t=!1;var l=Nn(u)?s:r;if(e(a)&&(t=!0,a=new kn({conversationID:u,type:l})),console.log(this._name+`.getConversationProfile conversationID:${u} isNewConversation:`+t),null==(o.data.conversation=a)||!a.getProfileCompleted()){if(l===s){let e=u.replace(s,"");yield this._handleC2CConversation(a,e),t&&(yield qn.get([e]))}if(l===r){let e=u.replace(r,"");if(!n.getGroup(e))return o;yield this._handleGroupConversation(a,e),t&&a.groupProfile.type!==i&&(yield xn.get([e]))}}}return o})}_handleC2CConversation(o,a){return I(this,void 0,void 0,function*(){var{user:e,helper:t,utils:{isEmpty:s},appStore:{conversationStore:r,userStore:i}}=this._core,n=o["conversationID"],e=yield null==(e=e.userProfile)?void 0:e.getUserProfile({userIDList:[a]});if(0===(null==e?void 0:e.data.length))throw new t.ChatError({code:yn.USER_OR_GRP_NOT_FOUND});o.userProfile=null==e?void 0:e.data[0];e=null==(t=i.getFriend(a))?void 0:t.remark,s(e)||o.remark===e||(o.remark=e),o.setProfileCompleted(),i=T.hasLocalConversation(n);console.log(this._name+`._handleC2CConversation conversationID:${n} hasLocalConversation: `+i),i?r.updateConversation(n,o):T.appendToPinnedConversation(o)})}_handleGroupConversation(r,i){return I(this,void 0,void 0,function*(){var{apiMap:{getGroupProfile:e},appStore:{conversationStore:t}}=this._core,s=r["conversationID"],e=yield e({groupID:i}),e=(r.groupProfile=null==e?void 0:e.data.group,r.setProfileCompleted(),T.hasLocalConversation(s));console.log(this._name+`._handleGroupConversation conversationID:${s} hasLocalConversation: `+e),e?t.updateConversation(s,r):T.appendToPinnedConversation(r)})}},Bn=new class{init(e){e=e.helper;e.registerApi({apiName:"getTotalUnreadMessageCount",context:this})}getTotalUnreadMessageCount(){return T.getTotalUnreadMessageCount()}},jn=new class{constructor(){this._serverGroupConversationLastReadSeqMap=new Map,this._name="SetMessageRead"}init(e){let{helper:t,common:{isTopic:s},notificationCenter:r,InnerEvent:{MESSAGE_PUSH:i},InnerEventSubType:{ALL_MESSAGE_READ:n}}=this._core=e;t.registerApi({apiName:"setMessageRead",context:this,matcher:e=>!s(e[0].conversationID)}),t.registerApi({apiName:"setAllMessageRead",context:this}),r.subscribeInnerEvent(i,n,this._handleAllMessageRead,this)}handleC2CMessageReadSync(e){let{helper:{isEmpty:s},OuterConstant:r}=this._core;e.forEach(e=>{var t=e["ReadC2cMsgNotify"];if(!s(t)){let{UinPairReadArray:e=[]}=t;e.forEach(e=>{var{From_Account:e,LastReadTime:t}=e,e=""+r.CONV_C2C+e;console.log(this._name+`.handleC2CMessageReadSync conversationID:${e} lastReadTime:`+t),T.markMessageAsRead({conversationID:e,lastReadTime:t}),T.updateUnreadCount(e)})}})}handleGroupMessageReadSync(e){let{OuterConstant:s,utils:{isUndefined:t}}=this._core;e.forEach(e=>{e=e.MsgBody.GroupReadInfoArray;t(e)||e.forEach(e=>{var{GroupId:e,LastReadMsgSeq:t}=e,e=""+s.CONV_GROUP+e;console.log(this._name+`.handleGroupMessageReadSync conversationID:${e} lastReadSequence:`+t),T.markMessageAsRead({conversationID:e,lastReadSequence:t}),T.updateUnreadCount(e),this._clearGroupAtInfoList(e)})})}setMessageRead(l){return I(this,void 0,void 0,function*(){var e,t=this._core["OuterConstant"],s=l["conversationID"],r={code:0,data:{}},i=T.getLocalConversation(s);let n=this._name+`.setMessageRead conversationID:${s} unreadCount:`+((null==i?void 0:i.unreadCount)||0);if(r.successLog={message:n},!i)return r;var o=!(null!=(e=null==(o=this._core)?void 0:o.helper)&&e.isEmpty(i.groupAtInfoList));if(i.type===t.CONV_GROUP&&o&&this._deleteGroupAtTips(s),0===i.unreadCount)return r;var a=this._core["helper"]["ChatError"];try{if(i.type===t.CONV_C2C){let e=this._getLocalMessageMaxTime(i);yield this._setC2CMessageRead(s,e),n+="lastMessageTime:"+e}if(i.type===t.CONV_GROUP){let e=this._getLocalMessageMaxSequence(i);yield this._setGroupMessageRead(s,e),n+="lastMessageSequence:"+e}}catch(e){let{errorCode:t,errorInfo:s}=e;throw new a({functionName:"setMessageRead",code:t,message:s,moreMessage:n})}return i.type===t.CONV_SYSTEM&&(i.unreadCount=0),T.emitConversationListUpdate(),Object.assign(Object.assign({},r),{successLog:{message:n}})})}setAllMessageRead(){return I(this,arguments,void 0,function*(t={}){let{OuterConstant:{READ_ALL_MSG:e},utils:{safeStringify:i}}=this._core,n="scope:"+t.scope,s=(t.scope||(t.scope=e),t)["scope"],o=this._generateSetAllMessageReadRequestData(s);if(0===o.allC2CMessageReadStatus&&0===o.groupMessageReadInfoList.length)return{code:0};try{let r=yield function(s){return I(this,void 0,void 0,function*(){var{allC2CMessageReadStatus:e,groupMessageReadInfoList:t}=s,e={C2CReadAllMsg:e,GroupReadInfo:t};return A.core.common.buildAndSendPacket({servcmd:"openim.read_all_unread_msg",data:e})})}(o);if(r){let{GroupReadInfoArray:e,C2CReadAllMsg:t}=r,s=this._parseGroupReadInfo(e);0<this._updateAllConversationReadStatus({allC2CMessageReadStatus:t})&&T.emitConversationListUpdate(),n+="failureGroupInfoList:"+i(s)}return{code:0,successLog:{message:n}}}catch(t){let e=t["errorCode"];throw new this._core.helper.ChatError({functionName:"setAllMessageRead",code:e,moreMessage:n})}})}_handleAllMessageRead(e){var{GroupReadInfoArray:e,C2CReadAllMsg:t}=e;this._parseGroupReadInfo(e),0<this._updateAllConversationReadStatus({allC2CMessageReadStatus:t})&&T.emitConversationListUpdate()}_updateAllConversationReadStatus(e){let{OuterConstant:{CONV_C2C:r,CONV_GROUP:i},appStore:t}=this._core,n=t.conversationStore.getConversationMap(),o=e["allC2CMessageReadStatus"],a=0;for(let[s,t]of n)if(1<=t.unreadCount){if(1===o&&t.type===r){let e=this._getLocalMessageMaxTime(t);T.markMessageAsRead({conversationID:s,lastReadTime:e})}else if(t.type===i){let t=s.replace(i,"");if(this._serverGroupConversationLastReadSeqMap.has(t)){let e=this._serverGroupConversationLastReadSeqMap.get(t);T.markMessageAsRead({conversationID:s,lastReadSequence:e})}}T.updateUnreadCount(s,!1)&&(a+=1)}return a}_generateSetAllMessageReadRequestData(r){let{OuterConstant:{CONV_C2C:i,CONV_GROUP:n,READ_ALL_C2C_MSG:o},appStore:e}=this._core,a={allC2CMessageReadStatus:0,groupMessageReadInfoList:[]},t=e.conversationStore.getConversationMap();for(let[,s]of t){let{type:e,unreadCount:t}=s;if(this._shouldSetAllMessageRead({scope:r,type:e,unreadCount:t}))if(e===i&&0===a.allC2CMessageReadStatus){if(a.allC2CMessageReadStatus=1,r===o)break}else if(e===n){let e=this._getLocalMessageMaxSequence(s),t=s.groupProfile["groupID"];a.groupMessageReadInfoList.push({GroupId:t,MsgSeq:e})}}return a}_parseGroupReadInfo(e){let{isUndefined:i}=this._core["utils"],n=[];return null!=e&&e.forEach(e=>{var{GroupId:e,MsgSeq:t,RetCode:s,LastReadMsgSeq:r}=e;i(s)?this._serverGroupConversationLastReadSeqMap.set(e,r):(this._serverGroupConversationLastReadSeqMap.set(e,t),0!==s&&n.push(e+`-${t}-`+s))}),n}_deleteGroupAtTips(o){return I(this,void 0,void 0,function*(){console.log(this._name+"._deleteGroupAtTips conversationID:"+o);let e=T.getLocalConversation(o);if(e){var n=(null==e?void 0:e.groupAtInfoList)||[];if(0!==n.length)try{let{common:{getCurrentUserID:t,isCommunity:e},OuterConstant:{CONV_GROUP:s,CONV_AT_ALL:r}}=this._core,i=[...n];e({groupID:o.replace(s,"")})&&0===(i=n.filter(e=>!e.atTypeArray.includes(r))).length?this._clearGroupAtInfoList(o,!1):(yield function(t,s){return I(this,void 0,void 0,function*(){var e=t["messageListToDelete"];return s.common.buildAndSendPacket({servcmd:"openim.deletemsg",data:{DelMsgList:e}})})}({messageListToDelete:i.map(e=>({From_Account:e.from,To_Account:t(),MsgSeq:e.__sequence,MsgRandom:e.__random,GroupId:e.groupID}))},this._core),console.log(this._name+"._deleteGroupAtTips ok. count:"+n.length),this._clearGroupAtInfoList(o))}catch(e){console.error(this._name+"._deleteGroupAtTips fail:",e)}}})}_clearGroupAtInfoList(e,t=!0){var s=T.getLocalConversation(e);s&&(0<s.groupAtInfoList.length&&(s.clearGroupAtInfoList(),console.log(this._name+`._clearGroupAtInfoList conversationID:${e} needEmitConversationUpdate:`+t)),t)&&T.emitConversationListUpdate()}_getLocalMessageMaxTime(e){var t=e["conversationID"],t=this._core.message.messageDataHandler.getLocalMessageList(t),t=Math.max(...t.map(e=>e.time));let s=(null==(e=null==e?void 0:e.lastMessage)?void 0:e.lastTime)||0;return t>s&&(console.log(`${this._name}._getLocalMessageMaxTime update lastMessageTime from ${s} to `+t),s=t),s}_getLocalMessageMaxSequence(e){var t=e["conversationID"],t=this._core.message.messageDataHandler.getLocalMessageList(t),t=Math.max(...t.map(e=>e.sequence));let s=(null==(e=null==e?void 0:e.lastMessage)?void 0:e.lastSequence)||0;return t>s&&(console.log(`${this._name}._getLocalMessageMaxSequence update lastMessageSequence from ${s} to `+t),s=t),s}_setC2CMessageRead(e,t){return I(this,void 0,void 0,function*(){try{yield function(e,t){return I(this,void 0,void 0,function*(){return t.common.buildAndSendPacket({servcmd:"openim.msgreaded",data:e})})}({C2CMsgReaded:{Cookie:"",C2CMsgReadedItem:[{To_Account:e.replace("C2C",""),LastedMsgTime:t,Receipt:1}]}},this._core),console.log(this._name+"._setC2CMessageRead ok, lastReadTime:"+t),T.markMessageAsRead({conversationID:e,lastReadTime:t}),T.updateUnreadCount(e)}catch(e){throw console.warn(this._name+"._setC2CMessageRead fail:",e),e}})}_setGroupMessageRead(e,t){return I(this,void 0,void 0,function*(){try{yield function(s,r){return I(this,void 0,void 0,function*(){var{groupID:e,lastMessageSequence:t}=s;return r.common.buildAndSendPacket({servcmd:"group_open_http_svc.msg_read_report",data:{GroupId:e,MsgReadedSeq:t}})})}({groupID:e.replace("GROUP",""),lastMessageSequence:t},this._core),console.log(this._name+"._setGroupMessageRead ok, lastReadSequence:"+t),T.markMessageAsRead({conversationID:e,lastReadSequence:t}),T.updateUnreadCount(e)}catch(e){throw console.warn(this._name+"._setGroupMessageRead fail:",e),e}})}_shouldSetAllMessageRead(e){var{CONV_C2C:t,CONV_GROUP:s,READ_ALL_MSG:r,READ_ALL_C2C_MSG:i,READ_ALL_GROUP_MSG:n}=this._core["OuterConstant"],{type:e,scope:o,unreadCount:a}=e;return!(a<=0||(e!==t||![r,i].includes(o))&&(e!==s||![r,n].includes(o)))}},Kn=new class{constructor(){this._name="PinConversation"}init(e){e=(this._core=e).helper;e.registerApi({apiName:"pinConversation",context:this})}handleConversationPinned(e,o){var{isArray:t}=this._core["utils"];if(t(e)){let i=this._core["OuterConstant"],n=!1;e.forEach(e=>{var{Type:e,To_Account:t,GroupId:s}=e;let r;1===e?r=T.getLocalConversation(""+i.CONV_C2C+t):2===e&&(r=T.getLocalConversation(""+i.CONV_GROUP+s)),r&&(console.log(`${this._name}.handleConversationPinned conversationID:${r.conversationID} localPinned:${r.isPinned} remotePinned:`+o),o&&!r.isPinned&&(r.isPinned=!0,n=!0),!o)&&r.isPinned&&(r.isPinned=!1,n=!0)}),n&&T.emitConversationListUpdate(!0)}}pinConversation(e){return I(this,void 0,void 0,function*(){let{OuterConstant:s,common:r,helper:{ChatError:i}}=this._core,{conversationID:n,isPinned:o}=e,a={code:0,data:{conversationID:n}},l=T.getLocalConversation(n);if(l&&l.isPinned===o)return a;if(Pn(n))return l&&(l.isPinned=o),T.emitConversationListUpdate(!0),a;var u=`conversationID:${n} isPinned:`+o;try{let e=null,t=(Nn(n)?e={Type:1,To_Account:n.replace(s.CONV_C2C,"")}:Ln(n)&&(e={Type:2,GroupId:n.replace(s.CONV_GROUP,"")}),yield function(r,i){return I(this,void 0,void 0,function*(){var{fromAccount:e,operationType:t,itemList:s}=r;return i.common.buildAndSendPacket({servcmd:"recentcontact.top",data:{From_Account:e,OperationType:t,RecentContactItem:s}})})}({fromAccount:r.getCurrentUserID(),operationType:!0===o?1:2,itemList:[e]},this._core));if(t){if(l)l.isPinned!==o&&(l.isPinned=o);else{let e=new kn({conversationID:n,type:Nn(n)?s.CONV_C2C:s.CONV_GROUP,isPinned:o});T.setLocalConversation(n,e)}T.emitConversationListUpdate(!0)}return Object.assign(Object.assign({},a),{successLog:{message:u}})}catch(e){let{errorCode:t,errorInfo:s}=e;throw new i({functionName:"pinConversation",code:t,message:s,moreMessage:u})}})}},Hn=new class{constructor(){this._name="DeleteConversation"}init(e){e=(this._core=e).helper;e.registerApi({apiName:"deleteConversation",context:this})}handleConversationDeleted(e){var{isArray:t}=this._core["utils"];if(t(e)){let r=this._core["OuterConstant"],i=[];e.forEach(e=>{var{Type:e,Peer_Account:t,GroupId:s}=e;1===e&&i.push(""+r.CONV_C2C+t),2===e&&i.push(""+r.CONV_GROUP+s)}),console.log(this._name+".handleConversationDeleted conversationIDList:"+i),this._deleteLocalConversationList(i)}}deleteConversation(t){return I(this,void 0,void 0,function*(){var e=this._core["utils"]["isString"];e(t)?yield this._deleteConversation({conversationIDList:[t],flag:Mn.ONLY_CONVERSATIONID}):(100<(e=Object.assign({},t)).conversationIDList.length&&(e.conversationIDList=e.conversationIDList.slice(0,100)),yield this._deleteConversation(e))})}_deleteConversation(e){return I(this,void 0,void 0,function*(){let{conversationIDList:s,clearHistoryMessage:r=!0,flag:i=0}=e,{ChatError:n}=this._core["helper"],o=`conversationIDList:${s} clearHistoryMessage:`+r;try{let e=yield Promise.all([this._deleteConversationFromLocal(s),this._deleteConversationFromServer(s,r)]),t=[...e[0],...e[1]];if(0===t.length)throw new this._core.helper.ChatError({code:yn.CONV_NOT_FOUND});return{code:0,data:i===Mn.ONLY_CONVERSATIONID?{conversationID:t[0]}:{conversationIDList:t},successLog:{message:o}}}catch(e){let{errorCode:t,errorInfo:s}=e;throw new n({code:t,message:s,moreMessage:o})}})}_deleteConversationFromLocal(e){let s=this._core["OuterConstant"];return e.filter(e=>{var t;return!!T.hasLocalConversation(e)&&((t=null==(t=T.getLocalConversation(e))?void 0:t.type)===s.CONV_GROUP&&!this._hasLocalGroup(e)||t===s.CONV_SYSTEM)&&(this._deleteLocalConversation(e),!0)})}_deleteConversationFromServer(t,n){return I(this,void 0,void 0,function*(){let{OuterConstant:r,common:e}=this._core,i={fromAccount:e.getCurrentUserID(),conversationList:[],clearHistoryMessage:n?1:0};if(t.forEach(e=>{var t,s;T.hasLocalConversation(e)&&(t=(null==(t=T.getLocalConversation(e))?void 0:t.type)||"",s=e.replace(t,""),t===r.CONV_C2C?i.conversationList.push({To_Account:s,Type:1}):t===r.CONV_GROUP&&this._hasLocalGroup(e)&&i.conversationList.push({ToGroupid:s,Type:2}))}),0!==i.conversationList.length){var s=yield function(r,i){return I(this,void 0,void 0,function*(){var{fromAccount:e,conversationList:t,clearHistoryMessage:s}=r;return i.common.buildAndSendPacket({servcmd:"recentcontact.batch_delete",data:{From_Account:e,ContactItem:t,ClearRamble:s}})})}(i,this._core);if(s){let{ResultItem:e=[]}=s,t=[];return 0<e.length&&e.forEach(e=>{0===e.ResultCode&&(e=1===e.Type?""+r.CONV_C2C+e.To_Account:""+r.CONV_GROUP+e.ToGroupid,t.push(e))}),this._deleteLocalConversationList(t),t}}return[]})}_deleteLocalConversationList(e){let t=!1;e.forEach(e=>{T.hasLocalConversation(e)&&(this._deleteLocalConversation(e,!1),t=!0)}),console.log(this._name+"._deleteLocalConversationList isUpdate:"+t),t&&T.emitConversationListUpdate()}_deleteLocalConversation(e,t=!0){var s=T.hasLocalConversation(e);console.log(this._name+`._deleteLocalConversation conversationID:${e} has:`+s),s&&(T.deleteLocalConversation(e),this._deleteConversationLocalMessage(e),t)&&T.emitConversationListUpdate()}_hasLocalGroup(e){var{OuterConstant:{CONV_GROUP:t},appStore:{groupStore:s}}=this._core,e=e.replace(t,"");return!!s.getGroup(e)}_deleteConversationLocalMessage(e){console.log(this._name+"._deleteConversationLocalMessage conversationID:"+e),this._core.message.messageDataHandler.deleteConversationMessageList(e)}},Wn=new class{constructor(){this._name="SetConversationDraft"}init(e){e=(this._core=e).helper;e.registerApi({apiName:"setConversationDraft",context:this})}setConversationDraft(s){return I(this,void 0,void 0,function*(){var{conversationID:e,draftText:t}=s;if(console.log(this._name+` conversationID:${e} draftText:`+t),T.hasLocalConversation(e))return null!=(e=T.getLocalConversation(e))&&e.setDraftText(t),T.emitConversationListUpdate(),{code:0,data:{conversation:e}};throw new this._core.helper.ChatError({code:yn.CONV_NOT_FOUND})})}},Yn=new class{constructor(){this._name="SetC2CMessageRemindType"}init(e){this._core=e}set(a,l){return I(this,void 0,void 0,function*(){30<a.length&&(console.warn(`${this._name}.set userIDList length:${a.length} exceeds limit 30`),a.splice(30));let e=function(){var{MSG_REMIND_ACPT_AND_NOTE:e,MSG_REMIND_DISCARD:t,MSG_REMIND_ACPT_NOT_NOTE:s}=A.core.OuterConstant;return{[e]:0,[t]:1,[s]:2}}()[l],t=yield function(s,r){return I(this,void 0,void 0,function*(){var{userIDList:e,receiveMessageOption:t}=s;return r.common.buildAndSendPacket({servcmd:"openim.set_c2c_peer_mute_notifications",data:{Peer_Account:e,Mute_Notifications:t}})})}({userIDList:a,receiveMessageOption:e},this._core),{ErrorList:s=[]}=t||{},r=[],i=(s.forEach(e=>{var{Peer_Account:e,ErrorCode:t}=e,t=(r.push({userID:e,code:t}),a.indexOf(e));-1<t&&a.splice(t,1)}),[]),n=[],o=this._core["OuterConstant"];return a.forEach(e=>{n.push(""+o.CONV_C2C+e),i.push({userID:e})}),T.patchMessageRemindType(n,l),{code:0,data:{successUserIDList:i,failureUserIDList:r}}})}},$n=new class{constructor(){this._name="SetGroupMessageRemindType"}init(e){this._core=e}set(r,i){return I(this,void 0,void 0,function*(){let{common:{getCurrentUserID:e,isTopic:t},OuterConstant:s}=this._core;if(yield function(r,i){return I(this,void 0,void 0,function*(){var{groupID:e,userID:t,receiveMessageOption:s}=r;return i.common.buildAndSendPacket({servcmd:"group_open_http_svc.modify_group_member_info",data:{GroupId:e,Member_Account:t,MsgFlag:s}})})}({groupID:r,userID:e(),receiveMessageOption:i},this._core),!t(r)){let e=""+s.CONV_GROUP+r;T.patchMessageRemindType([e],i)}return{code:0,data:{groupID:r,messageRemindType:i}}})}},zn=new class{constructor(){this._name="SetMessageRemindType"}init(e){e=(this._core=e).helper;e.registerApi({apiName:"setMessageRemindType",context:this})}handleC2CMessageRemindTypeSync(e){let{helper:{isEmpty:t},OuterConstant:n,ssoLog:o}=this._core;e.forEach(e=>{var i=e["MuteNotificationsSync"];if(!t(i)){let{To_Account:e,MuteNotifications:t}=i,s=e.map(e=>""+n.CONV_C2C+e),r=wn(t);o.debug(this._name+`.handleC2CMessageRemindTypeSync conversationIDList:${s} messageRemindType:`+r),T.patchMessageRemindType(s,r)}})}setMessageRemindType(a){return I(this,void 0,void 0,function*(){let s="setMessageRemindType",{groupID:e,userIDList:t,messageRemindType:r}=a,{helper:i,utils:{isUndefined:n},ssoLog:o}=this._core;try{if(!n(e))return o.debug(`${this._name}.${s} groupID:${e} messageRemindType:`+r),yield $n.set(e,r);if(n(t))throw new i.ChatError({functionName:s,message:"userIDList or groupID is required"});return o.debug(this._name+`.${s} userIDList:${t} messageRemindType:`+r),yield Yn.set(t,r)}catch(e){let t=new i.ChatError({functionName:s,code:null==e?void 0:e.errorCode,message:null==e?void 0:e.errorInfo});throw console.error(this._name+`.${s} fail:`,t),t}})}},Jn=new class{init(e){e.ssoLog.debug("ConversationAction.init"),this._core=e,Fn.init(e),Vn.init(e),Bn.init(e),jn.init(e),Kn.init(e),Hn.init(e),Wn.init(e),zn.init(e);var{notificationCenter:e,InnerEvent:{MESSAGE_PUSH:t,DESTROY:s}}=this._core,{CONV_MODIFIED:r,C2C_MESSAGE_READ_SYNC:i,GROUP_MESSAGE_READ_SYNC:n,C2C_REMIND_TYPE_SYNC:o}=e["InnerEventSubType"];e.subscribeInnerEvent(t,r,this._onConversationModified,this),e.subscribeInnerEvent(t,i,this._onC2CMessageReadSync,this),e.subscribeInnerEvent(t,o,this._onC2CMessageRemindTypeSync,this),e.subscribeInnerEvent(t,n,this._onGroupMessageReadSync,this),e.subscribeInnerEvent(s,this._dispose,this)}_onConversationModified(e){let{ConvModifyPushType:s}=this._core["constants"],{RecentContactMod:t=[]}=e;t.forEach(t=>{var e=t["PushType"];if(e===s.CONV_DELETED){let e=t.RecentContactDeleteItem["RecentContactList"];Hn.handleConversationDeleted(e)}if(e===s.CONV_PINED){let e=t.RecentContactTopItem["RecentContactList"];Kn.handleConversationPinned(e,!0)}if(e===s.CONV_UNPINED){let e=t.RecentContactTopItem["RecentContactList"];Kn.handleConversationPinned(e,!1)}})}_onC2CMessageReadSync(e){var{C2cNotifyMsgArray:e=[]}=e;jn.handleC2CMessageReadSync(e)}_onC2CMessageRemindTypeSync(e){var{C2cNotifyMsgArray:e=[]}=e;zn.handleC2CMessageRemindTypeSync(e)}_onGroupMessageReadSync(e){var{GroupTips:e=[]}=e;jn.handleGroupMessageReadSync(e)}_dispose(){var{notificationCenter:e,InnerEvent:{MESSAGE_PUSH:t,DESTROY:s}}=this._core,{CONV_MODIFIED:r,C2C_MESSAGE_READ_SYNC:i,GROUP_MESSAGE_READ_SYNC:n,C2C_REMIND_TYPE_SYNC:o}=e["InnerEventSubType"];e.unSubscribeInnerEvent(t,r,this._onConversationModified,this),e.unSubscribeInnerEvent(t,i,this._onC2CMessageReadSync,this),e.unSubscribeInnerEvent(t,o,this._onC2CMessageRemindTypeSync,this),e.unSubscribeInnerEvent(t,n,this._onGroupMessageReadSync,this),e.unSubscribeInnerEvent(s,this._dispose,this)}},Qn=new class{init(e){e=(this._core=e).helper;e.registerApi({apiName:"setAllReceiveMessageOpt",context:this})}setAllReceiveMessageOpt(o){return I(this,void 0,void 0,function*(){try{var{MSG_REMIND_ACPT_NOT_NOTE:e}=this._core["OuterConstant"],{messageRemindType:t=e,isRepeated:s=!0}=o,{startTime:r=0,endTime:i=0}=this._calcStartAndEndTime(o),n=yield function(n){return I(this,void 0,void 0,function*(){var e=A.core["common"],{startTime:t,endTime:s,isRepeated:r,messageRemindType:i}=n;return e.buildAndSendPacket({servcmd:"im_msg_db_logic.ws_set_do_not_disturb",data:{StartTime:t,EndTime:s,IsRepeated:r,Level:i}})})}({messageRemindType:this._getType(t),startTime:r,endTime:i,isRepeated:s?Cn.ON:Cn.OFF});return{code:0,data:{errorCode:n.ErrorCode,errorInfo:n.ErrorInfo}}}catch(e){Un("setAllReceiveMessageOpt",e)}})}_calcStartAndEndTime(e){var{startHour:e=0,startMinute:t=0,startSecond:s=0,duration:r=0,isRepeated:i=!0}=e,n=new Date,n=new Date(n.getFullYear(),n.getMonth(),n.getDate(),e,t,s),e=Math.round(n.getTime()/1e3);let o=i&&86400<=r?e+86400:e+r;return{startTime:e,endTime:o}}_getType(e){var t=this._core["OuterConstant"];return{[t.MSG_REMIND_ACPT_AND_NOTE]:0,[t.MSG_REMIND_DISCARD]:1,[t.MSG_REMIND_ACPT_NOT_NOTE]:2}[e]}},Xn=new class{init(e){var{helper:e,notificationCenter:t,InnerEvent:s}=this._core=e;e.registerApi({apiName:"getAllReceiveMessageOpt",context:this}),t.subscribeInnerEvent(s.MESSAGE_PUSH,t.InnerEventSubType.ALL_RECEIVE_MESSAGE_OPTION,this.onAllReceiveMsgOptionNotify,this)}onAllReceiveMsgOptionNotify(e){var e=this._handleResult(e),{notificationCenter:t,OuterEvent:{ALL_RECEIVE_MESSAGE_OPT_UPDATED:s}}=this._core;t.emitOuterEvent(s,{name:s,data:e})}getAllReceiveMessageOpt(){return I(this,void 0,void 0,function*(){try{var e=yield function(){return I(this,void 0,void 0,function*(){var e=A.core["common"],t={To_Account:e.getCurrentUserID()};return e.buildAndSendPacket({servcmd:"im_msg_db_logic.ws_get_do_not_disturb",data:t})})}();return{code:0,data:this._handleResult(e)}}catch(e){Un("getAllReceiveMessageOpt",e)}})}_handleResult(e){var t=this._core["OuterConstant"],{MSG_REMIND_ACPT_AND_NOTE:t,MSG_REMIND_DISCARD:s,MSG_REMIND_ACPT_NOT_NOTE:r}=t,{Level:e,StartTime:i,EndTime:n,IsRepeated:o}=e;return{messageRemindType:{0:t,1:s,2:r}[e]||t,startTime:i,endTime:n,isRepeated:o===Cn.ON}}},Zn=new class{init(e){e.ssoLog.debug("ReceiveMessageOptions.init"),this._core=e,Yn.init(e),$n.init(e),qn.init(e),xn.init(e),Qn.init(e),Xn.init(e)}};let eo=e=>!Nn(e)&&!Ln(e)&&!Pn(e),to={getConversationProfile:[{key:"conversationID",required:!0,rules:["string"],allowEmpty:!1,customValidator:e=>!eo(e)||"conversationID is invalid."}],setMessageRead:{conversationID:{required:!0,rules:["string"],allowEmpty:!1,customValidator:e=>!eo(e)||"conversationID is invalid."}},pinConversation:{conversationID:{required:!0,rules:["string"],allowEmpty:!1,customValidator:e=>!eo(e)||"conversationID is invalid."},isPinned:{required:!0,rules:["boolean"],allowEmpty:!1}},deleteConversation:[{key:"options",required:!0,rules:["string","object"],allowEmpty:!1,customValidator:e=>{var{utils:{isArray:t,isObject:s,isString:r}}=A["core"];if(!r(e)&&!s(e))return"options is String or Object.";if(r(e)&&eo(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(eo(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=>!(!Nn(e)&&!Ln(e))||"conversationID is invalid."},draftText:{required:!0,rules:["string"],allowEmpty:!0}},setAllReceiveMessageOpt:{messageRemindType:{required:!1,rules:["string"],allowEmpty:!0},startHour:{required:!1,rules:["number"],allowEmpty:!0},startMinute:{required:!1,rules:["number"],allowEmpty:!0},startSecond:{required:!1,rules:["number"],allowEmpty:!0},duration:{required:!1,rules:["number"],allowEmpty:!0},isRepeated:{required:!1,rules:["boolean"],allowEmpty:!0}}},so={getConversationList:!0,getConversationProfile:!0,getTotalUnreadCount:!0,setMessageRead:!0,pinConversation:!0,deleteConversation:!0,setConversationDraft:!0,setMessageRemindType:!0,getAllReceiveMessageOpt:!0,setAllReceiveMessageOpt:!0},ro=new class{constructor(){this.name="Conversation"}install(e){A.init(e),Jn.init(e),Zn.init(e),T.init(e),e.helper.registerValidateConfig({auth:so,params:to})}},io=new class{init(e){this.core=e}},no="AVChatRoom",oo="GRP_COUNTER",ao=["Type","Name","Introduction","Notification","FaceUrl","Owner_Account","CreateTime","InfoSeq","LastInfoTime","LastMsgTime","MemberNum","MaxMemberNum","ApplyJoinOption","NextMsgSeq","ShutUpAllMember","InviteJoinOption","LastRecallTime"],lo=["Type","Name","Introduction","Notification","FaceUrl","CreateTime","Owner_Account","LastInfoTime","LastMsgTime","NextMsgSeq","MemberNum","MaxMemberNum","ApplyJoinOption","InviteJoinOption"],uo=["Role","JoinTime","MsgFlag","MsgSeq"],co=["Role","JoinTime","MsgSeq","MsgFlag","NameCard"],ho="notStart",go="resolved",po="rejected",_o=["Owner","Admin","Member"],mo=["Role","JoinTime","NameCard","ShutUpUntil","OnlineStatus"],vo={from:!0,groupID:!0,groupName:!0,to:!0},fo={from:!0,groupID:!0,groupName:!0,to:!0,type:!0},Io=e=>e===io.core.OuterConstant.GRP_PUBLIC,Eo=e=>e===io.core.OuterConstant.GRP_AVCHATROOM,So=(r,e)=>{var t=io.core.utils["isArray"];if(!t(r)||!t(e))return!1;let i=!1;return e.forEach(({key:t,value:e})=>{var s=r.find(e=>e.key===t);s?s.value!==e&&(s.value=e,i=!0):(r.push({key:t,value:e}),i=!0)}),i},Co=s=>{var r=[];if(s)for(let e=0,t=s.length;e<t;e++){var{Key:i,Value:n}=s[e];r.push({key:i,value:n})}return r},Mo=s=>{var r=[];for(let e=0,t=s.length;e<t;e++){var{key:i,value:n}=s[e];r.push({Key:i,Value:n})}return r};function yo(e,t){var s=io.core["helper"];if(!s.checkBusinessCapabilityBits(t))throw new s.ChatError({functionName:e,code:3122,replacement1:e})}function Oo(e,t){var s=io.core["helper"],s=new s.ChatError({functionName:e,code:(null==t?void 0:t.errorCode)||(null==t?void 0:t.code),message:(null==t?void 0:t.errorInfo)||(null==t?void 0:t.message)});throw console.error(e+" fail:",s),s}let Ao=["groupID","name","avatar","type","introduction","notification","ownerID","selfInfo","createTime","infoSequence","lastInfoTime","lastMessage","nextMessageSeq","memberCount","maxMemberCount","memberList","joinOption","groupCustomField","muteAllMembers","isSupportTopic","inviteOption","_lastRevokedTime","_groupAtInfoList"];class To{constructor(e){this.groupID="",this.name="",this.avatar="",this.type="",this.introduction="",this.notification="",this.ownerID="",this.createTime=0,this.selfInfo={messageRemindType:"",joinTime:"",nameCard:"",role:"",userID:"",memberCustomField:void 0,readedSequence:0,excludedUnreadSequenceList:void 0},this.lastMessage={lastTime:0,lastSequence:0,fromAccount:"",messageForShow:""},this.nextMessageSeq=0,this.memberCount=0,this.maxMemberCount=0,this.joinOption="",this.inviteOption="",this.groupCustomField=[],this.muteAllMembers=!1,this.isSupportTopic=!1,this._lastRevokedTime=0,this._groupAtInfoList=[],this._initGroup(e)}_initGroup(e){var t,{isString:s}=io.core["utils"];for(t in e)Ao.indexOf(t)<0||("selfInfo"!==t?"isSupportTopic"!==t?"muteAllMembers"===t&&s(e[t])?this.muteAllMembers="On"===e[t]:this[t]=e[t]:this.isSupportTopic=1===e[t]:this.updateSelfInfo(e[t]))}updateGroup(e){let{utils:{isArray:t,isUndefined:s,isNumber:r,isString:i},common:{deepMerge:n}}=io.core;e.appid=void 0,e.grossTopicNextMsgSeq=void 0,e.selfInfo&&(e.selfInfo.grossTopicReadSeq=void 0);e=JSON.parse(JSON.stringify(e));e.lastMsgTime&&(this.lastMessage.lastTime=e.lastMsgTime),i(e.muteAllMembers)&&(e.muteAllMembers="On"===e.muteAllMembers),e.groupCustomField&&So(this.groupCustomField,e.groupCustomField),s(e.isSupportTopic)||(this.isSupportTopic=r(e.isSupportTopic)?1===e.isSupportTopic:e.isSupportTopic),n(this,e,["members","errorCode","lastMsgTime","groupCustomField","isSupportTopic"]),t(e.members)&&0<e.members.length&&e.members.forEach(e=>{e.userID===this.selfInfo.userID&&n(this.selfInfo,e,["sequence"])})}updateSelfInfo(e){var{nameCard:e,joinTime:t,role:s,messageRemindType:r,readedSequence:i,excludedUnreadSequenceList:n}=e,o=io.core["common"]["deepMerge"];o(this.selfInfo,{nameCard:e,joinTime:t,role:s,messageRemindType:r,readedSequence:i,excludedUnreadSequenceList:n},[],["",null,void 0,0,NaN])}setSelfNameCard(e){this.selfInfo.nameCard=e}}var R=new class{constructor(){this._name="GroupDataHandler"}init(e){var e=(this._core=e)["appStore"]["groupStore"];this._groupMap=e.getGroupMap()}hasLocalGroup(e){return this._groupMap.has(e)}getLocalGroup(e){return this._groupMap.get(e)}updateLocalGroup(e){var{getCurrentUserID:t}=this._core["common"];let s;e.forEach(e=>{var t;s=e.groupID,this.hasLocalGroup(s)?null!=(t=this.getLocalGroup(s))&&t.updateGroup(e):this._groupMap.set(s,new To(e))});var r=t();for(let[,e]of this._groupMap)e.selfInfo.userID=r,"Owner"===e.selfInfo.role&&(e.ownerID=r)}deleteLocalGroup(e){this._groupMap.delete(e)}getLocalGroupList(){let{GRP_ROOM:t,GRP_LIVE:s}=this._core["OuterConstant"];return[...this._groupMap.values()].filter(e=>{e=e.type;return e!==t&&e!==s})}clearLocalGroup(){this._groupMap.clear()}emitGroupListUpdate(){var e=this.getLocalGroupList(),{OuterEvent:{GROUP_LIST_UPDATED:t},notificationCenter:s}=this._core;s.emitOuterEvent(t,{name:t,data:e})}updateConversationGroupProfile(t){let{appStore:{conversationStore:s},OuterConstant:{CONV_GROUP:e}}=this._core,r=""+e+t;if(s.getConversation(r)){let e=this.getLocalGroup(t);s.updateConversation(r,{groupProfile:e})}}reset(){this.clearLocalGroup()}};function Ro(o,a){return I(this,void 0,void 0,function*(){var{type:e,limit:t,offset:s,supportTopic:r=0,memberAccount:i,responseFilter:n}=o;return a.common.buildAndSendPacket({servcmd:"group_open_http_svc.get_joined_group_list",data:{Type:e,Limit:t,Offset:s,Member_Account:i,ResponseFilter:n,SupportTopic:r,NeedAppDefineData:1}})})}function D(e,t){return{code:0,data:e||{},successLog:t}}var Do=new class{constructor(){this._name="GetGroupList",this._pagingStatus=ho,this.PAGING_GRP_COUNT_LIMIT=200}init(e){var{helper:e,constants:{WORKFLOW_NAME:t,WORKFLOW_STEP:s}}=this._core=e;e.registerApi({apiName:"getGroupList",context:this}),e.registerWorkflowStep(t.SYNC_SERVER_INFO_AFTER_LOGIN,s.GROUP_LIST_SYNC,this._syncGroupList,this)}getGroupList(){return I(this,arguments,void 0,function*(e=!1){if(e){let e=[];return yield this._pagingGetJoinedCommunityList({limit:this.PAGING_GRP_COUNT_LIMIT,offset:0,groupList:e}),R.updateLocalGroup(e),R.getLocalGroupList()}return this._core.ssoLog.debug("getGroupList",this._name+".getGroupList pagingStatus:"+this._pagingStatus),this._pagingStatus===po||this._pagingStatus===ho?this._syncGroupList().then(()=>{var e=R.getLocalGroupList();return D({groupList:e,isSyncCompleted:this._isSyncCompleted()})}).catch(e=>{throw e}):(e=R.getLocalGroupList(),D({groupList:e,isSyncCompleted:this._isSyncCompleted()},{message:"return group count:"+e.length}))})}_syncGroupList(){return I(this,void 0,void 0,function*(){this._pagingStatus===ho&&R.clearLocalGroup();var e=this.PAGING_GRP_COUNT_LIMIT,t=[];try{yield this._pagingGetGroupList({limit:e,offset:0,groupList:t}),this._pagingStatus=go,this._groupListTreeShaking(t),R.updateLocalGroup(t);var s=R.getLocalGroupList();return this._core.ssoLog.debug("_syncGroupList",this._name+"._syncGroupList ok, count:"+s.length),R.emitGroupListUpdate(),s}catch(e){throw this._pagingStatus=po,e}})}_pagingGetGroupList(e){return I(this,void 0,void 0,function*(){var i=this._core["ssoLog"],{isCommunityRelay:n=!1,groupList:o}=e;let a,{limit:l,offset:u}=e;var c=[...ao];n&&(a=this._core.OuterConstant.GRP_COMMUNITY,c.push("AtInfoList"));try{let e=yield Ro({type:a,limit:l,offset:u,memberAccount:this._core.store.get("login").userId,responseFilter:{GroupBaseInfoFilter:c,SelfInfoFilter:[...uo]}},this._core),{GroupIdList:t=[],TotalCount:s=0}=e||{},r=this._convertGroupKey(t);o.push(...r);var d=u+l,h=!(d<s),g=`offset:${u} limit:${l} total:${s} isCompleted:${h} current:${o.length} isCommunityRelay:`+n;return i.debug("_pagingGetGroupList",this._name+"._pagingGetGroupList ok. "+g),n?h?o:(u=d,this._pagingGetGroupList({isCommunityRelay:!0,limit:l,offset:u,groupList:o})):h?(i.debug("_pagingGetGroupList",this._name+"._pagingGetGroupList start to get community list"),u=0,this._pagingGetGroupList({isCommunityRelay:!0,limit:l,offset:u,groupList:o})):(u=d,this._pagingGetGroupList({limit:l,offset:u,groupList:o}))}catch(e){if(10018===e.ErrorCode)return i.warn("_pagingGetGroupList",this._name+"._pagingGetGroupList response size exceeds the limit, request count:"+l),this._pagingGetGroupList({isCommunityRelay:n,limit:50,offset:u,groupList:o});if(n)return 11e3===e.code&&i.debug("_pagingGetGroupList",this._name+"._pagingGetGroupList ok. community unavailable"),o;throw e}})}_pagingGetJoinedCommunityList(e){return I(this,void 0,void 0,function*(){var{common:{getCurrentUserID:i},OuterConstant:n,ssoLog:o}=this._core,a=e["groupList"];let{limit:l,offset:u}=e;try{let e=yield Ro({limit:l,offset:u,type:n.GRP_COMMUNITY,memberAccount:i(),supportTopic:1,responseFilter:{GroupBaseInfoFilter:[...ao],SelfInfoFilter:[...uo]}},this._core),{GroupIdList:t=[],TotalCount:s=0}=e||{},r=this._convertGroupKey(t);a.push(...r);var c=u+l,d=!(c<s),h=`offset:${u} limit:${l} total:${s} isCompleted:${d} current:`+a.length;return o.debug("_pagingGetJoinedCommunityList",this._name+"._pagingGetJoinedCommunityList ok. "+h),d?a:(u=c,this._pagingGetJoinedCommunityList({limit:l,offset:u,groupList:a}))}catch(e){if(10018===e.code)return o.warn("_pagingGetJoinedCommunityList",this._name+"._pagingGetJoinedCommunityList response size exceeds the limit, request count:"+l),this._pagingGetJoinedCommunityList({limit:50,offset:u,groupList:a});throw e}})}_groupListTreeShaking(s){var r=new Map([...R.getLocalGroupList()]);for(let e=0,t=s.length;e<t;e++)r.delete(s[e].groupID);var i=[...r.keys()];for(let e=0,t=i.length;e<t;e++)R.deleteLocalGroup(i[e])}_isSyncCompleted(){return this._pagingStatus===go}_convertGroupKey(s){var r=[];for(let e=0,t=s.length;e<t;e++){var{AppDefinedData:i,ApplyJoinOption:n,CreateTime:o,FaceUrl:a,GroupId:l,Introduction:u,InviteJoinOption:c,LastInfoTime:d,LastMsgTime:h,MemberNum:g,MaxMemberNum:p,MuteAllMember:_,Name:m,NextMsgSeq:v,Notification:f,Owner_Account:I,Type:E,LastRecallTime:S,SelfInfo:C,AtInfoList:M=[],SupportTopic:y}=s[e],i=Co(i),C=this._convertSelfInfo(C),M=this._convertAtInfoList(l,M);r.push({groupCustomField:i,joinOption:n,createTime:o,avatar:a,groupID:l,introduction:u,inviteOption:c,lastInfoTime:d,lastMsgTime:h,memberCount:g,maxMemberCount:p,muteAllMembers:_,name:m,nextMessageSeq:v,notification:f,ownerID:I,type:E,selfInfo:C,_lastRevokedTime:S,_groupAtInfoList:M,isSupportTopic:y})}return r}_convertSelfInfo(e){var{JoinTime:e,MsgFlag:t,MsgSeq:s,NoUnreadSeqList:r,Role:i}=e;return{joinTime:e,messageRemindType:t,readedSequence:s,excludedUnreadSequenceList:r,role:i}}_convertAtInfoList(r,e){if(0===e.length)return[];let i=[];return e.forEach(e=>{var{AtFlagList:e,AtMsgSeq:t,From_Account:s}=e;i.push({groupID:r,groupAtType:e,sequence:t,from:s})}),i}},bo=new class{constructor(){this._name="CreateGroup"}init(e){e=(this._core=e).helper;e.registerApi({apiName:"createGroup",context:this})}createGroup(l){return I(this,void 0,void 0,function*(){var o;this._preCheckParams(l);let e=this._core["helper"]["ChatError"];try{let{utils:{isEmpty:e},common:{getCurrentUserID:t}}=this._core,s=yield function(g,p){return I(this,void 0,void 0,function*(){var{name:e,type:t,groupID:s,introduction:r,notification:i,avatar:n,maxMemberNum:o,joinOption:a,inviteOption:l,memberList:u,groupCustomField:c,isSupportTopic:d}=g;let h;e={Name:e,Type:t,GroupId:s,Introduction:r,Notification:i,FaceUrl:n,MaxMemberCount:o,ApplyJoinOption:a,InviteJoinOption:l,MemberList:h=u?u.map(e=>{var{userID:e,memberCustomField:t}=e;return{Member_Account:e,AppMemberDefinedData:t?Mo(t):void 0}}):h,AppDefinedData:c,SupportTopic:d,webPushFlag:1};return p.common.buildAndSendPacket({servcmd:"group_open_http_svc.create_group",data:e})})}(Object.assign(Object.assign({},l),{ownerID:t()}),this._core),{GroupId:r,OverJoinedGroupLimit_Account:i=[]}=s||{},n=`${this._name}.createGroup ok, type:${l.type} groupID:${r} overLimitUserIDList:`+i;e(l.memberList)||e(i)||(l.memberList=null==(o=l.memberList)?void 0:o.filter(e=>i.includes(e.userID))),R.updateLocalGroup([Object.assign(Object.assign({},l),{groupID:r})]);var a=R.getLocalGroup(r);return this._notNeedSendCustomMessage(l)||(this._sendCustomMessage(r,l.type),R.emitGroupListUpdate()),D({group:a},{message:n})}catch(o){var{errorCode:a,errorInfo:t}=o;throw new e({functionName:"createGroup",code:a,message:t,moreMessage:" groupID:"+l.groupID})}})}_preCheckParams(e){var{type:t,groupID:s}=e,{utils:{isEmpty:r,isUndefined:i},common:{isCommunity:n}}=this._core,r=!r(s);if(!(()=>{var{GRP_PUBLIC:e,GRP_WORK:t,GRP_MEETING:s,GRP_AVCHATROOM:r,GRP_COMMUNITY:i}=io.core.OuterConstant;return[e,t,s,r,i]})().includes(t))throw new this._core.helper.ChatError({code:2600});if(!n({type:t})){if(r&&n({groupID:s}))throw new this._core.helper.ChatError({code:2602});i(e.isSupportTopic)||(e.isSupportTopic=void 0)}if(this._canIUseMemberList(t)||i(e.memberList)||(e.memberList=void 0),this._canIUseJoinOption(t)||i(e.joinOption)||(e.joinOption=void 0),n({type:t})){if(r&&!n({groupID:s}))throw new this._core.helper.ChatError({code:2602});e.isSupportTopic=this._canIUseTopic(e)?1:0}}_canIUseMemberList(e){return!Eo(e)}_canIUseJoinOption(e){return Io(e)||this._core.common.isCommunity({type:e})}_canIUseTopic(e){e=e.isSupportTopic;return!0===e}_notNeedSendCustomMessage(e){var{type:e,isSupportTopic:t}=e,{GRP_AVCHATROOM:s,GRP_COMMUNITY:r}=this._core["OuterConstant"];return e===s||e===r&&1===t}_sendCustomMessage(e,t){var s=this._core["OuterConstant"];let r="Create Group",i=0;t===s.GRP_COMMUNITY&&(r="Create Community",i=1);var t={to:e,conversationType:"GROUP",payload:{data:JSON.stringify({businessID:"group_create",content:r,cmd:i,opUser:this._core.store.get("login").userId,version:4})}},e=null==(s=null==(e=null==(s=this._core)?void 0:s.message)?void 0:e.messageFactory)?void 0:s.createCustomMessage(t);null!=(s=null==(t=null==(s=this._core)?void 0:s.message)?void 0:t.messageSender)&&s.sendMessage(e,{})}},b=new class{constructor(){this._name="AttributesDataHandler",this._groupAttributesCache=new Map,this._groupAttributesCacheValuesCopy={}}init(e){var{helper:e,constants:t}=this._core=e;e.registerWorkflowStep(t.WORKFLOW_NAME.SYNC_SERVER_INFO_AFTER_RE_ONLINE,t.WORKFLOW_STEP.GROUP_ATTRIBUTE_CACHE_CLEAR,this.clearLocalMainSequence,this)}clearLocalMainSequence(){this._groupAttributesCache.forEach(e=>{e.localMainSequence=0})}isGroupAttributesUpdated(e){var e=e["elements"]["newGroupProfile"],{isEmpty:t,isUndefined:s}=this._core["utils"];return!s(e)&&!t(e.groupAttributeOption)}handleGroupAttributesUpdated(e){var{groupID:e,groupAttributeOption:t}=e,{serverMainSequence:t,groupAttributeList:s=[],operation:r}=t,i=(this._core.ssoLog.debug("handleGroupAttributesUpdated",this._name+`.handleGroupAttributesUpdated groupID:${e} operation:`+r),this._core)["utils"]["isUndefined"];i(r)||(this.refreshGroupAttributesCache({groupID:e,serverMainSequence:t,groupAttributeList:s,operation:r}),this.emitGroupAttributesUpdated(e))}initGroupAttributesCache(e){var{groupID:e,avChatRoomKey:t}=e;this._groupAttributesCache.set(e,{lastUpdateTime:0,localMainSequence:0,serverMainSequence:0,avChatRoomKey:t,values:new Map}),this._core.ssoLog.debug("initGroupAttributesCache",this._name+`.initGroupAttributesCache. groupID:${e} avChatRoomKey:`+t)}hasGroupAttributesCache(e){return this._groupAttributesCache.has(e)}getGroupAttributesCache(e){return this.hasGroupAttributesCache(e)||this.initGroupAttributesCache({groupID:e}),this._groupAttributesCache.get(e)}deleteGroupAttributesCache(e){this.hasGroupAttributesCache(e)&&this._groupAttributesCache.delete(e)}refreshGroupAttributesCache(e){var{groupID:s,serverMainSequence:r,groupAttributeList:i,operation:n}=e;if(this.hasGroupAttributesCache(s)){let e=this.getGroupAttributesCache(s),t=e["localMainSequence"];5!==n&&r-t!=1||(e.serverMainSequence=r,e.localMainSequence=r,e.lastUpdateTime=Date.now(),this._updateGroupAttributesCacheValues({groupAttributes:e,groupAttributeList:i,operation:n})),1<r-t&&(e.serverMainSequence=r),this._groupAttributesCache.set(s,e),this._core.ssoLog.debug("refreshGroupAttributesCache",this._name+`.refreshGroupAttributesCache. operation:${n} localMainSequence:${t} serverMainSequence:`+r)}}_updateGroupAttributesCacheValues(e){let{groupAttributes:r,groupAttributeList:t=[],operation:s}=e;3!==s?4!==s?(1===s&&r.values.clear(),t.forEach(e=>{var{key:e,value:t,sequence:s}=e;r.values.set(e,{value:t,sequence:s})})):t.forEach(e=>{r.values.delete(e.key)}):r.values.clear()}getGroupAttributesCacheValues(e){let s,{groupID:r,keyList:i=[]}=e,n={};if(this.hasGroupAttributesCache(r)){let t=this.getGroupAttributesCache(r)["values"];if(0===i.length)for(let e of t.keys())n[e]=(null==(s=t.get(e))?void 0:s.value)||"";else i.forEach(e=>{t.has(e)&&(n[e]=(null==(e=t.get(e))?void 0:e.value)||"")})}return n}saveGroupAttributesCacheValuesCopy(e){this._groupAttributesCacheValuesCopy=this.getGroupAttributesCacheValues({groupID:e})}emitGroupAttributesUpdated(e){var t,s=this.getGroupAttributesCacheValues({groupID:e}),{updatedKeyList:r,deletedKeyList:i}=this._computeValuesChangedData(s);this._core.ssoLog.debug("emitGroupAttributesUpdated",`${this._name}.emitGroupAttributesUpdated update count:${r.length}, delete count:`+i.length),0===r.length&&0===i.length||this._emitEvent({name:null==(t=this._core)?void 0:t.OuterEvent.GROUP_ATTRIBUTES_UPDATED,data:{groupID:e,groupAttributes:s,updatedKeyList:r,deletedKeyList:i}})}_computeValuesChangedData(t){let{isUndefined:s}=this._core["utils"],r=[],i=[];return Object.keys(t).forEach(e=>{t[e]!==this._groupAttributesCacheValuesCopy[e]&&r.push(e)}),Object.keys(this._groupAttributesCacheValuesCopy).forEach(e=>{s(t[e])&&i.push(e)}),this._groupAttributesCacheValuesCopy={},{updatedKeyList:r,deletedKeyList:i}}_emitEvent(e){var t;null!=(t=this._core)&&t.notificationCenter.emitOuterEvent(e.name,e)}convertKeyValueMapToList(t){let s=[];return Object.keys(t).forEach(e=>{s.push({key:e,value:t[e]})}),s}reset(){this._groupAttributesCache.clear(),this._groupAttributesCacheValuesCopy={}}},No=new class{constructor(){this._name="DismissGroup"}init(e,t){e=(this._core=e).helper;e.registerApi({apiName:"dismissGroup",context:this,matcher:()=>!t.getInstalledSubPlugins().includes(no)})}dismissGroup(i){return I(this,void 0,void 0,function*(){let{ChatError:t}=this._core["helper"];try{yield function(e,t){return I(this,void 0,void 0,function*(){return t.common.buildAndSendPacket({servcmd:"group_open_http_svc.destroy_group",data:{GroupId:e}})})}(i,this._core);let e=R.getLocalGroup(i)["type"];return R.deleteLocalGroup(i),R.emitGroupListUpdate(),b.deleteGroupAttributesCache(i),D({groupID:i,type:e},{message:i})}catch(e){var{errorCode:s,errorInfo:r}=e;throw new t({functionName:"dismissGroup",code:s,message:r})}})}},Lo=new class{constructor(){this._name="GetGroupProfile"}init(e){e=(this._core=e).helper;e.registerApi({apiName:"getGroupProfile",context:this})}getGroupProfile(t){return I(this,void 0,void 0,function*(){let{groupID:i,groupCustomFieldFilter:e}=t,n={groupIDList:[i],responseFilter:{GroupBaseInfoFilter:[...ao],AppDefinedDataFilter_Group:e,MemberInfoFilter:[...co]}},{ChatError:r}=this._core["helper"];try{let e=yield this.getGroupProfileAdvance(n),{successGroupList:t,failureGroupList:s}=e;if(0<s.length)throw s[0];let r;return(r=!R.hasLocalGroup(i)&&Eo(t[0].type)?new To(t[0]):(R.updateLocalGroup(t),R.getLocalGroup(i))).isSupportTopic||R.updateConversationGroupProfile(i),D({group:r},{message:"groupID:"+i})}catch(e){let{code:t,message:s}=e;throw new r({functionName:"getGroupProfile",code:t,message:s})}})}getGroupProfileAdvance(a){return I(this,void 0,void 0,function*(){let e=a["groupIDList"],{isCommunity:t}=this._core["common"],s=e.filter(e=>!t({groupID:e})),r=e.filter(e=>t({groupID:e})),i=(50<s.length&&(s.length=50),50<r.length&&(r.length=50),yield Promise.all([this._getGroupProfileAdvance(Object.assign(Object.assign({},a),{groupIDList:s})),this._getGroupProfileAdvance(Object.assign(Object.assign({},a),{groupIDList:r,isCommunityProfile:!0}))])),n=[],o=[];return i.forEach(e=>{n.push(...e.successGroupList),o.push(...e.failureGroupList)}),{successGroupList:n,failureGroupList:o}})}_getGroupProfileAdvance(e){return I(this,void 0,void 0,function*(){let{ssoLog:n,utils:{isUndefined:o}}=this._core,{isCommunityProfile:t=!1}=e,a=f(e,["isCommunityProfile"]);if(0===a.groupIDList.length)return{successGroupList:[],failureGroupList:[]};try{let e=yield function(s,r){return I(this,void 0,void 0,function*(){var{groupIDList:e,responseFilter:t}=s;return r.common.buildAndSendPacket({servcmd:"group_open_http_svc.get_group_self_member_info",data:{GroupIdList:e,ResponseFilter:t}})})}(a,this._core),{GroupInfo:t=[]}=e||{},s=this._convertGroupProfileKey(t),r=s.filter(e=>o(e.errorCode)||0===e.errorCode),i=s.filter(e=>e.errorCode&&0!==e.errorCode).map(e=>({code:e.errorCode,message:e.errorInfo,data:{groupID:e.groupID}}));return n.debug("_getGroupProfileAdvance",this._name+"._getGroupProfileAdvance ok, groupID:"+a.groupIDList.join(",")),{successGroupList:r,failureGroupList:i}}catch(e){if(t)return{successGroupList:[],failureGroupList:[]};throw e}})}_convertGroupProfileKey(s){var r=[];for(let e=0,t=s.length;e<t;e++){var{AppDefinedData:i,ApplyJoinOption:n,CreateTime:o,FaceUrl:a,GroupId:l,InfoSeq:u,Introduction:c,InviteJoinOption:d,LastInfoTime:h,LastMsgTime:g,MaxMemberNum:p,MemberNum:_,MuteAllMember:m,Name:v,NextMsgSeq:f,Notification:I,Owner_Account:E,ShutUpAllMember:S,ShutUpUntil:C,Type:M,MemberList:y,ErrorCode:O,ErrorInfo:A}=s[e],i=Co(i),y=this._convertMembers(y);r.push({groupCustomField:i,joinOption:n,createTime:o,avatar:a,groupID:l,infoSequence:u,introduction:c,inviteOption:d,lastInfoTime:h,lastMsgTime:g,maxMemberCount:p,memberCount:_,muteAllMembers:m,name:v,nextMessageSeq:f,notification:I,ownerID:E,shutUpAllMember:S,muteUntil:C,type:M,members:y,errorCode:O,errorInfo:A})}return r}_convertMembers(s){if(!s)return[];var r=[];for(let e=0,t=s.length;e<t;e++){var{AppMemberDefinedData:i,JoinTime:n,Member_Account:o,MsgFlag:a,MsgSeq:l,NameCard:u,Role:c}=s[e],i=Co(i);r.push({memberCustomField:i,joinTime:n,userID:o,messageRemindType:a,sequence:l,nameCard:u,role:c})}return r}},Po=new class{constructor(){this._groupCountersMap=new Map}init(e){this._core=e}getLocalGroupCounters(e){return this._hasLocalGroupCounters(e)||this.initGroupCountersCache({groupID:e}),this._groupCountersMap.get(e)}updateLocalGroupCounters(e){var{groupID:r,counterList:i=[],groupCounterSeq:n}=e;if(this._hasLocalGroupCounters(r)){let{counters:s,avChatRoomKey:e,groupCounterSeq:t}=this.getLocalGroupCounters(r);0<n&&n<t||(i.forEach(e=>{var{Key:e,Value:t=0}=e;s.set(e,t)}),this._groupCountersMap.set(r,{lastUpdateTime:Date.now(),groupCounterSeq:n,counters:s,avChatRoomKey:e}))}}initGroupCountersCache(e){var{groupID:e,avChatRoomKey:t}=e;this._groupCountersMap.set(e,{lastUpdateTime:0,groupCounterSeq:0,counters:new Map,avChatRoomKey:t})}getLocalCounters(e,s){let r={};if(this._hasLocalGroupCounters(e)){let t=this.getLocalGroupCounters(e)["counters"];if(0<s.length)s.forEach(e=>{t.has(e)&&(r[e]=t.get(e))});else for(let e of t.keys())r[e]=t.get(e)}return r}deleteLocalGroupCounters(e){var{groupID:s,counterList:r=[],groupCounterSeq:i}=e;if(this._hasLocalGroupCounters(s)){let{counters:t,avChatRoomKey:e}=this.getLocalGroupCounters(s);r.forEach(e=>{t.delete(e.key)}),this._groupCountersMap.set(s,{lastUpdateTime:Date.now(),groupCounterSeq:i,counters:t,avChatRoomKey:e})}}setGroupCounters(t,i){if(this._hasLocalGroupCounters(t)){let e=this.getLocalGroupCounters(t),s=e["counters"],r=!1;Object.entries(i).forEach(([e,t])=>{s.has(e)&&s.get(e)!==t&&(s.set(e,t),r=!0)}),r&&this._groupCountersMap.set(t,Object.assign(Object.assign({},e),{lastUpdateTime:Date.now(),counters:s}))}}_hasLocalGroupCounters(e){return this._groupCountersMap.has(e)}reset(){this._groupCountersMap.clear()}},Go=new class{constructor(){this._name="JoinGroup"}init(e,t){e=(this._core=e).helper;e.registerApi({apiName:"joinGroup",context:this,matcher:()=>!t.getInstalledSubPlugins().includes(no)})}joinGroup(s){return I(this,void 0,void 0,function*(){let r=s["groupID"],{helper:{ChatError:i},OuterConstant:e,ssoLog:t}=this._core;try{if(R.hasLocalGroup(r))try{return yield Lo.getGroupProfile({groupID:r}),D({status:e.JOIN_STATUS_ALREADY_IN_GROUP,group:R.getLocalGroup(r)},{message:`groupID:${r} joinedStatus:`+e.JOIN_STATUS_ALREADY_IN_GROUP})}catch(i){t.warn("joinGroup",this._name+`.joinGroup ${r} was unjoined, start to join!`),R.deleteLocalGroup(r)}return yield this._applyJoinGroup(s)}catch(e){let{errorCode:t,errorInfo:s}=e;throw new i({functionName:"joinGroup",code:t,message:s,moreMessage:"groupID:"+r})}})}_applyJoinGroup(h){return I(this,void 0,void 0,function*(){var{OuterConstant:e,helper:t,ssoLog:s}=this._core,r=h["groupID"],i=Object.assign({},h),t=t.checkBusinessCapabilityBits("AV_HISTORY_MSG"),i=(t&&(i.historyMessageFlag=1),yield function(r,i){return I(this,void 0,void 0,function*(){var{groupID:e,applyMessage:t,historyMessageFlag:s}=r;return i.common.buildAndSendPacket({servcmd:"group_open_http_svc.apply_join_group",data:{GroupId:e,ApplyMsg:t,HugeGroupHistoryMsgFlag:s}})})}(i,this._core)),{Type:i,JoinedStatus:n,LongPollingKey:o,StartSeq:a,HugeGroupFlag:l,AVChatRoomKey:u,RspMsgList:c=[]}=i||{},t=`groupID:${r} joinedStatus:${n} longPollingKey:${o} startSeq:${a} avChatRoomFlag:${l} canGetAVChatRoomHistoryMsg:${t}, historyMessageCount:`+c.length;s.debug("_applyJoinGroup",this._name+"._applyJoinGroup ok, "+t);let d=new To({groupID:r,type:i});if(n===e.JOIN_STATUS_WAIT_APPROVAL)return D({status:e.JOIN_STATUS_WAIT_APPROVAL,group:d});if(n!==e.JOIN_STATUS_SUCCESS)throw new this._core.helper.ChatError({code:2660});try{d=(yield Lo.getGroupProfile({groupID:r})).data.group}catch(e){s.warn("_applyJoinGroup",this._name+`._applyJoinGroup getGroupProfile failed, groupID: ${r}, errorCode:`+(null==e?void 0:e.code))}return this._handleJoinResult({group:d,avChatRoomFlag:l,longPollingKey:o,startSequence:a,avChatRoomKey:u,historyMessageList:c})})}_handleJoinResult(e){var{group:t,avChatRoomFlag:s,avChatRoomKey:r}=e;return 1===s?(b.initGroupAttributesCache({groupID:t.groupID,avChatRoomKey:r}),Po.initGroupCountersCache({groupID:t.groupID,avChatRoomKey:r}),D(e)):(R.updateLocalGroup([t]),R.emitGroupListUpdate(),D({status:this._core.OuterConstant.JOIN_STATUS_SUCCESS,group:t},{message:"groupID:"+t.groupID}))}},wo=new class{constructor(){this._name="QuitGroup"}init(e,t){e=(this._core=e).helper;e.registerApi({apiName:"quitGroup",context:this,matcher:()=>!t.getInstalledSubPlugins().includes(no)})}quitGroup(i){return I(this,void 0,void 0,function*(){if(!R.hasLocalGroup(i))throw new this._core.helper.ChatError({code:2623});let{ChatError:t}=this._core["helper"];try{yield function(e,t){return I(this,void 0,void 0,function*(){return t.common.buildAndSendPacket({servcmd:"group_open_http_svc.quit_group",data:{GroupId:e}})})}(i,this._core);let e=R.getLocalGroup(i)["type"];return R.deleteLocalGroup(i),R.emitGroupListUpdate(),b.deleteGroupAttributesCache(i),D({groupID:i,type:e},{message:"groupID:"+i})}catch(e){var{errorCode:s,errorInfo:r}=e;throw new t({functionName:"quitGroup",code:s,message:r,moreMessage:"groupID:"+i})}})}},Uo=new class{constructor(){this._name="SearchGroup"}init(e){e=(this._core=e).helper;e.registerApi({apiName:"searchGroupByID",context:this})}searchGroupByID(v){return I(this,void 0,void 0,function*(){try{var t=yield function(t,s){return I(this,void 0,void 0,function*(){var e={GroupIdList:[t],GroupBasePublicInfoFilter:[...lo]};return s.common.buildAndSendPacket({servcmd:"group_open_http_svc.get_group_public_info",data:e})})}(v,this._core),{GroupInfo:s=[]}=t||{},{AppDefinedData:e=[],ApplyJoinOption:r,CreateTime:i,FaceUrl:n,Introduction:o,InviteJoinOption:a,MaxMemberNum:l,MemberNum:u,Name:c,Owner_Account:d,Type:h,ErrorCode:g,ErrorInfo:p}=s[0];if(0!==g)throw new this._core.helper.ChatError({code:g,message:p});var _=Co(e),m=new To({groupID:v,name:c,avatar:n,introduction:o,joinOption:r,inviteOption:a,maxMemberCount:l,memberCount:u,type:h,ownerID:d,createTime:i,groupCustomField:_});return D({group:m})}catch(e){var{errorCode:t,errorInfo:s}=e;throw new this._core.helper.ChatError({functionName:"searchGroupByID",code:t,message:s})}})}},ko=new class{constructor(){this._name="UpdateGroupProfile"}init(e){e=(this._core=e).helper;e.registerApi({apiName:"updateGroupProfile",context:this})}updateGroupProfile(o){return I(this,void 0,void 0,function*(){let r=o["groupID"],{utils:{isUndefined:t},ssoLog:s,helper:i}=this._core,n=R.getLocalGroup(r);if(n){let e=n["type"];this._canIUseJoinOption(e)||t(o.joinOption)||(s.warn("updateGroupProfile",this._name+`.updateGroupProfile groupID:${r} joinOption is unavailable for Work/Meeting/AVChatRoom`),o.joinOption=void 0)}t(o.muteAllMembers)||(o.muteAllMembers=!0===o.muteAllMembers?"On":"Off");try{return yield function(u,c){return I(this,void 0,void 0,function*(){var{groupID:e,name:t,avatar:s,introduction:r,notification:i,muteAllMembers:n,joinOption:o,inviteOption:a,groupCustomField:l}=u,e={GroupId:e,Name:t,FaceUrl:s,Introduction:r,Notification:i,ShutUpAllMember:n,ApplyJoinOption:o,InviteJoinOption:a,AppDefinedData:l?Mo(l):void 0};return c.common.buildAndSendPacket({servcmd:"group_open_http_svc.modify_group_base_info",data:e})})}(o,this._core),n?(n.updateGroup(o),R.emitGroupListUpdate()):n=new To(o),D({group:n},{message:"groupID:"+r})}catch(e){let{errorCode:t,errorInfo:s}=e;throw new i.ChatError({code:t,message:s,moreMessage:"groupID:"+r})}})}_canIUseJoinOption(e){return Io(e)||this._core.common.isCommunity({type:e})}},Fo=new class{constructor(){this._name="ChangeGroupOwner"}init(e){e=(this._core=e).helper;e.registerApi({apiName:"changeGroupOwner",context:this})}changeGroupOwner(o){return I(this,void 0,void 0,function*(){var t="changeGroupOwner",{groupID:e,newOwnerID:s}=o,e=R.getLocalGroup(e),{helper:r,OuterConstant:i,common:{getCurrentUserID:n}}=this._core;if((null==e?void 0:e.type)===i.GRP_AVCHATROOM)throw new r.ChatError({functionName:t,code:2620});if(s===n())throw new r.ChatError({functionName:t,code:2621});try{return yield function(s,r){return I(this,void 0,void 0,function*(){var{groupID:e,newOwnerID:t}=s;return r.common.buildAndSendPacket({servcmd:"group_open_http_svc.change_group_owner",data:{GroupId:e,NewOwner_Account:t}})})}(o,this._core),e.ownerID=s,R.emitGroupListUpdate(),D({group:e})}catch(e){throw new r.ChatError({functionName:t,code:null==e?void 0:e.errorCode,message:null==e?void 0:e.errorInfo})}})}},qo=new class{constructor(){this._name="GetGroupOnlineMemberCount",this._onlineMemberCountMap=new Map}init(e,t){e=(this._core=e).helper;e.registerApi({apiName:"getGroupOnlineMemberCount",context:this,matcher:()=>!t.getInstalledSubPlugins().includes(no)})}getGroupOnlineMemberCount(n){return I(this,void 0,void 0,function*(){let s="getGroupOnlineMemberCount";if(!R.hasLocalGroup(n))return D({memberCount:0});let r=Date.now();if(this._onlineMemberCountMap.has(n)){let e=this._onlineMemberCountMap.get(n),{lastReqTime:t=0,memberCount:s=0}=e||{};if(r-t<=6e4)return D({memberCount:s})}try{let e=yield function(e,t){return I(this,void 0,void 0,function*(){return t.common.buildAndSendPacket({servcmd:"group_open_http_svc.get_online_member_num",data:{GroupId:e}})})}(n,this._core),{OnlineMemberNum:t=0}=e||{};this._onlineMemberCountMap.set(n,{lastReqTime:Date.now(),memberCount:t});var i=`${this._name}.${s} ok. groupID:${n} memberCount:`+t;return D({memberCount:t},{message:i})}catch(e){throw new this._core.helper.ChatError({functionName:s,code:null==e?void 0:e.errorCode,message:null==e?void 0:e.errorInfo})}})}},xo=new class{init(e,t){e.ssoLog.debug("GroupAction.init"),Do.init(e),bo.init(e),No.init(e,t),Go.init(e,t),wo.init(e,t),Uo.init(e),Lo.init(e),ko.init(e),Fo.init(e),qo.init(e,t)}dismissGroup(e){return No.dismissGroup(e)}joinGroup(e){return Go.joinGroup(e)}quitGroup(e){return wo.quitGroup(e)}getGroupOnlineMemberCount(e){return qo.getGroupOnlineMemberCount(e)}},Vo=new class{constructor(){this._name="GetGroupApplicationList"}init(e){e=(this._core=e).helper;e.registerApi({apiName:"getGroupApplicationList",context:this})}getGroupApplicationList(){return I(this,void 0,void 0,function*(){var t="getGroupApplicationList";try{var e=yield Promise.all([this._getGroupApplicationList(),this._getGroupApplicationList({type:this._core.OuterConstant.GRP_COMMUNITY})]),s=(this._core.ssoLog.debug("getGroupApplicationList",this._name+`.${t} ok.`),this._handleGroupApplicationResult([...e[0],...e[1]]));return D({applicationList:s})}catch(e){throw new this._core.helper.ChatError({functionName:t,code:null==e?void 0:e.errorCode,message:null==e?void 0:e.errorInfo})}})}_getGroupApplicationList(n){return I(this,void 0,void 0,function*(){var{type:e,startTime:t=0,limit:s=20}=n||{},r=this._core["common"];let i;try{i=yield function(i,n){return I(this,void 0,void 0,function*(){var{type:e,startTime:t,limit:s,handleAccount:r}=i;return n.common.buildAndSendPacket({servcmd:"group_open_http_svc.get_pendency",data:{Type:e,StartTime:t,Limit:s,Handle_Account:r}})})}({type:e,startTime:t,limit:s,handleAccount:r.getCurrentUserID()},this._core)}catch(e){if(11e3!==(null==e?void 0:e.errorCode))throw e;i={}}var{NextStartTime:e=0,PendencyList:t=[]}=i||{};return 0===e?t:(s=yield this._getGroupApplicationList(Object.assign(Object.assign({},n),{startTime:e})),[...t,...s])})}_handleGroupApplicationResult(e){let s=[];return e.forEach(e=>{var e=this._convertApplicationData(e),t=e["handled"],e=f(e,["handled"]);0===t&&s.push(e)}),s}_convertApplicationData(e){var{Handled:e,AddTime:t,ApplyInviteMsg:s,Authentication:r,FromUserNickName:i,From_Account:n,GroupId:o,GroupName:a,PendencyType:l,To_Account:u}=e;return{handled:e,messageKey:t,applicant:n,applicantNick:i,groupID:o,groupName:a,authentication:r,applicationType:l,userID:u,note:s}}},Bo=new class{constructor(){this._name="HandleGroupApplication"}init(e){e=(this._core=e).helper;e.registerApi({apiName:"handleGroupApplication",context:this})}handleGroupApplication(e){return I(this,void 0,void 0,function*(){var t=e["application"],s=this._handleParams(e);try{2===(null==t?void 0:t.applicationType)?yield function(o,a){return I(this,void 0,void 0,function*(){var{groupID:e,handleAction:t,handleMessage:s,applicant:r,authentication:i,invitee:n}=o;return a.common.buildAndSendPacket({servcmd:"group_open_http_svc.handle_invite_join_permission_group",data:{GroupId:e,HandleMsg:t,ApprovalMsg:s,Applicant_Account:r,Authentication:i,Invited_Account:n}})})}(s,this._core):yield function(o,a){return I(this,void 0,void 0,function*(){var{groupID:e,handleAction:t,handleMessage:s,applicant:r,authentication:i,messageKey:n}=o;return a.common.buildAndSendPacket({servcmd:"group_open_http_svc.handle_apply_join_group",data:{GroupId:e,HandleMsg:t,ApprovalMsg:s,Applicant_Account:r,Authentication:i,MsgKey:n}})})}(s,this._core);let e=R.getLocalGroup(s.groupID);return D({group:e})}catch(e){throw new this._core.helper.ChatError({functionName:"handleGroupApplication",code:null==e?void 0:e.errorCode,message:null==e?void 0:e.errorInfo})}})}_handleParams(e){var{handleAction:e,handleMessage:t,message:s,application:r}=e;let i,n,o,a,l;if(s){let e=(s||{})["payload"];i=e.operatorID,n=null==(s=e.groupProfile)?void 0:s.groupID,o=e.authentication,a=e.messageKey}else i=(null==r?void 0:r.applicant)||"",n=(null==r?void 0:r.groupID)||"",o=(null==r?void 0:r.authentication)||"",a=(null==r?void 0:r.messageKey)||0;return 2===(null==r?void 0:r.applicationType)&&(l=r.userID),{handleAction:e,handleMessage:t,applicant:i,invitee:l,groupID:n,authentication:o,messageKey:a}}},jo=new class{init(e){e.ssoLog.debug("GroupApplication.init"),Vo.init(e),Bo.init(e)}};let Ko=class{constructor(e){this.userID="",this.avatar="",this.nick="",this.role="",this.joinTime="",this.nameCard="",this.muteUntil=0,this.memberCustomField=[],this.isOnline=!1,this.updateMember(e)}updateMember(e){var{utils:{isUndefined:t},common:{deepMerge:s}}=io["core"],t=(t(e.muteTime)||(this.muteUntil=Math.floor((Date.now()+1e3*e.muteTime)/1e3)),t(e.onlineStatus)||(this.isOnline="Online"===e.onlineStatus),[null,void 0,"",0,NaN]);e.memberCustomField&&So(this.memberCustomField,e.memberCustomField),s(this,e,["memberCustomField","marks","onlineStatus","muteTime"],t)}};function Ho(a,l){return I(this,void 0,void 0,function*(){var{groupID:e,userID:t,muteTime:s,role:r,nameCard:i,memberCustomField:n}=a;let o;e={GroupId:e,Member_Account:t,ShutUpTime:s,Role:r,NameCard:i,AppMemberDefinedData:o=n?Mo(n):o};return l.common.buildAndSendPacket({servcmd:"group_open_http_svc.modify_group_member_info",data:e})})}var Wo=new class{constructor(){this._name="GetGroupMemberList"}init(e,t){e=(this._core=e).helper;e.registerApi({apiName:"getGroupMemberList",context:this,matcher:()=>!t.getInstalledSubPlugins().includes(no)})}getGroupMemberList(r){return I(this,void 0,void 0,function*(){let u="getGroupMemberList",{groupID:c,offset:d=0,count:e=100,role:t="",filter:s=""}=r,h=R.getLocalGroup(c),g=100<e?100:e,p={groupID:c,offset:d,limit:g,memberRoleFilter:_o.includes(t)?[t]:void 0,memberInfoFilter:mo};try{let e=yield function(o,a){return I(this,void 0,void 0,function*(){var e=a.common["isCommunity"],{groupID:t,offset:s,limit:r,memberRoleFilter:i,memberInfoFilter:n}=o,r={GroupId:t,Limit:r,MemberRoleFilter:i,MemberInfoFilter:n};return e({groupID:t})?r.Next=String(s):r.Offset=s,a.common.buildAndSendPacket({servcmd:"group_open_http_svc.get_group_member_info",data:r})})}(p,this._core),{MemberList:t,MemberNum:s,Next:r}=e||{},i=`${this._name}.${u} ok, totalMemberCount:${s} next:`+r,{utils:{isArray:n,isEmpty:o},common:{isCommunity:a}}=this._core;if(h&&(h.memberCount=s),!n(t)||0===t.length)return D({memberList:[],offset:0},{message:i});let l=d+g;a({groupID:c})&&(l=o(r)?0:r),t.length<g&&(l=0);var _=this._convertMemberInfo(t),_=yield this._patchAvatarAndNick(_),m=this._generateGroupMember(_);return D({memberList:m,offset:l},{message:i})}catch(e){throw new this._core.helper.ChatError({functionName:u,code:null==e?void 0:e.errorCode,message:null==e?void 0:e.errorInfo})}})}_convertMemberInfo(s){var r=[];for(let e=0,t=s.length;e<t;e++){var{AppMemberDefinedData:i,JoinTime:n,Member_Account:o,OnlineStatus:a,Role:l,ShutUpUntil:u,NameCard:c}=s[e],i=Co(i);r.push({userID:o,joinTime:n,onlineStatus:a,role:l,muteUntil:u,memberCustomField:i,nameCard:c})}return r}_patchAvatarAndNick(n){return I(this,void 0,void 0,function*(){let e,t=n.map(e=>e.userID),s=yield null==(e=this._core.user.userProfile)?void 0:e.getUserProfile({userIDList:t}),r=(null==s?void 0:s.data)||[],i=new Map(r.map(e=>[e.userID,e]));return n.forEach(e=>{var t,s;i.has(e.userID)&&({nick:t="",avatar:s=""}=i.get(e.userID),e.nick=t,e.avatar=s)}),n})}_generateGroupMember(s){var r=[];for(let e=0,t=s.length;e<t;e++){var i=new Ko(s[e]);r.push(i)}return r}},Yo=new class{constructor(){this._name="GetGroupMemberProfile"}init(e){e=(this._core=e).helper;e.registerApi({apiName:"getGroupMemberProfile",context:this})}getGroupMemberProfile(c){return I(this,void 0,void 0,function*(){let t="getGroupMemberProfile",{groupID:r,userIDList:i,memberCustomFieldFilter:n}=c,e=R.getLocalGroup(r),{helper:s,utils:{isArray:o},ssoLog:a}=this._core;if(e&&Eo(e.type))throw new s.ChatError({functionName:t,replacement1:t,code:2687});50<i.length&&(a.warn("getGroupMemberProfile",`${this._name}.${t} userIDList length:${i.length} exceeds limit 50`),i.splice(50));var l=`userIDList length:${i.length} groupID:`+r;try{let e=yield function(i,n){return I(this,void 0,void 0,function*(){var{groupID:e,userIDList:t,memberInfoFilter:s,memberCustomFieldFilter:r}=i;return n.common.buildAndSendPacket({servcmd:"group_open_http_svc.get_specified_group_member_info",data:{GroupId:e,Member_List_Account:t,MemberInfoFilter:s,AppDefinedDataFilter_GroupMember:r}})})}({groupID:r,userIDList:i,memberCustomFieldFilter:n,memberInfoFilter:[...mo]},this._core),t=(e||{})["MemberList"];if(!o(t)||0===t.length)return D({memberList:[]});var u=this._convertMemberInfo(t),u=yield this._getMemberAvatarAndNick(u);let s=this._generateGroupMember(u);return D({memberList:s},{message:l})}catch(e){throw new s.ChatError({functionName:t,code:null==e?void 0:e.errorCode,message:null==e?void 0:e.errorInfo,moreMessage:l})}})}_convertMemberInfo(s){var r=[];for(let e=0,t=s.length;e<t;e++){var{AppMemberDefinedData:i,JoinTime:n,Member_Account:o,OnlineStatus:a,Role:l,ShutUpUntil:u,NameCard:c}=s[e],i=Co(i);r.push({userID:o,joinTime:n,onlineStatus:a,role:l,muteUntil:u,memberCustomField:i,nameCard:c})}return r}_getMemberAvatarAndNick(n){return I(this,void 0,void 0,function*(){let e,t=n.map(e=>e.userID),s=yield null==(e=this._core.user.userProfile)?void 0:e.getUserProfile({userIDList:t}),r=(null==s?void 0:s.data)||[],i=new Map(r.map(e=>[e.userID,e]));return n.forEach(e=>{var t,s;i.has(e.userID)&&({nick:t="",avatar:s=""}=i.get(e.userID),e.nick=t,e.avatar=s)}),n})}_generateGroupMember(s){var r=[];for(let e=0,t=s.length;e<t;e++){var i=new Ko(s[e]);r.push(i)}return r}},$o=new class{constructor(){this._name="AddGroupMember"}init(e){e=(this._core=e).helper;e.registerApi({apiName:"addGroupMember",context:this})}addGroupMember(r){return I(this,void 0,void 0,function*(){let t="addGroupMember",{groupID:o,userIDList:e}=r,a=R.getLocalGroup(o),s=this._core["helper"];if(a&&Eo(a.type))throw new s.ChatError({functionName:t,code:2661});var l=e.map(e=>({Member_Account:e}));try{let e=yield function(s,r){return I(this,void 0,void 0,function*(){var{groupID:e,userIDList:t}=s;return r.common.buildAndSendPacket({servcmd:"group_open_http_svc.add_group_member",data:{GroupId:e,MemberList:t}})})}({groupID:o,userIDList:l},this._core),{MemberList:t=[]}=e||{},{failureUserIDList:s,successUserIDList:r,existedUserIDList:i,overLimitUserIDList:n}=this._handleResult(t);return D({failureUserIDList:s,successUserIDList:r,existedUserIDList:i,overLimitUserIDList:n,group:a},{message:` groupID:${o} successUserIDList:${r} failureUserIDList:${s} existedUserIDList:${i} overLimitUserIDList:`+n})}catch(e){throw new s.ChatError({functionName:t,code:null==e?void 0:e.errorCode,message:null==e?void 0:e.errorInfo})}})}_handleResult(e){let s=[],r=[],i=[],n=[];return e.forEach(e=>{var{Result:e,Member_Account:t}=e;0===e?s.push(t):1===e?r.push(t):2===e?i.push(t):4===e&&n.push(t)}),{failureUserIDList:s,successUserIDList:r,existedUserIDList:i,overLimitUserIDList:n}}},zo=new class{constructor(){this._name="DeleteGroupMember"}init(e,t){e=(this._core=e).helper;e.registerApi({apiName:"deleteGroupMember",context:this,matcher:()=>!t.getInstalledSubPlugins().includes(no)})}deleteGroupMember(a){return I(this,void 0,void 0,function*(){var t="deleteGroupMember",{groupID:e,userIDList:s}=a,r=R.getLocalGroup(e),{helper:i,utils:{isUndefined:n},ssoLog:o}=this._core;if(n(r))throw new i.ChatError({functionName:t,code:2603});20<s.length&&(o.warn("deleteGroupMember",`${this._name}.${t} userIDList length:${s.length} exceeds limit 20`),s.splice(20));try{return yield function(r,i){return I(this,void 0,void 0,function*(){var{groupID:e,userIDList:t,reason:s}=r;return i.common.buildAndSendPacket({servcmd:"group_open_http_svc.delete_group_member",data:{GroupId:e,MemberToDel_Account:t,Reason:s}})})}({groupID:e,userIDList:s},this._core),D({group:r,userIDList:s},{message:`groupID:${e} userIDList length:`+s.length})}catch(e){throw new i.ChatError({functionName:t,code:null==e?void 0:e.errorCode,message:null==e?void 0:e.errorInfo})}})}},Jo=new class{constructor(){this._name="SetGroupMemberMuteTime"}init(e){e=(this._core=e).helper;e.registerApi({apiName:"setGroupMemberMuteTime",context:this})}setGroupMemberMuteTime(o){return I(this,void 0,void 0,function*(){let t=this._core["helper"],{groupID:s,userID:r,muteTime:i}=o,n=` groupID:${s} userID:${r} muteTime:`+i;this._preCheckSettingMuteParams(o);try{yield Ho(o,this._core);let e=R.getLocalGroup(s),t=new Ko({userID:r,muteTime:i});return D({group:e,member:t},{message:n})}catch(e){throw new t.ChatError({functionName:"setGroupMemberMuteTime",code:null==e?void 0:e.errorCode,message:null==e?void 0:e.errorInfo,moreMessage:n})}})}_preCheckSettingMuteParams(e){var e=e["userID"],{store:t,helper:s}=this._core;if(e===t.get("login").userId)throw new s.ChatError({functionName:"setGroupMemberMuteTime",code:2685})}},Qo=new class{constructor(){this._name="SetGroupMemberRole"}init(e){e=(this._core=e).helper;e.registerApi({apiName:"setGroupMemberRole",context:this})}setGroupMemberRole(a){return I(this,void 0,void 0,function*(){let t="setGroupMemberRole",s=this._core["helper"],{groupID:r,userID:i,role:n}=a,o=`${this._name}.${t} ok, groupID:${r} userID:${i} role:`+n;this._preCheckSettingRoleParams(a);try{yield Ho(a,this._core);let e=R.getLocalGroup(r),t=new Ko({userID:i,role:n});return D({group:e,member:t},{message:o})}catch(e){throw new s.ChatError({functionName:t,code:null==e?void 0:e.errorCode,message:null==e?void 0:e.errorInfo,moreMessage:o})}})}_preCheckSettingRoleParams(e){var{groupID:e,userID:t,role:s}=e,{store:r,helper:i,OuterConstant:n,common:{isCommunity:o}}=this._core,a=R.getLocalGroup(e);if((null==(a=null==a?void 0:a.selfInfo)?void 0:a.role)!==n.GRP_MBR_ROLE_OWNER)throw new i.ChatError({functionName:"setGroupMemberRole",code:2681});if(t===r.get("login").userId)throw new i.ChatError({functionName:"setGroupMemberRole",code:2684});a=[..._o];if(o({groupID:e})&&a.push(n.GRP_MBR_ROLE_CUSTOM),!a.includes(s))throw new i.ChatError({functionName:"setGroupMemberRole",code:2683})}},Xo=new class{constructor(){this._name="SetGroupMemberNameCard"}init(e){e=(this._core=e).helper;e.registerApi({apiName:"setGroupMemberNameCard",context:this})}setGroupMemberNameCard(u){return I(this,void 0,void 0,function*(){let i="setGroupMemberNameCard",{helper:t,common:{getCurrentUserID:n}}=this._core;this._preCheckSettingNameCardParams(u);try{let{groupID:e,userID:t=n(),nameCard:s}=u,r={groupID:e,userID:t,nameCard:s};yield Ho(r,this._core);var o=`${this._name}.${i} ok, groupID:${e} userID:${t} nameCard:`+s,a=R.getLocalGroup(e),l=new Ko({userID:t,nameCard:s});return D({group:a,member:l},{message:o})}catch(e){throw new t.ChatError({functionName:i,code:null==e?void 0:e.errorCode,message:null==e?void 0:e.errorInfo,moreMessage:logText})}})}_preCheckSettingNameCardParams(e){var e=e["groupID"],t=this._core["helper"],e=R.getLocalGroup(e);if(Eo(null==e?void 0:e.type))throw new t.ChatError({functionName:"setGroupMemberNameCard",code:2687})}},Zo=new class{constructor(){this._name="SetGroupMemberCustomField"}init(e){e=(this._core=e).helper;e.registerApi({apiName:"setGroupMemberCustomField",context:this})}setGroupMemberCustomField(a){return I(this,void 0,void 0,function*(){let t="setGroupMemberCustomField",{helper:s,common:{getCurrentUserID:e}}=this._core;this._preCheckSettingCustomFiledParams(a);var{groupID:r,userID:i=e(),memberCustomField:n}=a,o=`${this._name}.${t} ok, groupID:${r}userID:${i} memberCustomField:`+JSON.stringify(n);try{let e={groupID:r,userID:i,memberCustomField:n},t=(yield Ho(e,this._core),R.getLocalGroup(r)),s=new Ko({userID:i,memberCustomField:n});return D({group:t,member:s},{message:o})}catch(e){throw new s.ChatError({functionName:t,code:null==e?void 0:e.errorCode,message:null==e?void 0:e.errorInfo,moreMessage:o})}})}_preCheckSettingCustomFiledParams(e){var e=e["groupID"],t=this._core["helper"],e=R.getLocalGroup(e);if(Eo(null==e?void 0:e.type))throw new t.ChatError({functionName:"setGroupMemberCustomField",code:2687})}},ea=new class{init(e,t){e.ssoLog.debug("GroupMember.init"),Wo.init(e,t),Yo.init(e),$o.init(e),zo.init(e,t),Jo.init(e),Qo.init(e),Xo.init(e),Zo.init(e)}getGroupMemberList(e){return Wo.getGroupMemberList(e)}deleteGroupMember(e){return zo.deleteGroupMember(e)}},ta=new class{init(e){e=(this._core=e).helper;e.registerApi({apiName:"getGroupCounters",context:this})}getGroupCounters(l){return I(this,void 0,void 0,function*(){var t="getGroupCounters";try{yo(t,oo);var e,s,r,{groupID:i,keyList:n=[]}=l,{avChatRoomKey:o,lastUpdateTime:a}=Po.getLocalGroupCounters(i);return Date.now()-a>=this._getExpireTime()&&(e=yield function(i){return I(this,void 0,void 0,function*(){var{groupID:e,GroupCounterKeys:t,avChatRoomKey:s}=i,r=io.core["common"];return r.buildAndSendPacket({servcmd:"group_open_http_svc.get_group_counter",data:{GroupId:e,keyList:t,BytesKey:s}})})}({groupID:i,keyList:n,avChatRoomKey:o}),{GroupCounter:s=[],GroupCounterSeq:r}=e,Po.updateLocalGroupCounters({groupID:i,counterList:s,groupCounterSeq:r})),{code:0,data:{counters:Po.getLocalCounters(i,n)}}}catch(e){Oo(t,e)}})}_getExpireTime(){var{store:e,utils:{isUndefined:t}}=this._core,e=(e.get("cloudConfig")||{})["grp_counter_expire_time"];return t(e)?3e4:Number(e)}},sa=new class{init(e){e=e.helper;e.registerApi({apiName:"setGroupCounters",context:this}),e.registerApi({apiName:"increaseGroupCounter",context:this}),e.registerApi({apiName:"decreaseGroupCounter",context:this})}setGroupCounters(e){return I(this,void 0,void 0,function*(){return this._handleCounterOperation("Set",e)})}increaseGroupCounter(e){return I(this,void 0,void 0,function*(){return this._handleCounterOperation("Increase",e)})}decreaseGroupCounter(e){return I(this,void 0,void 0,function*(){return this._handleCounterOperation("Decrease",e)})}_handleCounterOperation(a,l){return I(this,void 0,void 0,function*(){var t=a+"GroupCounter";try{yo(t,oo);var{groupID:e,key:s,value:r=0}=l,i=Po.getLocalGroupCounters(e)["avChatRoomKey"],n="Set"===a?this._convertObjectToList(l.counters):[{Key:s,Value:r}],o=yield this._updateGroupCounters({groupID:e,counterList:n,avChatRoomKey:i,mode:a});return Po.setGroupCounters(e,o),{code:0,data:{counters:o}}}catch(e){Oo(t,e)}})}_updateGroupCounters(n){return I(this,void 0,void 0,function*(){let e=yield function(){var{groupID:e,counterList:t,mode:s,avChatRoomKey:r}=n,i=io.core["common"];return i.buildAndSendPacket({servcmd:"group_open_http_svc.update_group_counter",data:{GroupId:e,GroupCounter:t,Mode:s,BytesKey:r}})}(),{GroupCounter:t=[]}=e,s={};return t.forEach(e=>{var{Key:e,Value:t=0}=e;s[e]=t}),s})}_convertObjectToList(e){return Object.entries(e).map(([e,t])=>({Key:e,Value:t||0}))}},ra=new class{init(e){this._core=e,ta.init(e),sa.init(e)}isGroupCounterUpdated(e){var e=e["elements"]["groupCounterInfo"],t=this._core["utils"]["isEmpty"];return!t(e)}handleGroupCounterUpdated(e){let{to:r,elements:{groupCounterInfo:t}}=e;t.forEach(e=>{var{type:e,groupCounterSeq:t,counterList:s=[]}=e;0!==e&&2!==e||this._processAndNotifyCounterUpdate(r,t,s),1===e&&Po.deleteLocalGroupCounters({groupID:r,groupCounterSeq:t,counterList:s})})}_processAndNotifyCounterUpdate(s,e,t){let{OuterEvent:r,notificationCenter:i}=this._core;Po.updateLocalGroupCounters({groupID:s,groupCounterSeq:e,counterList:t}),t.forEach(({Key:e,Value:t=0})=>{i.emitOuterEvent(r.GROUP_COUNTER_UPDATED,{name:r.GROUP_COUNTER_UPDATED,data:{groupID:s,key:e,value:t}})})}reset(){Po.reset()}},ia=new class{constructor(){this._name="InitGroupAttributes"}init(e){e=(this._core=e).helper;e.registerApi({apiName:"initGroupAttributes",context:this})}initGroupAttributes(e){return I(this,void 0,void 0,function*(){let{groupID:i,groupAttributes:n}=e,{serverMainSequence:o,avChatRoomKey:a}=b.getGroupAttributesCache(i),l=b.convertKeyValueMapToList(n);try{let e=yield function(i,n){return I(this,void 0,void 0,function*(){var{groupID:e,mainSequence:t,groupAttributeList:s,avChatRoomKey:r}=i;return n.common.buildAndSendPacket({servcmd:"group_open_http_svc.set_group_attr",data:{GroupId:e,AttrMainSeq:t,GroupAttr:s,BytesKey:r,AttrControl:["RaceConflict"]}})})}({groupID:i,avChatRoomKey:a,groupAttributeList:l,mainSequence:o},this._core),{AttrMainSeq:t,GroupAttr:s}=e||{},r=s.map(e=>{var{Key:e,seq:t}=e;return{key:e,value:n[e],sequence:t}});return b.saveGroupAttributesCacheValuesCopy(i),b.refreshGroupAttributesCache({groupID:i,serverMainSequence:t,groupAttributeList:r,operation:1}),b.emitGroupAttributesUpdated(i),D({groupAttributes:n},{message:` groupID:${i} serverMainSequence:`+t})}catch(e){throw new this._core.helper.ChatError({functionName:"initGroupAttributes",code:null==e?void 0:e.errorCode,message:null==e?void 0:e.errorInfo})}})}},na=new class{constructor(){this._name="SetGroupAttributes"}init(e){e=(this._core=e).helper;e.registerApi({apiName:"setGroupAttributes",context:this})}setGroupAttributes(e){return I(this,void 0,void 0,function*(){let{groupID:i,groupAttributes:n}=e,{serverMainSequence:o,avChatRoomKey:a,values:r}=b.getGroupAttributesCache(i),l=b.convertKeyValueMapToList(n).map(e=>{var{key:t,value:s}=e;return{key:t,value:s,seq:(null==(t=r.get(e.key))?void 0:t.sequence)||0}});try{let e=yield function(i,n){return I(this,void 0,void 0,function*(){var{groupID:e,mainSequence:t,groupAttributeList:s,avChatRoomKey:r}=i;return n.common.buildAndSendPacket({servcmd:"group_open_http_svc.modify_group_attr",data:{GroupId:e,AttrMainSeq:t,GroupAttr:s,BytesKey:r,AttrControl:["RaceConflict"]}})})}({groupID:i,avChatRoomKey:a,groupAttributeList:l,mainSequence:o},this._core),{AttrMainSeq:t,GroupAttr:s}=e||{},r=s.map(e=>{var{Key:e,seq:t}=e;return{key:e,value:n[e],sequence:t}});return b.saveGroupAttributesCacheValuesCopy(i),b.refreshGroupAttributesCache({groupID:i,serverMainSequence:t,groupAttributeList:r,operation:2}),b.emitGroupAttributesUpdated(i),D({groupAttributes:n},{message:` groupID:${i} serverMainSequence:`+t})}catch(e){throw new this._core.helper.ChatError({functionName:"setGroupAttributes",code:null==e?void 0:e.errorCode,message:null==e?void 0:e.errorInfo})}})}},oa=new class{constructor(){this._name="DeleteGroupAttributes"}init(e){e=(this._core=e).helper;e.registerApi({apiName:"deleteGroupAttributes",context:this})}deleteGroupAttributes(l){return I(this,void 0,void 0,function*(){var t="deleteGroupAttributes",{groupID:e,keyList:s=[]}=l;try{var{resultList:r,serverMainSequence:i,operation:n,groupAttributeList:o}=(0===s.length?yield this._clearGroupAttributes(e):yield this._deleteGroupAttributes(e,s))||{},a=this._name+`.${t} ok. groupID:${e} operation: `+n;return b.saveGroupAttributesCacheValuesCopy(e),b.refreshGroupAttributesCache({groupID:e,serverMainSequence:i,groupAttributeList:o,operation:n}),b.emitGroupAttributesUpdated(e),D({keyList:r},{message:a})}catch(e){throw new this._core.helper.ChatError({functionName:t,code:null==e?void 0:e.errorCode,message:null==e?void 0:e.errorInfo})}})}_deleteGroupAttributes(o,a){return I(this,void 0,void 0,function*(){let{serverMainSequence:e,avChatRoomKey:t,values:s}=b.getGroupAttributesCache(o),r=[],i=[];a.forEach(e=>{var t;s.has(e)&&({sequence:t=0}=s.get(e)||{},i.push({key:e,seq:t}),r.push(e))});var n=((yield function(i,n){return I(this,void 0,void 0,function*(){var{groupID:e,mainSequence:t,groupAttributeList:s,avChatRoomKey:r}=i;return n.common.buildAndSendPacket({servcmd:"group_open_http_svc.delete_group_attr",data:{GroupId:e,AttrMainSeq:t,GroupAttr:s,BytesKey:r,AttrControl:["RaceConflict"]}})})}({groupID:o,avChatRoomKey:t,groupAttributeList:i,mainSequence:e},this._core))||{})["AttrMainSeq"];return{resultList:r,serverMainSequence:n,groupAttributeList:i,operation:4}})}_clearGroupAttributes(r){return I(this,void 0,void 0,function*(){var{serverMainSequence:e,avChatRoomKey:t,values:s}=b.getGroupAttributesCache(r),s=[...s.keys()],t=((yield function(r,i){return I(this,void 0,void 0,function*(){var{groupID:e,mainSequence:t,avChatRoomKey:s}=r;return i.common.buildAndSendPacket({servcmd:"group_open_http_svc.clear_group_attr",data:{GroupId:e,AttrMainSeq:t,BytesKey:s,AttrControl:["RaceConflict"]}})})}({groupID:r,avChatRoomKey:t,mainSequence:e},this._core))||{})["AttrMainSeq"];return{resultList:s,serverMainSequence:t,operation:3}})}},aa=new class{constructor(){this._name="GetGroupAttributes"}init(e){e=(this._core=e).helper;e.registerApi({apiName:"getGroupAttributes",context:this})}getGroupAttributes(l){return I(this,void 0,void 0,function*(){let r=l["groupID"],{avChatRoomKey:i,lastUpdateTime:e,localMainSequence:t,serverMainSequence:s}=b.getGroupAttributesCache(r),{ChatError:n}=this._core["helper"],o=`groupID:${r} localMainSequence:${t} serverMainSequence:${s} keyList:`+l.keyList;if(3e4<=Date.now()-e||t<s)try{let e=yield this.getGroupAttributesFromServer({groupID:r,avChatRoomKey:i}),t=b.getGroupAttributesCacheValues(l),{serverGroupAttributeList:s=[]}=e||{};return D({groupAttributes:t},{message:o,moreMessage:"from server, count:"+s.length})}catch(e){throw new n({functionName:"getGroupAttributes",code:null==e?void 0:e.errorCode,message:null==e?void 0:e.errorInfo})}var a=b.getGroupAttributesCacheValues(l);return D({groupAttributes:a},{message:o,moreMessage:"from cache"})})}getGroupAttributesFromServer(i){return I(this,void 0,void 0,function*(){var{utils:{isUndefined:e},ssoLog:t}=this._core,{groupID:s,avChatRoomKey:r}=i,{AttrMainSeq:e=0,GroupAttrAry:r}=(yield function(r,i){return I(this,void 0,void 0,function*(){var{groupID:e,groupType:t,avChatRoomKey:s}=r;return i.common.buildAndSendPacket({servcmd:"group_open_attr_http_svc.get_group_attr",data:{GroupId:e,GroupType:t,Key:s}})})}({groupID:s,avChatRoomKey:r,groupType:e(r)?0:1},this._core))||{},t=(t.debug("getGroupAttributesFromServer",this._name+`._getGroupAttributesFromServer ok. groupID:${s} serverMainSequence:`+e),r.map(e=>{var{key:e,value:t,seq:s}=e;return{key:e,value:t,sequence:s}}));return b.refreshGroupAttributesCache({groupID:s,serverMainSequence:e,groupAttributeList:t,operation:5}),{serverGroupAttributeList:r}})}},la=new class{init(e){e.ssoLog.debug("GroupAttribute.init"),ia.init(e),na.init(e),oa.init(e),aa.init(e),b.init(e)}isGroupAttributesUpdated(e){return b.isGroupAttributesUpdated(e)}handleGroupAttributesUpdated(e){let{to:t,elements:{newGroupProfile:s}}=e,r=s["groupAttributeOption"],{serverMainSequence:i,withChangedAttributeInfo:n}=r,o=b.getGroupAttributesCache(t)["localMainSequence"],a=i-o;if(console.log(`GroupAttribute.handleGroupAttributesUpdated groupID:${t} withChangedAttributeInfo:${n} diffSequence:`+a),0!=a)if(b.saveGroupAttributesCacheValuesCopy(t),1!==n||1!=a){if(b.hasGroupAttributesCache(t)){let e=b.getGroupAttributesCache(t)["avChatRoomKey"];aa.getGroupAttributesFromServer({groupID:t,avChatRoomKey:e}).then(()=>{b.emitGroupAttributesUpdated(t)}).catch(()=>{})}}else b.handleGroupAttributesUpdated({groupID:t,groupAttributeOption:r})}reset(){b.reset()}};function ua(e,t="tips"){let{ClientSeq:s,From_Account:r,MsgClientTime:i,MsgPriority:n,MsgRandom:o,MsgSeq:a,MsgTimeStamp:l,TinyId:u,ToGroupId:c,GroupInfo:d,MsgBody:h}=e,g=function(){var{GroupCode:e,GroupId:t,GroupName:s,GroupType:r,MsgFrom_AccountExtraInfo:i,From_Account:n,To_Account:o}=d;return{groupCode:e,groupID:t,groupName:s,type:r,messageFromAccountExtraInformation:i,from:n,to:o}}();return{clientSequence:s,from:r,clientTime:i,priority:n,random:o,sequence:a,time:l,tinyID:u,to:c,groupProfile:g,elements:("tips"===t?ca:ha)(h)}}function ca(r){let t={};return Object.keys(r).forEach(s=>{var e;switch(s){case"MemberNum":t.memberCount=r[s];break;case"OpType":t.operationType=r[s];break;case"Operator_Account":t.operatorID=r[s];break;case"List_Account":t.userIDList=r[s];break;case"MsgMemberExtraInfo":t.memberInfoList=null==(e=r[s])?void 0:e.map(e=>da(e));break;case"MsgOperatorMemberExtraInfo":t.operatorInfo=da(r[s]);break;case"MsgGroupNewInfo":t.newGroupProfile=function(o){let e={};return Object.keys(o).forEach(n=>{switch(n){case"GroupIntroduction":e.introduction=o[n];break;case"GroupName":e.groupName=o[n];break;case"GroupFaceUrl":e.avatar=o[n];break;case"GroupNotification":e.notification=o[n];break;case"ApplyJoinOption":e.joinOption=o[n];break;case"InviteJoinOption":e.inviteOption=o[n];break;case"ShutupAll":e.muteAllMembers=o[n];break;case"Owner_Account":e.ownerID=o[n];break;case"GroupAttrOption":e.groupAttributeOption=function(){var{BytesChangedKeys:e,GroupAttrSeq:t,OpType:s,PushChangedAttrValFlag:r,GroupAttrInfo:i}=o[n];return{changedKeyList:e,groupAttributeList:i.map(e=>{var{Key:e,Val:t,SubKeySeq:s}=e;return{key:e,value:t,sequence:s}}),serverMainSequence:t,operation:s,withChangedAttributeInfo:r}}()}}),e}(r[s]);break;case"MsgMemberInfo":t.msgMemberInfo=null==(e=r[s])?void 0:e.map(e=>{var{ShutupTime:e,User_Account:t}=e;return{muteTime:e,userID:t}});break;case"OnlineMemberInfo":t.onlineMemberInfo=function(){var{ExpireTime:e,OnlineMemberNum:t}=r[s];return{expireTime:e,onlineMemberNum:t}}();break;case"GroupCounterInfo":t.groupCounterInfo=r[s].map(e=>{var{GroupCounterSeq:e,GroupCounter:t,Type:s}=e;return{type:s,groupCounterSeq:e,counterList:t}})}}),t}function da(e){var{ImageUrl:e,NickName:t,Role:s,UserId:r}=e;return{avatar:e,nick:t,role:s,userID:r}}function ha(t){let s={};return Object.keys(t).forEach(e=>{switch(e){case"MsgKey":s.messageKey=t[e];break;case"Operator_Account":s.operatorID=t[e];break;case"ReportType":s.operationType=t[e];break;case"Authentication":s.authentication=t[e];break;case"MsgFlag":s.messageRemindType=t[e];break;case"UserDefinedField":s.userDefinedField=t[e];break;case"RemarkInfo":s.remarkInfo=t[e];break;case"BanDuration":s.duration=t[e];break;case"MuteTime":s.muteTime=t[e]}}),s}class ga{constructor(e){this.type=io.core.OuterConstant.MSG_GRP_TIP,this.content={},this._initContent(e)}static parseServerPushElement(e){e=ca(e);return new ga(e)}_initContent(t){Object.keys(t).forEach(e=>{switch(e){case"groupProfile":this._initGroupProfile(t[e]);break;case"operatorInfo":this._initOperatorInfo(t[e]);break;case"memberInfoList":case"msgMemberInfo":this._updateMemberList(t[e]);break;case"newGroupProfile":this._initNewGroupProfile(t[e]);break;case"memberExtraInfo":case"remarkInfo":case"onlineMemberInfo":break;default:this.content[e]=t[e]}}),this.content.userIDList||(this.content.userIDList=[this.content.operatorID])}_initGroupProfile(t){this.content.groupProfile={};var s=Object.keys(t);for(let e=0;e<s.length;e++){var r=s[e];vo[r]&&(this.content.groupProfile[r]=t[r])}}_initOperatorInfo(t){this.content.operatorInfo={};var s=Object.keys(t);for(let e=0;e<s.length;e++){var r=s[e];this.content.operatorInfo[r]=t[r]}}_updateMemberList(e){this.content.memberList?this.content.memberList.forEach(t=>{e.forEach(e=>{t.userID===e.userID&&Object.assign(t,e)})}):this.content.memberList=e}_initNewGroupProfile(t){this.content.newGroupProfile={};var s=Object.keys(t);for(let e=0;e<s.length;e++){var r=s[e];"muteAllMembers"!==r?this.content.newGroupProfile[r]=t[r]:this.content.newGroupProfile.muteAllMembers=1===t.muteAllMembers}}}var pa=new class{constructor(){this._name="GroupTipsNotification"}init(e){var{common:{workflowManager:t},constants:{WORKFLOW_NAME:s,WORKFLOW_STEP:r}}=this._core=e,{message:{messageFactory:e},OuterConstant:i}=e;null!=e&&e.registerElementClass(i.MSG_GRP_TIP,ga),t.registerWorkflowStep(s.SYNC_SERVER_INFO_AFTER_RE_ONLINE,r.GROUP_TIPS_RECOVER,this._handleGroupTipsRecover,this),t.registerWorkflowStep(s.RECEIVE_GROUP_TIPS_NOTIFICATION,r.HANDLE_GROUP_TIPS_NOTIFICATION,this.onNewGroupTips,this)}onNewGroupTips(e){let t=(e||{})["data"],{messageList:s,conversationUpdateFieldList:r}=this._handleGroupTips(t),{notificationCenter:i,OuterEvent:n,appStore:{conversationStore:o}}=this._core;return null!=r&&r.forEach(e=>{var{conversationID:e,lastMessage:t,unreadCount:s}=e,{unreadCount:r=0}=o.getConversation(e)||{};o.updateConversation(e,{lastMessage:t,unreadCount:s+r})}),0<s.length&&(i.emitOuterEvent(n.MESSAGE_RECEIVED,{name:n.MESSAGE_RECEIVED,data:s}),this._handleGroupTipMessage(s)),{conversationUpdateFieldList:r}}_handleGroupTips(e,s=!0){let{Event:r,GroupTips:i}=e,n=new Map,t=[],o=[];for(let t=0,e=i.length;t<e;t++){let e=ua(i[t],"tips");if(6===r){if(la.isGroupAttributesUpdated(e)){la.handleGroupAttributesUpdated(e);continue}if(ra.isGroupCounterUpdated(e)){ra.handleGroupCounterUpdated(e);continue}}var a=e["groupProfile"]["groupID"];if(R.hasLocalGroup(a)){a=this._assembleMessage(e);if(6===r&&(a._onlineOnlyFlag=!0,o.push(a)),4===r){if(!this._core.message.messageDataHandler.storeConversationMessage(a)&&s)continue;o.push(a)}this._handleConversationOptions(n,a)}}return t.push(...n.values()),{conversationUpdateFieldList:t,messageList:o}}_assembleMessage(e){var{OuterConstant:t,message:{messageFactory:s}}=this._core,t=(e.flow="in",e.conversationType=t.CONV_GROUP,s.createMessage(e)),s=(this._patchNickAndAvatar(e.elements,t),new ga(Object.assign(Object.assign({},e.elements),{groupProfile:Object.assign({},e.groupProfile)})));return t.setElement(s),t.isSystemMessage=!1,t}_patchNickAndAvatar(e,s){let{utils:{isEmpty:t},OuterConstant:{GROUP_TIPS_OPERATION_TYPE:r}}=this._core,{operationType:i,memberInfoList:n,operatorInfo:o}=e,a={};if(t(n)?t(o)||(a=o):i!==r.JOINED&&i!==r.KICKED&&i!==r.ADMIN_SET&&i!==r.ADMIN_CANCELED||(a=Object.assign({},n[0])),!t(a)){let{nick:e="",avatar:t=""}=a;s.nick=e,s.avatar=t}}_handleConversationOptions(e,t){var{common:{getMessagePreviewText:s},utils:{isObject:r}}=this._core,{conversationID:i,conversationType:n}=t;let o;if(e.has(i))o=e.get(i),"in"!==t.flow||t._isExcludedFromUnreadCount||t._onlineOnlyFlag||o.unreadCount++,o.type=n,o.lastMessage=t._isExcludedFromLastMessage?"":Object.assign({},t);else{let e=0;"in"!==t.flow||t._isExcludedFromUnreadCount||t._onlineOnlyFlag||(e=1),o={conversationID:i,unreadCount:e,type:n,lastMessage:t._isExcludedFromLastMessage?"":Object.assign({},t)}}r(o.lastMessage)&&(o.lastMessage.messageForShow=s(o.lastMessage.type,o.lastMessage.payload)),e.set(i,o)}_handleGroupTipMessage(e){let{GROUP_TIPS_OPERATION_TYPE:s}=this._core["OuterConstant"];e.forEach(e=>{var t=e.payload["operationType"];switch(t){case s.JOINED:this._handleNewMemberJoined(e);break;case s.QUITTED:this._handleMemberQuitted(e);break;case s.KICKED:this._handleMemberKicked(e);break;case s.GROUP_PROFILE_UPDATED:this._handleGroupProfileUpdated(e)}})}_handleNewMemberJoined(e){this._handleGroupMemberCountUpdated(e)}_handleMemberQuitted(e){this._handleGroupMemberCountUpdated(e)}_handleMemberKicked(e){this._handleGroupMemberCountUpdated(e)}_handleGroupProfileUpdated(e){let t,{newGroupProfile:s,groupProfile:r,operatorInfo:i}=e.payload,n=r.groupID,o=R.getLocalGroup(n);Object.keys(s).forEach(e=>{switch(e){case"ownerID":this._handleGroupOwnerChanged(n,s);break;case"groupName":o.name=s[e];break;default:o[e]=s[e]}});var e=this._core["utils"]["isUndefined"];e(i)||(null==(t=null==o?void 0:o.selfInfo)?void 0:t.userID)!==i.userID||Object.keys(i).forEach(e=>{"nameCard"===e&&o.updateSelfInfo({nameCard:i[e]}),"role"===e&&this._updateSelfRole(o,i[e])}),R.emitGroupListUpdate(),R.updateConversationGroupProfile(n)}_handleGroupOwnerChanged(e,t){var{common:s,OuterConstant:r}=this._core,e=R.getLocalGroup(e),t=t["ownerID"];s.getCurrentUserID()===t&&e.updateGroup({ownerID:t,selfInfo:{role:r.GRP_MBR_ROLE_OWNER}})}_updateSelfRole(e,t){var s=this._core["OuterConstant"];let r=s.GRP_MBR_ROLE_MEMBER;400===t?r=s.GRP_MBR_ROLE_OWNER:300===t&&(r=s.GRP_MBR_ROLE_ADMIN),e.updateSelfInfo({role:r})}_handleGroupMemberCountUpdated(e){var{memberCount:e,groupProfile:{groupID:t}}=e.payload,s=R.getLocalGroup(t),r=this._core["utils"]["isNumber"];s&&r(e)&&s.memberCount!==e&&(s.memberCount=e,R.emitGroupListUpdate(),R.updateConversationGroupProfile(t))}_handleGroupTipsRecover(e){var t=this._core["utils"]["isArray"],e=((null==e?void 0:e.result)||{})["groupTipList"];t(e)&&e.forEach(e=>{e=this._handleGroupTips({Event:e.Event,GroupTips:[e]},!1).messageList;this._handleGroupTipMessage(e)})}};class _a{constructor(e){this.type=io.core.OuterConstant.MSG_GRP_SYS_NOTICE,this.content={},this._initContent(e)}static parseServerPushElement(e){e=ha(e);return new _a(e)}_initContent(t){Object.keys(t).forEach(e=>{switch(e){case"remarkInfo":this.content.handleMessage=t[e];break;case"groupProfile":this._initGroupProfile(t[e]);break;case"memberInfoList":break;default:this.content[e]=t[e]}})}_initGroupProfile(t){this.content.groupProfile={};var s=Object.keys(t);for(let e=0;e<s.length;e++){var r=s[e];fo[r]&&(this.content.groupProfile[r]=t[r])}}}var ma=new class{constructor(){this._name="GroupSystemNotification"}init(e){var{message:{messageFactory:e},OuterConstant:{MSG_GRP_SYS_NOTICE:t}}=this._core=e;null!=e&&e.registerElementClass(t,_a)}onNewGroupSystemNotification(e){var{GroupTips:e=[],isInstantMessage:t=!0}=e,{conversationUpdateFieldList:e,messageList:s}=(this._core.ssoLog.debug("onNewGroupSystemNotification",` count:${e.length} isInstantMessage:`+t),this._handleGroupSystemNotification(e,t)),{notificationCenter:r,OuterEvent:i}=this._core;0<e.length&&this._handleGroupSysTemMessage(t,s),!0===t&&0<s.length&&r.emitOuterEvent(i.MESSAGE_RECEIVED,{name:i.MESSAGE_RECEIVED,data:s})}_handleGroupSystemNotification(t,s){var r=[];let i={};for(let e=0;e<t.length;e++){var n=ua(t[e],"system"),o=n["elements"]["operationType"];15!==o&&(o=this._assembleMessage(n),this._core.message.messageDataHandler.storeConversationMessage(o))&&(r.push(o),i=this._handleConversationOptions(o,s))}return i.lastMessage=r[r.length-1],{conversationUpdateFieldList:0<r.length?[i]:[],messageList:r}}_assembleMessage(e){var{message:{messageFactory:t},OuterConstant:s,utils:{randomInt:r}}=this._core,s=(e.flow="in",e.conversationType=s.CONV_SYSTEM,e.conversationSubType=e.groupProfile.type,e.conversationID=s.CONV_SYSTEM,t.createMessage(e)),t=new _a(Object.assign(Object.assign({},e.elements),{groupProfile:Object.assign({},e.groupProfile)})),e=(s.setElement(t),s.isSystemMessage=!0,1===s.sequence&&1===s.random),t=2===s.sequence&&2===s.random;return(e||t)&&(s.sequence=r(),s.random=r(),s.generateMessageID()),s}_handleConversationOptions(e,t){var s=this._core["OuterConstant"],s={conversationID:s.CONV_SYSTEM,unreadCount:0,type:s.CONV_SYSTEM,subType:e.conversationSubType,lastMessage:null};return t&&s.unreadCount++,s}_handleGroupSysTemMessage(e,t){e&&t.forEach(e=>{var t=e.payload["operationType"];switch(t){case 2:this._handleGroupJoinResult(e);break;case 4:this._handleMemberKicked(e);break;case 5:this._handleGroupDismissed(e);break;case 7:this._handleGroupInvitedResult(e);break;case 8:this._handleGroupQuitResult(e);break;case 20:this._handleMessageRemindTypeSynced(e);break;case 21:this._handleAVChatRoomMemberBanned(e)}})}_handleGroupJoinResult(e){var e=e.payload["groupProfile"],{groupID:t,type:s}=e,r=R.hasLocalGroup(t);this._core.ssoLog.debug("_handleGroupJoinResult",` groupID:${t} type:${s} hasLocalGroup:`+r),r||Eo(s)||(R.updateLocalGroup([Object.assign({},e)]),R.emitGroupListUpdate())}_handleMemberKicked(e){var{groupID:e,type:t}=e.payload["groupProfile"];R.hasLocalGroup(e)&&this._deleteLocalGroup(e,t),this._updateConversationProfile(e,{unreadCount:0})}_handleGroupDismissed(e){var{groupID:e,type:t}=e.payload["groupProfile"];R.hasLocalGroup(e)&&this._deleteLocalGroup(e,t),this._updateConversationProfile(e,{unreadCount:0})}_handleGroupInvitedResult(e){var e=e.payload["groupProfile"],e=e["groupID"],t=R.hasLocalGroup(e);this._core.ssoLog.debug("_handleGroupInvitedResult",` groupID:${e} hasLocalGroup:`+t),t||Lo.getGroupProfile({groupID:e}).then(e=>{var e=e["data"]["group"];R.updateLocalGroup([Object.assign({},e)]),R.emitGroupListUpdate()})}_handleGroupQuitResult(e){var{groupID:e,type:t}=e.payload["groupProfile"],s=R.hasLocalGroup(e);this._core.ssoLog.debug("_handleGroupQuitResult",` groupID:${e} type:${t} hasLocalGroup:`+s),s&&this._deleteLocalGroup(e,t),this._updateConversationProfile(e,{unreadCount:0})}_handleMessageRemindTypeSynced(e){var{groupProfile:{groupID:e},messageRemindType:t}=e.payload;this._updateConversationProfile(e,{messageRemindType:t})}_handleAVChatRoomMemberBanned(e){var{groupID:e,type:t}=e.payload["groupProfile"];this._deleteLocalGroup(e,t)}_deleteLocalGroup(s,e){if(Eo(e)){let{appStore:{conversationStore:e},OuterConstant:{CONV_GROUP:t}}=this._core;e.deleteConversation(""+t+s)}R.deleteLocalGroup(s),R.emitGroupListUpdate()}_updateConversationProfile(e,t){var{appStore:{conversationStore:s},OuterConstant:{CONV_GROUP:r}}=this._core,r=""+r+e;s.getConversation(r)&&s.updateConversation(r,t)}},va=new class{init(e){(this._core=e).ssoLog.debug("GroupNotificationHandler.init"),pa.init(e),ma.init(e);var{notificationCenter:e,InnerEvent:t}=e,s=e["InnerEventSubType"];e.subscribeInnerEvent(t.MESSAGE_PUSH,s.GROUP_TIPS_NOTIFICATION,this._onNewGroupTipsNotification,this),e.subscribeInnerEvent(t.MESSAGE_PUSH,s.GROUP_SYSTEM_NOTIFICATION,this._onNewGroupSystemNotification,this),e.subscribeInnerEvent(t.DESTROY,this._dispose,this)}_onNewGroupTipsNotification(e){var{common:{workflowManager:t},constants:{WORKFLOW_NAME:s}}=this._core;t.executeWorkflow(s.RECEIVE_GROUP_TIPS_NOTIFICATION,e)}_onNewGroupSystemNotification(e){ma.onNewGroupSystemNotification(e)}_dispose(){var{notificationCenter:e,InnerEvent:t}=this._core,s=e["InnerEventSubType"];e.unSubscribeInnerEvent(t.MESSAGE_PUSH,s.GROUP_TIPS_NOTIFICATION,this._onNewGroupTipsNotification,this),e.unSubscribeInnerEvent(t.MESSAGE_PUSH,s.GROUP_SYSTEM_NOTIFICATION,this._onNewGroupSystemNotification,this)}};let N={required:!0,rules:["string"],allowEmpty:!1},fa={required:!0,rules:["number"],allowEmpty:!1},Ia={required:!0,rules:["array"],allowEmpty:!1},Ea={required:!0,rules:["object"],allowEmpty:!1},Sa={createGroup:{name:N,type:N},dismissGroup:[Object.assign({key:"groupID"},N)],joinGroup:{groupID:N,applyMessage:{required:!1,rules:["string"],allowEmpty:!0}},quitGroup:[Object.assign({key:"groupID"},N)],searchGroupByID:[Object.assign({key:"groupID"},N)],getGroupProfile:{groupID:N,groupCustomFieldFilter:{required:!1,rules:["array"],allowEmpty:!0}},updateGroupProfile:{groupID:N,muteAllMembers:{required:!1,rules:["boolean"],allowEmpty:!1}},changeGroupOwner:{groupID:N,newOwnerID:N},getGroupOnlineMemberCount:[Object.assign({key:"groupID"},N)],handleGroupApplication:{handleAction:N},getGroupMemberList:{groupID:N},getGroupMemberProfile:{groupID:N,userIDList:Ia,memberCustomFieldFilter:{required:!1,rules:["array"],allowEmpty:!0}},addGroupMember:{groupID:N,userIDList:Ia},deleteGroupMember:{groupID:N,userIDList:Ia},setGroupMemberMuteTime:{groupID:N,userID:N,muteTime:Object.assign(Object.assign({},fa),{customValidator:e=>!(e<0)||"muteTime must be a non-negative number."})},setGroupMemberRole:{groupID:N,userID:N,role:N},setGroupMemberNameCard:{groupID:N,userID:{required:!1,rules:["string"],allowEmpty:!1},nameCard:N},setGroupMemberCustomField:{groupID:N,userID:{required:!1,rules:["string"],allowEmpty:!1},memberCustomField:Ia},markGroupMemberList:{groupID:N,markType:Object.assign(Object.assign({},fa),{customValidator:e=>!(e<1e3)||"markType must be greater than or equal to 1000."}),enableMark:{required:!0,rules:["boolean"],allowEmpty:!1},userIDList:Ia},initGroupAttributes:{groupID:N,groupAttributes:Ea},setGroupAttributes:{groupID:N,groupAttributes:Ea},deleteGroupAttributes:{groupID:N,keyList:Object.assign(Object.assign({},Ia),{allowEmpty:!0})},getGroupAttributes:{groupID:N,keyList:Object.assign(Object.assign({},Ia),{allowEmpty:!0})},getGroupCounters:{groupID:N,keyList:{required:!1,rules:["array"],allowEmpty:!0}},setGroupCounters:{groupID:N,counters:Ea},increaseGroupCounter:{groupID:N,key:N,value:fa},decreaseGroupCounter:{groupID:N,key:N,value:fa}},Ca={getGroupList:!0,createGroup:!0,dismissGroup:!0,joinGroup:!0,quitGroup:!0,searchGroupByID:!0,getGroupProfile:!0,updateGroupProfile:!0,changeGroupOwner:!0,getGroupOnlineMemberCount:!0,getGroupApplicationList:!0,handleGroupApplication:!0,getGroupMemberList:!0,getGroupMemberProfile:!0,addGroupMember:!0,deleteGroupMember:!0,setGroupMemberMuteTime:!0,setGroupMemberRole:!0,setGroupMemberNameCard:!0,setGroupMemberCustomField:!0,markGroupMemberList:!0,initGroupAttributes:!0,setGroupAttributes:!0,getGroupAttributes:!0,deleteGroupAttributes:!0,getGroupCounters:!0,setGroupCounters:!0,increaseGroupCounter:!0,decreaseGroupCounter:!0},Ma=new class{constructor(){this._installedSubPlugins=[],this.groupDataHandler=R,this.groupAction=xo,this.groupAttribute=la,this.groupMember=ea,this.name="Group"}install(e,t=[]){this._core=e,io.init(e),R.init(e),xo.init(e,this),ea.init(e,this),jo.init(e),ra.init(e),la.init(e),va.init(e),e.helper.registerValidateConfig({auth:Ca,params:Sa}),this._installSubPlugins(t);var{notificationCenter:t,InnerEvent:e}=e;t.subscribeInnerEvent(e.LOGOUT,this._reset,this),t.subscribeInnerEvent(e.DESTROY,this._dispose,this)}getInstalledSubPlugins(){return this._installedSubPlugins}_installSubPlugins(e){var{isArray:t}=this._core["utils"];e&&t(e)&&e.forEach(e=>{var t;this._installedSubPlugins.includes(e.name)||(null!=(t=e.install)&&t.call(e,this._core,this),this._installedSubPlugins.push(e.name))})}_reset(){R.reset(),la.reset(),ra.reset()}_dispose(){this._reset();var{notificationCenter:e,InnerEvent:t}=this._core;e.unSubscribeInnerEvent(t.LOGOUT,this._reset,this),e.unSubscribeInnerEvent(t.DESTROY,this._dispose,this)}},ya=new class{init(e){this.core=e}},Oa={NORMAL_MESSAGE:3,GROUP_TIPS_HAS_ROAMING:4,GROUP_SYSTEM_MESSAGE:5,GROUP_TIPS_HAS_NO_ROAMING:6,BROADCAST_MESSAGE:17,MESSAGE_REVOKED:20,MESSAGE_REACTION:21,LIVE_CUSTOM_DATA:100},Aa={GROUP_DISMISSED:5,QUIT_GROUP:8,AVCHATROOM_MEMBER_BANNED:21};class Ta{constructor(e){var{core:e,manager:t,groupID:s,getRequestParams:r,onSuccess:i,onFail:n}=e;this._name="Polling",this._core=e,this._manager=t,this._timeoutID=-1,this._isRunning=!1,this._groupID=s,this._getRequestParams=r,this._onSuccess=i,this._onFail=n}start(){this._isRunning=!0,this._request(),console.log(this._name+".start pollingInterval:"+this._manager.getCurrentPollingInterval(this._groupID))}isRunning(){return this._isRunning}_request(){return I(this,void 0,void 0,function*(){try{var e=yield function(i,n){return I(this,void 0,void 0,function*(){var{longPollingKey:e,startSequence:t,startBroadcastSeq:s,simplifiedMessage:r}=i;return n.common.buildAndSendPacket({servcmd:"group_open_long_polling_http_svc.get_msg",data:{Key:e,StartSeq:t,StartBroadcastSeq:s,DownsizeFlag:r,USP:1,HoldTime:90}})})}(this._getRequestParams(this._groupID),this._core),t=(this._onSuccess(this._groupID,e),this._manager.getCurrentPollingInterval(this._groupID));this._runNextPolling(t)}catch(e){this._onFail(this._groupID,e),this._runNextPolling(2e3)}})}_runNextPolling(e){this.isRunning()&&(-1<this._timeoutID&&clearTimeout(this._timeoutID),this._timeoutID=setTimeout(this._request.bind(this),e))}stop(){console.log(this._name+".stop timerID:"+this._timeoutID),-1<this._timeoutID&&(clearTimeout(this._timeoutID),this._timeoutID=-1),this._isRunning=!1}}class Ra{constructor(e){this._maxLength=e,this._map=new Map}set(e){var t;if(this._map.size>=this._maxLength){let e=(null==(t=this._map.entries().next().value)?void 0:t[0])||"";this._map.delete(e)}this._map.set(e,1)}has(e){return this._map.has(e)}delete(e){this.has(e)&&this._map.delete(e)}clear(){this._map.clear()}}let Da=e=>e===Oa.GROUP_TIPS_HAS_NO_ROAMING||e===Oa.GROUP_TIPS_HAS_ROAMING,ba=e=>e===Oa.GROUP_SYSTEM_MESSAGE;function Na(g){var e,t,s,r,i,n,o,a=function(){var{E:e,MCT:t,MR:s,MP:r,MTS:i,GId:n,MS:o,CCD:a,F_Account:l,IsSys:u,GInf:c,MsgBody:d}=g,h=f(g,["E","MCT","MR","MP","MTS","GId","MS","CCD","F_Account","IsSys","GInf","MsgBody"]);return Object.assign({Event:e,MsgClientTime:t,MsgRandom:s,MsgPriority:r,MsgTimeStamp:i,ToGroupId:n,MsgSeq:o,CloudCustomData:a,From_Account:l,IsSystemMsg:u,GroupInfo:function(e){var e=e||{},{GN:t,GT:s,F_Hd:r,F_NN:i,F_Ll:n}=e,e=f(e,["GN","GT","F_Hd","F_NN","F_Ll"]),t=Object.assign({GroupName:t,GroupType:s},e);return r&&(t.From_AccountHeadurl=r),i&&(t.From_AccountNick=i),n&&(t.From_AccountLevel=n),t}(c),MsgBody:function(e){let t=e,s=(t=Array.isArray(e)?t:[e]).map(e=>{var{O_Account:t,Opt:s,L_Account:r,RT:i,UDF:n,OpInf:o,OnlineInf:a,MsgMemberExtraInfo:l}=e,e=f(e,["O_Account","Opt","L_Account","RT","UDF","OpInf","OnlineInf","MsgMemberExtraInfo"]),t=Object.assign({Operator_Account:t,OpType:s,List_Account:r,ReportType:i,UserDefinedField:n},e);return o&&(t.MsgOperatorMemberExtraInfo=function(){var{Img:e,NN:t}=o,s=f(o,["Img","NN"]);return Object.assign({ImageUrl:e,NickName:t},s)}()),l&&(t.MsgMemberExtraInfo=null==l?void 0:l.map(e=>{var{Img:t,NN:s}=e,e=f(e,["Img","NN"]);return Object.assign({ImageUrl:t,NickName:s},e)})),a&&(t.OnlineMemberInfo=function(){var{ET:e,Num:t}=a;return{ExpireTime:e,OnlineMemberNum:t}}()),t});return Array.isArray(e)?s:s[0]}(d)},h)}(),l=a,u=l["Event"];if((Da(u)||ba(u))&&(l.From_Account=l.From_Account||"@TIM#SYSTEM"),u===Oa.BROADCAST_MESSAGE||u===Oa.NORMAL_MESSAGE){var c=l;let e=ya["core"]["OuterConstant"];c.CloudCustomData=c.CloudCustomData||"",c.MsgBody=c.MsgBody.map(t=>{if(t.MsgType===e.MSG_CUSTOM){let{content:e={}}=t;t.content=Object.assign({Data:"",Desc:"",Ext:""},e)}return t})}return Da(u)&&({GroupJoinType:e,MsgOperatorMemberExtraInfo:t={},MsgMemberExtraInfo:s,Operator_Account:r,List_Account:i,OpType:n}=(c=l).MsgBody||{},"number"==typeof e||1!==n&&2!==n||(c.MsgBody.GroupJoinType=2===n?0:1),s||(c.MsgBody.MsgMemberExtraInfo=null==i?void 0:i.map(e=>({UserId:e}))),1!==n||s||(c.MsgBody.MsgMemberExtraInfo=[{UserId:t.UserId}]),c.MsgBody.MsgOperatorMemberExtraInfo=Object.assign({Operator_Account:r,ImageUrl:"",NickName:""},t)),ba(u)&&({MsgOperatorMemberExtraInfo:e={},Operator_Account:i}=(o=l).MsgBody||{},o.MsgBody.MsgMemberExtraInfo=Object.assign({UserId:i,ImageUrl:"",NickName:""},e),o.MsgBody=Object.assign({Authentication:"",RemarkInfo:"",MsgKey:1e3*o.MsgTimeStamp},o.MsgBody),o.MsgBody=Object.keys(o.MsgBody).filter(e=>"MsgOperatorMemberExtraInfo"!==e).reduce((e,t)=>Object.assign(Object.assign({},e),{[t]:o.MsgBody[t]}),{})),a}var La=new class{constructor(){this._name="MessageParser",this._sequenceList=new Ra(200),this._messageIDList=new Ra(100),this._broadcastMessageIDMap=new Map,this._reportMessageStackedCount=0}init(e,t){this._core=e,this._avChatRoomHandler=t}onMessageReceived(i,e,n=!1){this._sortServerMessageList({groupID:i,serverMessageList:e,isHistoryMessage:n});var o=this._handleMessageList(i,e);if(0!==o.length){if(!n){let{appStore:{conversationStore:e},OuterConstant:{CONV_GROUP:t}}=this._core,s=(e=>{var{common:{getMessagePreviewText:t}}=ya["core"];return{lastTime:(null==e?void 0:e.time)||(null==e?void 0:e.lastTime)||0,lastSequence:(null==e?void 0:e.sequence)||(null==e?void 0:e.lastSequence)||0,fromAccount:(null==e?void 0:e.from)||(null==e?void 0:e.fromAccount)||"",messageForShow:t(null==e?void 0:e.type,null==e?void 0:e.payload),payload:(null==e?void 0:e.payload)||null,type:(null==e?void 0:e.type)||"",isRevoked:(null==e?void 0:e.isRevoked)||!1,cloudCustomData:(null==e?void 0:e.cloudCustomData)||"",onlineOnlyFlag:(null==e?void 0:e._onlineOnlyFlag)||!1,nick:(null==e?void 0:e.nick)||"",nameCard:(null==e?void 0:e.nameCard)||"",version:(null==e?void 0:e.version)||0,isPeerRead:(null==e?void 0:e.isPeerRead)||!1,revoker:(null==e?void 0:e.revoker)||null}})(o[o.length-1]);e.updateConversation(""+t+i,{lastMessage:s})}this._checkMessageStacked(o);let e=o.filter(e=>!0===e.isModified),t=o.filter(e=>!1===e.isModified),{MESSAGE_RECEIVED:s,MESSAGE_MODIFIED:r}=this._core["OuterEvent"];0<e.length&&this._emitEvent({name:r,data:e}),0<t.length&&this._emitEvent({name:s,data:t})}}_sortServerMessageList(e){var{groupID:e,serverMessageList:t,isHistoryMessage:s}=e;let r=[];r=this._avChatRoomHandler.isPollingSimplifiedMessage()&&!s?(t.sort((e,t)=>e.MS-t.MS),t.map(e=>e.MS)):(t.sort((e,t)=>e.MsgSeq-t.MsgSeq),t.map(e=>e.MsgSeq)),console.log(`${this._name}._sortServerMessageList groupID:${e} count:${r.length} sequenceList:`+r),r.length=0}_handleMessageList(s,r){var i,n,{messageDataHandler:o,messageHelper:a}=this._core["message"],l=this._avChatRoomHandler.isPollingSimplifiedMessage(),u=[],e=r.length;for(let t=0;t<e;t++){let e=r[t];if(l&&(e=Na(e)),ba(e.Event)&&Object.values(Aa).includes(e.MsgBody.ReportType)){this._onGroupDismissed(s);break}null!==this._filterMessageItem(e)&&(this._patchMessageType(e),i=a.parseServerGroupMessage(e),(n=this._createMessage(i)).level=e.GroupInfo.From_AccountLevel,Da(e.Event)&&this._avChatRoomHandler.isGroupAttributesUpdated(i)?this._avChatRoomHandler.handleGroupAttributesUpdated(i):null===this._filterDuplicateMessage(n)||o.isMessageSentByCurrentInstance(n)||(1===i.isModified&&(n.isModified=!0),Da(e.Event)&&this._updateLocalOnlineMemberCountFromTips(e),u.push(n)))}return u}_patchMessageType(e){var t=this._core["OuterConstant"];Da(e.Event)&&(e.MsgBody.MsgType=t.MSG_GRP_TIP),ba(e.Event)&&(e.MsgBody.MsgType=t.MSG_GRP_SYS_NOTICE)}_filterMessageItem(e){var t=e["Event"];return Object.values(Oa).includes(t)?t===Oa.MESSAGE_REVOKED?(this._handleMessageRevoked(e),null):t===Oa.LIVE_CUSTOM_DATA?(this._onLiveCustomData(e),null):t===Oa.MESSAGE_REACTION?null:e:(console.warn(this._name+".onMessageReceived unknown event:"+t),null)}_createMessage(e){var{message:{messageFactory:t},OuterConstant:s}=this._core;let r=s.CONV_GROUP;e.event===Oa.GROUP_SYSTEM_MESSAGE&&(r=s.CONV_SYSTEM);s=!!e.isSystemMessage,t=t.createMessage(Object.assign(Object.assign({},e),{conversationType:r,isSystemMessage:s,flow:"in"}));return t.setElement(e.elements),t}_filterDuplicateMessage(e){var t=this._core["common"];if(!t.isUnlimitedAVChatRoom()){if(this._sequenceList.has(e.sequence))return null;this._sequenceList.set(e.sequence)}t=this._messageIDList.has(e.ID);return t?(console.warn(`${this._name}_filterDuplicateMessageItem ID:${e.ID} has:`+t),null):(this._messageIDList.set(e.ID),e)}_handleMessageRevoked(e){let{OuterConstant:i,OuterEvent:{MESSAGE_REVOKED:t}}=this._core,{ToGroupId:n,MsgBody:{RevokeMsgList:s},RevokerInfo:{Revoker_Account:o,Reason:a=""}}=e,l=[];s.forEach(e=>{var{TinyId:e,MsgClientTime:t,Random:s,MsgSeq:r}=e,e={conversationID:""+i.CONV_GROUP+n,ID:e+`-${t}-`+s,revoker:o,revokeReason:a,revokerInfo:{userID:o,nick:"",avatar:""},sequence:r};l.push(e)}),0!==l.length&&this._emitEvent({name:t,data:l})}_onLiveCustomData(e){var t=this._core["OuterEvent"]["ROOM_CUSTOM_DATA_RECEIVED"],{ToGroupId:e,MsgSeq:s,MsgTimeStamp:r,MsgBody:i}=e,i=(null==i?void 0:i.Content)||(null==i?void 0:i.MsgContent)||"";this._emitEvent({name:t,data:i}),console.log(this._name+`._onLiveCustomData groupID:${e} sequence:${s} time:${r} data:`+i)}_onGroupDismissed(e){this._avChatRoomHandler.reset(e)}_checkMessageStacked(e){var t=e["length"];if(100<=t&&this._reportMessageStackedCount<5){let e=this._avChatRoomHandler.getJoinedGroups();this._core.ssoLog.info("MessageStacked",`count:${t} groupID:`+e.join(",")),this._reportMessageStackedCount+=1}}_emitEvent(e){this._core.notificationCenter.emitOuterEvent(e.name,e)}onBroadcastMessageReceived(s){var{message:{messageHelper:r},OuterEvent:{MESSAGE_RECEIVED:e}}=this._core,i=this._avChatRoomHandler.isPollingSimplifiedMessage(),n=[],o=s.length;for(let t=0;t<o;t++){let e=s[t];i&&(e=Na(e));var a=r.parseServerGroupMessage(e);Object.values(Oa).includes(e.Event)?((a=this._createMessage(a)).isBroadcastMessage=!0,this._broadcastMessageIDMap.has(a.ID)||(n.push(a),this._broadcastMessageIDMap.set(a.ID,1))):console.warn(this._name+".onBroadcastMessageReceived unknown event:"+e.Event)}0<n.length&&this._emitEvent({name:e,data:n})}_updateLocalOnlineMemberCountFromTips(t){var s=this._core["utils"]["isEmpty"],{ToGroupId:t,MsgBody:{OnlineMemberInfo:r}}=t;if(!s(r)){var{OnlineMemberNum:r=0,ExpireTime:i=60}=r,n=Date.now();let e=this._avChatRoomHandler.getLocalOnlineMemberCount(t);s(e)?e={lastReqTime:0,lastSyncTime:0,latestUpdateTime:n,memberCount:r,expireTime:i}:(e.latestUpdateTime=n,e.memberCount=r),this._avChatRoomHandler.updateLocalOnlineMemberCount(t,e)}}reset(){this._reportMessageStackedCount=0,this._sequenceList.clear(),this._messageIDList.clear(),this._broadcastMessageIDMap.clear()}};let Pa=e=>{var{store:t}=ya["core"];return(t.get("cloudConfig")||{})[e]},Ga=e=>{var{utils:{isUndefined:t}}=ya["core"];return!t(e)},wa=()=>{var e=Pa("polling_interval");return Ga(e)?parseInt(e,10):300},Ua=()=>{var e=Pa("polling_simplified_msg");return Ga(e)?parseInt(e,10):0};var ka,Fa=new class{constructor(){this._name="AVChatRoomHandler",this._joinedGroupMap=new Map,this._pollingRequestInfoMap=new Map,this._pollingInstanceMap=new Map,this._onlineMemberCountMap=new Map,this._pollingIntervalMap=new Map,this._pollingNoMessageCountMap=new Map,this._membersReqInfoMap=new Map,this._startBroadcastSequence=1}init(e,t){this._core=e,this._parentPlugin=t,La.init(e,this),e.ssoLog.debug("AVChatRoomHandler.init")}onAVChatRoomSystemNotification(e){var t=this._core["OuterConstant"]["GRP_AVCHATROOM"],{GroupTips:s=[]}=e;for(let e=0;e<s.length;e++){var{MsgBody:r,GroupInfo:{GroupId:i,GroupType:n}}=s[e],r=Object.values(Aa).includes(r.ReportType);n===t&&r&&this.reset(i)}}getCurrentPollingInterval(e){return this._pollingIntervalMap.get(e)||wa()}isPollingSimplifiedMessage(){return 0!==Ua()}isGroupAttributesUpdated(e){return!!this._parentPlugin.groupAttribute.isGroupAttributesUpdated(e)&&(this._parentPlugin.groupAttribute.handleGroupAttributesUpdated(e),!0)}updateLocalOnlineMemberCount(e,t){this._onlineMemberCountMap.set(e,t)}getLocalOnlineMemberCount(e){return this._onlineMemberCountMap.get(e)||{}}hasPollingInstance(e){return this._pollingInstanceMap.has(e)}getJoinedLiveList(){let{GRP_LIVE:t}=this._core["OuterConstant"],e=[];return e=0<this._joinedGroupMap.size?[...this._joinedGroupMap.values()].filter(e=>e.type===t):e}handleJoinGroupResult(l){return I(this,void 0,void 0,function*(){var{utils:{isUndefined:e},OuterConstant:{CONV_GROUP:t},apiMap:{getConversationProfile:s},OuterConstant:r}=this._core,{longPollingKey:i,group:n,historyMessageList:o=[]}=l,a=n["groupID"];return yield this._preCheck(n),this._joinedGroupMap.set(a,n),this._parentPlugin.groupDataHandler.updateLocalGroup([n]),this._parentPlugin.groupDataHandler.emitGroupListUpdate(),s(""+t+a),0<o.length&&La.onMessageReceived(a,o,!0),e(i)?{code:0,data:{status:r.JOIN_STATUS_SUCCESS,group:n}}:{code:0,data:this.startMessageLongPolling(l)}})}_preCheck(n){return I(this,void 0,void 0,function*(){var{common:t,OuterConstant:e,helper:s,apiMap:{quitGroup:r},ssoLog:i}=this._core;if(t.isUnlimitedAVChatRoom()){if(this._pollingInstanceMap.size>(t=Pa("polling_count_limit"),Ga(t)&&0<t?parseInt(t,10):20))throw new s.ChatError({code:2688,message:"the count of longPolling exceeds the max limit"})}else if(0!==this._joinedAVChatRoomCount()&&n.type!==e.GRP_LIVE){var[t,s]=this._joinedGroupMap.entries().next().value;if(s.selfInfo.role===e.GRP_MBR_ROLE_OWNER)this._parentPlugin.groupDataHandler.deleteLocalGroup(t);else try{yield r(t)}catch(e){i.debug("quitGroup",this._name+`._preCheck quitGroup failed, groupID:${t} info:`,e)}this.reset(t)}})}startMessageLongPolling(e){var t=this._core["OuterConstant"],{longPollingKey:e,startSequence:s=1,group:r}=e,i=r["groupID"];return this._pollingRequestInfoMap.set(i,{longPollingKey:e,startSequence:s}),this._pollingIntervalMap.set(i,wa()),this._startPolling(i),this._reportLongPollingCount(),{status:t.JOIN_STATUS_SUCCESS,group:r}}_startPolling(t){if(this._core.ssoLog.debug("_startPolling",this._name+"._startPolling groupID:"+t),this._pollingInstanceMap.has(t)){let e=this._pollingInstanceMap.get(t);void((null==e?void 0:e.isRunning())||null==e||e.start())}else{let e=new Ta({core:this._core,manager:this,groupID:t,getRequestParams:this._handleRequestParams.bind(this),onSuccess:this._handleSuccess.bind(this),onFail:this._handleFailure.bind(this)});e.start(),this._pollingInstanceMap.set(t,e)}}_handleRequestParams(e){var{longPollingKey:t,startSequence:s}=this._pollingRequestInfoMap.get(e)||{};return e===[...this._pollingInstanceMap.keys()][0]?{longPollingKey:t,startSequence:s,startBroadcastSeq:this._startBroadcastSequence,simplifiedMessage:Ua()}:{longPollingKey:t,startSequence:s,simplifiedMessage:Ua()}}_handleSuccess(s,e){var r=e["ErrorCode"];if(0!==r){let{longPollingKey:e,startSequence:t}=this._pollingRequestInfoMap.get(s)||{};void console.warn(`${this._name}._handleSuccess groupID:${s} key:${e} startSeq:${t} errorCode:`+r)}else this._hasJoinedAVChatRoom(s)&&this._handleResponseData(s,e)}_handleResponseData(t,e){var{Key:e,NextSeq:s,NextBroadcastSeq:r,RspMsgList:i=[],RspBroadcastMsgList:n=[]}=e;if(e&&s&&this._pollingRequestInfoMap.set(t,{longPollingKey:e,startSequence:s}),r&&r>this._startBroadcastSequence&&(this._startBroadcastSequence=r),0<i.length)0!==this._getPollingNoMessageCount(t)&&(this._updatePollingNoMessageCount(t,0),this._pollingIntervalMap.set(t,wa())),La.onMessageReceived(t,i);else{e=this._getPollingNoMessageCount(t);if(this._updatePollingNoMessageCount(t,e+=1),e===(s=Pa("polling_no_msg_count"),Ga(s)?parseInt(s,10):20)){let e=wa()+(r=Pa("polling_interval_plus"),Ga(r)?parseInt(r,10):2e3);this._pollingIntervalMap.set(t,e)}}0<n.length&&La.onBroadcastMessageReceived(n)}_handleFailure(e,t){var{ssoLog:s,utils:{safeStringify:r}}=this._core;s.warn("polling",this._name+`._handleFailure groupID:${e} error: `+r(t))}_joinedAVChatRoomCount(){let t=this._core["OuterConstant"],e=[];return(e=0<this._joinedGroupMap.size?this.getJoinedGroups().filter(e=>e.type===t.GRP_AVCHATROOM):e).length}_hasJoinedAVChatRoom(e){return this._joinedGroupMap.has(e)}getJoinedGroups(){return[...this._joinedGroupMap.values()]}updateLocalLiveGroup(e,t){this._joinedGroupMap.set(e,t),this._parentPlugin.groupDataHandler.updateLocalGroup([t])}handleLiveHistoryMessages(e,t){La.onMessageReceived(e,t,!0)}isOverFrequencyLimit(e){var t,s,r,i;return!this._membersReqInfoMap.has(e)||({startTime:t,requestCount:s}=this._membersReqInfoMap.get(e),{interval:r,count:i}=(()=>{var e=Pa("av_members_freq_limit");if(Ga(e)){var{interval:e,count:t}=JSON.parse(e);if(0<t&&0<e)return{interval:e,count:t}}return{interval:30,count:4}})(),Date.now()-t>1e3*r)?(this._membersReqInfoMap.set(e,{startTime:Date.now(),requestCount:1}),!1):(this._membersReqInfoMap.set(e,{startTime:t,requestCount:s+=1}),i<s)}_stopPolling(e){var t,s;if(this._core.ssoLog.debug("_stopPolling",this._name+"._stopPolling groupID:"+e),e)({appStore:{conversationStore:s},OuterConstant:{CONV_GROUP:t}}=this._core),s.deleteConversation(""+t+e),null!=(s=this._pollingInstanceMap.get(e))&&s.stop(),this._parentPlugin.groupDataHandler.deleteLocalGroup(e),this._pollingInstanceMap.delete(e),this._pollingRequestInfoMap.delete(e),this._joinedGroupMap.delete(e),this._onlineMemberCountMap.delete(e),this._pollingIntervalMap.delete(e),this._pollingNoMessageCountMap.delete(e),this._membersReqInfoMap.delete(e);else{for(let e of this._pollingInstanceMap.values())null!=e&&e.stop();this._pollingInstanceMap.clear(),this._pollingRequestInfoMap.clear(),this._joinedGroupMap.clear(),this._onlineMemberCountMap.clear(),this._pollingIntervalMap.clear(),this._pollingNoMessageCountMap.clear(),this._membersReqInfoMap.clear()}}_updatePollingNoMessageCount(e,t){this._pollingNoMessageCountMap.set(e,t)}_getPollingNoMessageCount(e){return this._pollingNoMessageCountMap.get(e)||0}_reportLongPollingCount(){var o=this._joinedGroupMap.size;if(1<o){let{common:e,OuterConstant:s,ssoLog:t}=this._core,r=e.isUnlimitedAVChatRoom()?1:0,i=[],n=[];this._joinedGroupMap.values().forEach(({groupID:e,type:t})=>{(t===s.GRP_LIVE?n:i).push(e)}),t.info("longPollingCount",String(o),{moreMessage:`av:${i.join(",")} live:${n.join(",")} code: `+r,eventType:29})}}reset(e){this._stopPolling(e),this._startBroadcastSequence=1,La.reset()}},qa=new class{init(e,t){this._core=e,this._parentPlugin=t;e=e.helper;e.registerApi({apiName:"joinGroup",context:this,matcher:()=>0<t.getInstalledSubPlugins().length})}joinGroup(i){return I(this,void 0,void 0,function*(){var e=this._core["OuterConstant"],t=yield this._parentPlugin.groupAction.joinGroup(i),{status:s,group:{type:r}}=t["data"];return r!==e.GRP_AVCHATROOM||s===e.JOIN_STATUS_ALREADY_IN_GROUP?t:Fa.handleJoinGroupResult(t.data)})}},xa=new class{init(e,t){this._core=e,this._parentPlugin=t;e=e.helper;e.registerApi({apiName:"quitGroup",context:this,matcher:()=>0<t.getInstalledSubPlugins().length})}quitGroup(r){return I(this,void 0,void 0,function*(){var e=this._core["OuterConstant"],t=yield this._parentPlugin.groupAction.quitGroup(r),{type:s}=t["data"];return s===e.GRP_AVCHATROOM&&Fa.reset(r),t})}},Va=new class{init(e,t){this._core=e,this._parentPlugin=t;e=e.helper;e.registerApi({apiName:"dismissGroup",context:this,matcher:()=>0<t.getInstalledSubPlugins().length})}dismissGroup(r){return I(this,void 0,void 0,function*(){var e=this._core["OuterConstant"],t=yield this._parentPlugin.groupAction.dismissGroup(r),{type:s}=t["data"];return s===e.GRP_AVCHATROOM&&Fa.reset(r),t})}},Ba=new class{constructor(){this._name="GetAVChatRoomMemberList"}init(e,t){this._core=e,this._parentPlugin=t;e=e.helper;e.registerApi({apiName:"getGroupMemberList",context:this,matcher:()=>0<t.getInstalledSubPlugins().length})}getGroupMemberList(i){return I(this,void 0,void 0,function*(){var{appStore:{groupStore:e},helper:t,OuterConstant:s}=this._core,r=i["groupID"],e=e.getGroup(r);if((null==e?void 0:e.type)===s.GRP_AVCHATROOM&&t.checkBusinessCapabilityBits("AV_MBR_LIST")){if(Fa.isOverFrequencyLimit(r))throw{code:2996,message:"Over frequency limit: get_members-"+r};return this._getGroupMemberList(i)}return this._parentPlugin.groupMember.getGroupMemberList(i)})}_getGroupMemberList(n){return I(this,void 0,void 0,function*(){let i="_getGroupMemberList",t=this._core["helper"];try{let e=yield function(s,r){return I(this,void 0,void 0,function*(){var{groupID:e,offset:t=0}=s;return r.common.buildAndSendPacket({servcmd:"group_open_avchatroom_http_svc.get_members",data:{GroupId:e,Timestamp:t}})})}(n,this._core),{MemberList:t=[],NextTimestamp:s=0}=e||{},r=this._handleMemberList(t);return console.log(`${this._name}.${i} ok, groupID:${n.groupID} count:${r.length} nextOffset:`+s),{code:0,data:{memberList:r,offset:s}}}catch(e){var s=new t.ChatError({functionName:i,code:null==e?void 0:e.errorCode,message:null==e?void 0:e.errorInfo});throw console.error(this._name+`.${i} fail:`,s),s}})}_handleMemberList(e){return e.map(e=>{var{Member_Account:e,NickName:t="",Avatar:s="",Remark:r="",JoinTime:i=0,Marks:n=[]}=e;return{userID:e,nick:t,avatar:s,remark:r,joinTime:i,marks:n,isOnline:!0}})}},ja=new class{constructor(){this._name="GetAVChatRoomOnlineMemberCount"}init(e,t){this._core=e,this._parentPlugin=t;e=e.helper;e.registerApi({apiName:"getGroupOnlineMemberCount",context:this,matcher:()=>0<t.getInstalledSubPlugins().length})}getGroupOnlineMemberCount(s){return I(this,void 0,void 0,function*(){var{appStore:{groupStore:e},OuterConstant:t}=this._core,e=e.getGroup(s);return e?e.type===t.GRP_AVCHATROOM?this._getOnlineMemberCount(s):this._parentPlugin.groupAction.getGroupOnlineMemberCount(s):{code:0,data:{memberCount:0}}})}_getOnlineMemberCount(r){return I(this,void 0,void 0,function*(){let t="_getOnlineMemberCount",{isEmpty:e}=this._core["utils"],s=Fa.getLocalOnlineMemberCount(r);if(e(s)||this._isExpired(r)){let{memberCount:e=0}=yield this._getOnlineMemberCountFromServer(r);return console.log(`${this._name}.${t} ok, groupID:${r} memberCount:${e} from server.`),{code:0,data:{memberCount:e}}}return console.log(`${this._name}.${t} ok, groupID:${r} memberCount:${s.memberCount} from local.`),{code:0,data:{memberCount:s.memberCount}}})}_isExpired(e){var e=Fa.getLocalOnlineMemberCount(e),t=Date.now(),s=t-e.lastSyncTime>1e3*e.expireTime,r=1e4<t-e.latestUpdateTime,t=3e3<t-e.lastReqTime;return s&&r&&t}_getOnlineMemberCountFromServer(n){return I(this,void 0,void 0,function*(){let t="_getOnlineMemberCountFromServer";try{let e=yield function(e,t){return I(this,void 0,void 0,function*(){return t.common.buildAndSendPacket({servcmd:"group_open_http_svc.get_online_member_num",data:{GroupId:e}})})}(n,this._core),{OnlineMemberNum:t=0,ExpireTime:s=60}=e||{},r=Date.now(),i={lastSyncTime:r,latestUpdateTime:r,lastReqTime:r,memberCount:t,expireTime:s};return Fa.updateLocalOnlineMemberCount(n,i),{memberCount:t}}catch(e){var s=new this._core.helper.ChatError({functionName:t,code:null==e?void 0:e.errorCode,message:null==e?void 0:e.errorInfo});throw console.error(`${this._name}.${t} fail:`,s),s}})}},Ka=new class{constructor(){this._name="DeleteAVChatRoomMember"}init(e,t){this._core=e,this._parentPlugin=t;e=e.helper;e.registerApi({apiName:"deleteGroupMember",context:this,matcher:()=>0<t.getInstalledSubPlugins().length})}deleteGroupMember(o){return I(this,void 0,void 0,function*(){var e="deleteGroupMember",{appStore:{groupStore:t},utils:{isUndefined:s},helper:r,OuterConstant:i}=this._core,n=o["groupID"],t=t.getGroup(n);if(s(t))throw new r.ChatError({functionName:e,code:2603});if(t.type!==i.GRP_AVCHATROOM)return this._parentPlugin.groupMember.deleteGroupMember(o);if(r.checkBusinessCapabilityBits("AV_BAN_MBR"))return this._deleteGroupMember(o);throw new r.ChatError({functionName:e,code:3122})})}_deleteGroupMember(a){return I(this,void 0,void 0,function*(){var t="_deleteGroupMember",{appStore:{groupStore:e},helper:s,ssoLog:r}=this._core,{groupID:i,duration:n=0,userIDList:o}=a;if(0===n)throw new s.ChatError({functionName:t,code:2686});try{return yield function(i,n){return I(this,void 0,void 0,function*(){var{groupID:e,userIDList:t,duration:s,reason:r}=i;return n.common.buildAndSendPacket({servcmd:"group_open_http_svc.ban_group_member",data:{GroupId:e,Members_Account:t,Duration:s,Description:r}})})}(a,this._core),r.debug(t,this._name+`.${t} ok, groupID:`+i),{code:0,data:{group:e.getGroup(i),userIDList:o}}}catch(e){throw new s.ChatError({functionName:t,code:null==e?void 0:e.errorCode,message:null==e?void 0:e.errorInfo})}})}},Ha=new class{constructor(){this._name="MarkAVChatRoomMember"}init(e){e=(this._core=e).helper;e.registerApi({apiName:"markGroupMemberList",context:this})}markGroupMemberList(e){return I(this,void 0,void 0,function*(){var i="markGroupMemberList",{groupID:n,markType:o,enableMark:a,userIDList:l=[]}=e,u=this._generateRequestData(e);try{let e=yield function(r,i){return I(this,void 0,void 0,function*(){var{groupID:e,operationType:t,memberList:s}=r;return i.common.buildAndSendPacket({servcmd:"group_open_avchatroom_http_svc.modify_user_info",data:{GroupId:e,CommandType:t,MemberList:s}})})}(u,this._core),{MemberList:t=[]}=e||{},{successUserIDList:s,failureUserIDList:r}=this._handleResult(t,l);return{code:0,data:{successUserIDList:s,failureUserIDList:r},successLog:{message:`${this._name}.${i} ok, groupID:${n} markType:${o} enableMark:${a} success:${s.length} fail:`+r.length}}}catch(e){throw new this._core.helper.ChatError({functionName:i,code:null==e?void 0:e.errorCode,message:null==e?void 0:e.errorInfo})}})}_generateRequestData(e){let{groupID:t,markType:s,enableMark:r,userIDList:i=[]}=e,n=!0===r?1:2,o=[...i];return 500<o.length&&console.warn(this._name+"._generateRequestData, the length of userIDList cannot exceed 500"),{groupID:t,operationType:n,memberList:o.map(e=>({Member_Account:e,Marks:[s]}))}}_handleResult(e,t){let s=[],r=[];return e.length===t.length?s.push(...t):t.forEach(t=>{(e.find(e=>e.Member_Account===t)?s:r).push(t)}),{successUserIDList:s,failureUserIDList:r}}},Wa=new class{init(e,t){e.ssoLog.debug("AVChatRoomAction.init"),qa.init(e,t),xa.init(e,t),Va.init(e,t),Ba.init(e,t),ja.init(e,t),Ka.init(e,t),Ha.init(e)}},Ya=new class{constructor(){this._name="LiveHandler"}init(e){var{helper:e,ssoLog:t}=this._core=e;e.registerExperimentalAPI("startMessageLongPolling",this),e.registerExperimentalAPI("stopMessageLongPolling",this),t.debug("LiveHandler.init")}startMessageLongPolling(e){var{common:t,utils:{isEmpty:s},OuterConstant:r,ssoLog:i}=this._core,{groupID:e,longPollingKey:n,longPollingSequence:o=1}=e;if(s(n))return i.warn("startMessageLongPolling",this._name+".startMessageLongPolling longPollingKey is empty."),Promise.resolve({});Fa.hasPollingInstance(e)&&this.stopMessageLongPolling({groupID:e});s=Fa.getJoinedLiveList(),t=t.isUnlimitedAVChatRoom(),!t&&0<s.length&&this.stopMessageLongPolling({groupID:s[0].groupID}),i.debug("startMessageLongPolling",this._name+`.startMessageLongPolling isUnlimited:${t} groupID:${e} longPollingKey:${n} longPollingSequence:`+o),s={groupID:e,type:r.GRP_LIVE};return Fa.updateLocalLiveGroup(e,s),this._getLiveHistoryMessages({groupID:e,longPollingKey:n,startSequence:o}),Fa.startMessageLongPolling({group:s,longPollingKey:n,startSequence:o})}stopMessageLongPolling(e){e=e.groupID;return Fa.reset(e),this._core.ssoLog.debug("stopMessageLongPolling",this._name+".stopMessageLongPolling ok, groupID:"+e),Promise.resolve({groupID:e})}_getLiveHistoryMessages(i){return I(this,void 0,void 0,function*(){var t=this._core["ssoLog"],s=i["groupID"];try{var e=yield function(r,i){return I(this,void 0,void 0,function*(){var{groupID:e,longPollingKey:t,startSequence:s}=r;return i.common.buildAndSendPacket({servcmd:"group_open_http_svc.get_huge_group_msg",data:{GroupId:e,LongPollingKey:t,PullPreSeq:s}})})}(i,this._core),{RspMsgList:r=[]}=e||{};t.debug("_getLiveHistoryMessages",this._name+`._getLiveHistoryMessages ok, groupID:${s} count:`+r.length),0<r.length&&Fa.handleLiveHistoryMessages(s,r)}catch(e){t.debug("_getLiveHistoryMessages",this._name+`._getLiveHistoryMessages failed, groupID:${s} info:`+e.message)}})}},n=new class{constructor(){this.name="AVChatRoom"}install(e,t){this._core=e,ya.init(e),Fa.init(e,t),Wa.init(e,t),Ya.init(e);var{notificationCenter:t,InnerEvent:e}=e,s=t["InnerEventSubType"];t.subscribeInnerEvent(e.MESSAGE_PUSH,s.GROUP_SYSTEM_NOTIFICATION,this._onAVChatRoomSystemNotification,this),t.subscribeInnerEvent(e.LOGOUT,this._reset,this),t.subscribeInnerEvent(e.DESTROY,this._dispose,this)}_onAVChatRoomSystemNotification(e){Fa.onAVChatRoomSystemNotification(e)}_reset(){Fa.reset()}_dispose(){this._reset();var{notificationCenter:e,InnerEvent:t}=this._core,s=e["InnerEventSubType"];e.unSubscribeInnerEvent(t.MESSAGE_PUSH,s.GROUP_SYSTEM_NOTIFICATION,this._onAVChatRoomSystemNotification,this),e.unSubscribeInnerEvent(t.LOGOUT,this._reset,this),e.unSubscribeInnerEvent(t.DESTROY,this._dispose,this)}};let $a=new class{init(e){this.core=e}},za="message",Ja="user",Qa={OR:"or",AND:"and"},Xa={required:!1,rules:["array"],allowEmpty:!0,customValidator:e=>!e||!!(Array.isArray(e)&&e.length<=5)||"keywordList should be an array and length <= 5"},Za={required:!1,rules:["string"],allowEmpty:!0,customValidator:e=>!e||!![Qa.OR,Qa.AND].includes(e)||"keywordListMatchType should be OR or AND"},el={required:!1,rules:["number"],allowEmpty:!0,customValidator:e=>"number"==typeof e&&1<=e&&e<=100||"count must be a number between 1 and 100"},tl={required:!1,rules:["string"],allowEmpty:!0},sl={required:!1,rules:["array"],allowEmpty:!0,customValidator:t=>{var e=$a.core["OuterConstant"];if(!Array.isArray(t))return"groupTypeList should be an array";var s=[e.GRP_PUBLIC,e.GRP_COMMUNITY,e.GRP_WORK,e.GRP_MEETING];let r=!1;for(let e=0;e<t.length;e++)if(-1===s.indexOf(t[e])){r=!0;break}return!r||"groupTypeList should be supported group type"}},rl={required:!1,rules:["array"],allowEmpty:!0,customValidator:t=>{var e=$a.core["OuterConstant"],s=[e.MSG_TEXT,e.MSG_IMAGE,e.MSG_AUDIO,e.MSG_FILE,e.MSG_VIDEO,e.MSG_LOCATION,e.MSG_CUSTOM,e.MSG_MERGER];let r=!1;for(let e=0;e<t.length;e++)if(-1===s.indexOf(t[e])){r=!0;break}return!r||"messageTypeList should be supported message type"}},il={required:!1,rules:["string"],allowEmpty:!0,customValidator:e=>{var t=$a.core["OuterConstant"];return!!(null!=e&&e.startsWith(t.CONV_C2C)||null!=e&&e.startsWith(t.CONV_GROUP)||e===t.CONV_SYSTEM)||"conversationID is invalid"}},nl=t=>({required:!1,rules:["number"],allowEmpty:!0,customValidator:e=>"number"==typeof e&&0<=e||t+" should be a number >= 0';"}),ol={required:!1,rules:["string"],allowEmpty:!0,customValidator:e=>{var t=$a.core["OuterConstant"];return!![t.GENDER_FEMALE,t.GENDER_MALE].includes(e)||"gender is invalid"}},al={searchCloudMessages:{keywordList:Xa,keywordListMatchType:Za,cursor:tl,senderUserIDList:{required:!1,rules:["array"],allowEmpty:!0,customValidator:e=>!!(Array.isArray(e)&&e.length<=5)||"senderUserIDList should be an array and length <= 5"},messageTypeList:rl,conversationID:il,timePosition:nl("timePosition"),timePeriod:nl("timePeriod")},searchCloudUsers:{keywordList:Xa,keywordListMatchType:Za,cursor:tl,count:el,miniBirthday:nl("miniBirthday"),maxBirthday:nl("maxBirthday"),gender:ol},searchCloudGroupMembers:{keywordList:Xa,keywordListMatchType:Za,cursor:tl,count:el,groupTypeList:sl,groupIDList:{required:!1,rules:["array"],allowEmpty:!0}},searchCloudGroups:{keywordList:Xa,keywordListMatchType:Za,cursor:tl,count:el,groupTypeList:sl}},ll={searchCloudMessages:!0,searchCloudUsers:!0,searchCloudGroupMembers:!0,searchCloudGroups:!0},ul=new class{constructor(){this.name="CloudSearch"}install(e){this._core=e,$a.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:ll,params:al})}searchCloudMessages(p){return I(this,void 0,void 0,function*(){try{let{OuterConstant:o,helper:a}=this._core,{conversationID:e,timePeriod:t,timePosition:s}=p,r=f(p,["conversationID","timePeriod","timePosition"]),i=Object.assign({count:100},r);e&&(e.startsWith(o.CONV_C2C)?i.account=e.replace(o.CONV_C2C,""):e.startsWith(o.CONV_GROUP)&&(i.groupID=e.replace(o.CONV_GROUP,""))),this._setTimeRangeParams(i,{timePeriod:t,timePosition:s});var n=yield function(c){return I(this,void 0,void 0,function*(){var{count:e,keywordList:t,keywordListMatchType:s,senderUserIDList:r,messageTypeList:i,endTime:n,startTime:o,cursor:a,account:l,groupID:u}=c,e={Count:e,KeywordList:t,MatchType:s,SendUserIDList:r,MsgTypeList:i,EndTime:n,StartTime:o,Cursor:a,PeerAccount:l,GroupID:u};return $a.core.common.buildAndSendPacket({servcmd:"message_search.query",data:e})})}(i);if(!n)return{code:0,data:{}};var{ErrorCode:l,ErrorInfo:u,TotalCount:c,Cursor:d="",ConversationMsgs:h=[]}=n;if(0!==l)throw{errorCode:l,errorInfo:u};var g=`keywordList:${p.keywordList} keywordListMatchType:${p.keywordListMatchType} cursor:${p.cursor} res: totalCount:`+c;return{code:0,data:{searchResultList:h.map(e=>{let{MsgList:t,Count:s,GroupID:i,UserID:r}=e,n=i?""+o.CONV_GROUP+i:""+o.CONV_C2C+r;return this._isSearchingAllConversations(p)&&1<s?{conversationID:n,messageCount:s,messageList:[]}:{conversationID:n,messageCount:s,messageList:t.map(e=>{return a.isEmpty(i)?(t=this._core,s=t.OuterConstant.CONV_C2C,r=t.message.messageHelper.parseServerPushMessage(e),(t=t.message.messageFactory.createMessage(Object.assign(Object.assign({},r),{conversationType:s,flow:"in"}))).setElement(r.elements),t):(s=this._core,r=s.OuterConstant.CONV_GROUP,t=s.message.messageHelper.parseServerGroupMessage(e),(s=s.message.messageFactory.createMessage(Object.assign(Object.assign({},t),{conversationType:r,flow:"in"}))).setElement(t.elements),s);var t,s,r})}}),cursor:d,totalCount:c},successLog:{message:g}}}catch(e){var{errorCode:n,errorInfo:l}=e||{};this._handleError({errorCode:n,errorInfo:l,searchType:za,functionName:"searchCloudMessages"})}})}searchCloudUsers(v){return I(this,void 0,void 0,function*(){var s;try{var{keywordListMatchType:e,count:t=20}=v,r=f(v,["keywordListMatchType","count"]),i=Object.assign({count:t,keywordListMatchType:e===Qa.AND?1:0},r),n=(this._setBirthdayRangeParams(i,v),yield function(a){return I(this,void 0,void 0,function*(){var{count:e,keywordList:t,keywordListMatchType:s,miniBirthday:r,maxBirthday:i,cursor:n,gender:o}=a,e={Count:e,Keywords:t,KeywordMatchType:s,Cursor:n,UserBirthStart:r,UserBirthEnd:i,Gender:o};return $a.core.common.buildAndSendPacket({servcmd:"user_search.query",data:e})})}(i));if(!n)return{error:0,data:{}};var{ErrorCode:o,ErrorInfo:a,TotalCount:l,Cursor:u="",Users:c=[]}=n;if(0!==o)throw{errorCode:o,errorInfo:a};var d=`keywordList:${v.keywordList} keywordListMatchType:${v.keywordListMatchType} cursor:${v.cursor} count:${v.count} res: totalCount:`+l,h=[];for(let e=0,t=c.length;e<t;e++){var g,p,{UserID:_,ProfileItems:m}=c[e];_!==this._core.OuterConstant.USER_NOT_FOUND&&""!==_&&(g=m.map(e=>({tag:e.Tag,value:e.StrValue})),p=null==(s=this._core.user.userProfile)?void 0:s.createProfile(_,g),h.push(p))}return{code:0,data:{searchResultList:h,cursor:u,totalCount:l},successLog:{message:d}}}catch(e){let{errorCode:t,errorInfo:s}=e||{};this._handleError({errorCode:t,errorInfo:s,searchType:Ja,functionName:"searchCloudUsers"})}})}searchCloudGroupMembers(d){return I(this,void 0,void 0,function*(){try{var{count:t=20,keywordListMatchType:s}=d,r=f(d,["count","keywordListMatchType"]),i=yield function(o){return I(this,void 0,void 0,function*(){var{count:e,keywordList:t,keywordListMatchType:s,groupTypeList:r,cursor:i,groupIDList:n}=o,e={Count:e,Keywords:t,KeywordMatchType:s,Cursor:i,GroupType:r,GroupIdList:n};return $a.core.common.buildAndSendPacket({servcmd:"group_member_search.query",data:e})})}(Object.assign({count:t,keywordListMatchType:s===Qa.AND?1:0},r));if(!i)return{code:0,data:{}};var{ErrorCode:n,ErrorInfo:o,GroupMembers:a=[],Cursor:u,TotalCount:c}=i;if(0!==n)throw{errorCode:n,errorInfo:o};let e=`keywordList:${d.keywordList} keywordListMatchType:${d.keywordListMatchType} cursor:${d.cursor} count:${d.count} res: totalCount:`+c,l=new Map;return a.forEach(e=>{var{GroupID:t,GroupName:e,GroupType:s,GroupFaceUrl:r,GroupMemberUserName:i,GroupMemberUserID:n,GroupMemberNameCard:o,GroupMemberAvatar:a=""}=e,e={groupID:t,name:e,type:s,avatar:r},s={userID:n,nick:i,nameCard:o,avatar:a};if(l.has(t)){let e=l.get(t);e.memberList.push(s),l.set(t,e)}else l.set(t,{groupInfo:e,memberList:[s]})}),{code:0,data:{searchResultList:[...l.values()],cursor:u,totalCount:c},successLog:{message:e}}}catch(e){var{errorCode:t,errorInfo:s}=e||{};this._handleError({errorCode:t,errorInfo:s,searchType:Ja,functionName:"searchCloudGroupMembers"})}})}searchCloudGroups(c){return I(this,void 0,void 0,function*(){try{var{count:t=20,keywordListMatchType:s}=c,e=f(c,["count","keywordListMatchType"]),r=yield function(n){return I(this,void 0,void 0,function*(){var{count:e,keywordList:t,keywordListMatchType:s,groupTypeList:r,cursor:i}=n,e={Count:e,Keywords:t,KeywordMatchType:s,Cursor:i,GroupType:r};return $a.core.common.buildAndSendPacket({servcmd:"group_search.query",data:e})})}(Object.assign({count:t,keywordListMatchType:s===Qa.AND?1:0},e));if(!r)return{code:0,data:{}};var{ErrorCode:i,ErrorInfo:n,Groups:o,Cursor:a,TotalCount:l}=r;if(0!==i)throw{errorCode:i,errorInfo:n};var u=`keywordList:${c.keywordList} keywordListMatchType:${c.keywordListMatchType} cursor:${c.cursor} count:${c.count} res: totalCount:`+l;return{code:0,data:{searchResultList:(null==o?void 0:o.map(e=>{var{GroupFaceUrl:e,GroupID:t,GroupIntroduction:s,GroupMemberNum:r,GroupName:i,GroupOwnerTinyID:n,GroupOwnerUserID:o,GroupOwnerUserName:a,GroupType:l,GroupAddOption:u,GroupInviteOption:c}=e;return{avatar:e,groupID:t,introduction:s,memberCount:r,name:i,ownerTinyID:n,ownerID:o,ownerNick:a,type:l,joinOption:u,inviteOption:c}}))||[],cursor:a,totalCount:l},successLog:{message:u}}}catch(e){var{errorCode:t,errorInfo:s}=e||{};this._handleError({errorCode:t,errorInfo:s,searchType:Ja,functionName:"searchCloudGroups"})}})}_setTimeRangeParams(e,{timePeriod:t,timePosition:s}){t&&0<t&&(e.startTime=s&&0<s?s-t:this._core.helper.timeManager.getServerTimeSeconds()-t),e.startTime&&e.startTime<0&&(e.startTime=void 0),s&&0<s&&(e.endTime=s)}_handleError({errorCode:e,errorMessage:t,searchType:s}){var r=this._core["helper"];let i=e;throw 60020===e?i="SearchUnable":s!==za&&27003===e?i="SearchParamsError":s!==za&&60018===e&&(i="SearchOverLimit"),new r.ChatError({code:i,message:t})}_isSearchingAllConversations(e){return this._core.helper.isEmpty(e.conversationID)}_setBirthdayRangeParams(e,t){var{miniBirthday:t,maxBirthday:s}=t;void 0!==t&&(e.miniBirthday=t,void 0===s)&&(e.maxBirthday=4294967295),void 0!==s&&(e.maxBirthday=s)}};function cl(e,t){return Math.round(Number(e)*Math.pow(10,t))/Math.pow(10,t)}let dl="qualityStat",hl="im-ssolog-quality-stat",gl=(ka=ka||{},ka[ka.ONLINE=8]="ONLINE","networkRTT"),pl="messageE2EDelay",_l="sendMessageC2C",ml="sendMessageGroup",vl="sendMessageGroupAV",fl="sendMessageRichMedia",Il="cosUpload",El="messageReceivedGroup",Sl="messageReceivedGroupAVPush",Cl="messageReceivedGroupAVPull",Ml={networkRTT:2,messageE2EDelay:3,sendMessageC2C:4,sendMessageGroup:5,sendMessageGroupAV:6,sendMessageRichMedia:7,messageReceivedGroup:8,messageReceivedGroupAVPush:9,messageReceivedGroupAVPull:10,cosUpload:11},yl=[_l,ml,vl,fl,Il],Ol=[El,Sl,Cl],Al=[gl,pl,_l,ml,vl,fl,Il,El,Sl,Cl],Tl={ERR_SVR_COMM_SENSITIVE_TEXT:80001,ERR_SVR_COMM_BODY_SIZE_LIMIT:80002,OPEN_SERVICE_OVERLOAD_ERROR:60022,ERR_SVR_MSG_PKG_PARSE_FAILED:20001,ERR_SVR_MSG_INTERNAL_AUTH_FAILED:20002,ERR_SVR_MSG_INVALID_ID:20003,ERR_SVR_MSG_PUSH_DENY:20006,ERR_SVR_MSG_IN_PEER_BLACKLIST:20007,ERR_SVR_MSG_BOTH_NOT_FRIEND:20009,ERR_SVR_MSG_NOT_PEER_FRIEND:20010,ERR_SVR_MSG_NOT_SELF_FRIEND:20011,ERR_SVR_MSG_SHUTUP_DENY:20012,ERR_SVR_GROUP_INVALID_PARAMETERS:10004,ERR_SVR_GROUP_PERMISSION_DENY:10007,ERR_SVR_GROUP_NOT_FOUND:10010,ERR_SVR_GROUP_INVALID_GROUPID:10015,ERR_SVR_GROUP_REJECT_FROM_THIRDPARTY:10016,ERR_SVR_GROUP_SHUTUP_DENY:10017,MSG_SEND_FAIL:2100,OVER_FREQUENCY_LIMIT:2996},Rl="quality_stat";var Dl=new class{constructor(){this._messageStatsMap=new Map,this._userSideErrorCodes=new Set(Object.values(Tl))}init(e){this._core=e,Object.values(yl).forEach(e=>{this._messageStatsMap.set(e,{totalCount:0,successCount:0,failedCountOfUserSide:0,costSum:0,costCount:0,fileSizeSum:0})})}dispatchSendStats(e){var{name:e,message:t,error:s,startTs:r}=e,i=this._core.constants["SEND_MESSAGE_STAT"];switch(e){case i.TOTAL_COUNT:this._handleTotalCount(t);break;case i.SUCCESS_COUNT:this._handleSuccessCount(t);break;case i.FAILED_COUNT:this._handleFailedCount(t,s);break;case i.SEND_COST:this._handleSendCost(t,r)}}getStatResult(e){var t,s,r,i,n,o=this._messageStatsMap.get(e);return o&&0!==o.totalCount?({totalCount:t,successCount:s,failedCountOfUserSide:i}=o,r=cl(s/t*100,2),n=cl((i=s+i)/t*100,2),o=this._calcAverageValue(o,e),this._resetStat(e),{total_count:t,success_count_business:s,percent_business:r,success_count_platform:i,percent_platform:n,average_value:o}):null}_handleTotalCount(e){e=this._getSendMessageSpecifiedKey(e),e=e&&this._messageStatsMap.get(e);e&&e.totalCount++}_handleSuccessCount(e){e=this._getSendMessageSpecifiedKey(e),e=e&&this._messageStatsMap.get(e);e&&e.successCount++}_handleFailedCount(s,e){var t=null!=(t=null==e?void 0:e.code)?t:null==e?void 0:e.errorCode;if(this._isUserSideError(t)){let e=this._getSendMessageSpecifiedKey(s),t=e&&this._messageStatsMap.get(e);t&&t.failedCountOfUserSide++}}_handleSendCost(e,t){e=this._getSendMessageSpecifiedKey(e),e=e&&this._messageStatsMap.get(e);e&&(e.costSum+=Date.now()-t,e.costCount++)}_isUserSideError(e){return this._userSideErrorCodes.has(e)||120001<=e&&e<=13e4||10100<=e&&e<=10200}_getSendMessageSpecifiedKey(s){let{MSG_IMAGE:e,MSG_AUDIO:t,MSG_VIDEO:r,MSG_FILE:i,CONV_C2C:n,CONV_GROUP:o,GRP_AVCHATROOM:a}=this._core.OuterConstant;if([e,t,r,i].includes(s.type))return fl;if(s.conversationType===n)return _l;if(s.conversationType===o){let e=this._core.appStore["groupStore"],t=e.getGroup(s.to);if(t){let e=t["type"];return e===a?vl:ml}}}_calcAverageValue(e,t){return 0===e.costCount?0:t===Il?Math.round(1e3*e.fileSizeSum/e.costSum):Math.round(e.costSum/e.costCount)}_resetStat(e){e=this._messageStatsMap.get(e);e&&(e.totalCount=0,e.successCount=0,e.failedCountOfUserSide=0,e.costSum=0,e.costCount=0,e.fileSizeSum=0)}},bl=new class{constructor(){this._lastCycleStats=new Map,this._currentCycleStats=new Map}init(e){var{OuterEvent:e,notificationCenter:t}=this._core=e;this._initStatsMap(),t.subscribeOuterEvent(e.MESSAGE_RECEIVED,this._onMessageReceived,this)}addMessageSequence(e){var t=this._getReceivedMessageSpecifiedKey(e),{utils:{isUndefined:s},OuterConstant:{CONV_GROUP:r},ssoLog:i}=this._core;s(t)||!this._currentCycleStats.has(t)?i.warn("addMessageSequence",dl+".addMessageSequence invalid key:"+t):({conversationID:s,sequence:i}=e,e=s.replace(r,""),0!==(s=this._lastCycleStats.get(t)).size&&s.has(e)&&i>(r=s.get(e)).minSeq&&i<r.maxSeq?this._insertToLastCycle(i,r):this._addToCurrentCycle(t,e,i))}getStatResult(e){var t=this._lastCycleStats.get(e);if(!t||0===t.size)return this._transferCycleDataOptimized(e),null;let r=0,i=0;return t.forEach(e=>{var{sortedSequences:e,minSeq:t,maxSeq:s}=e;0<e.length&&(i+=e.length,r+=s-t+1)}),0===r?null:(this._transferCycleDataOptimized(e),{total_count:r,success_count_business:i,percent_business:cl(i/r*100,2)})}reset(){this._lastCycleStats.clear(),this._currentCycleStats.clear()}dispose(){var{notificationCenter:e,OuterEvent:{MESSAGE_RECEIVED:t}}=this._core;e.unSubscribeOuterEvent(t,this._onMessageReceived,this),this.reset()}_initStatsMap(){Object.values(Ol).forEach(e=>{this._lastCycleStats.set(e,new Map),this._currentCycleStats.set(e,new Map)})}_onMessageReceived(e){var{data:e=[]}=e;e.forEach(e=>{this.addMessageSequence(e)})}_transferCycleDataOptimized(e){var t=this._currentCycleStats.get(e);if(t){let r=new Map;t.forEach((e,t)=>{var s=e.dirty?[...e.sortedSequences].sort((e,t)=>e-t):e.sortedSequences;r.set(t,{sortedSequences:s,minSeq:e.minSeq,maxSeq:e.maxSeq,dirty:!1})}),this._lastCycleStats.set(e,r),this._currentCycleStats.set(e,new Map)}}_getReceivedMessageSpecifiedKey(s){let{CONV_GROUP:e,GRP_AVCHATROOM:r}=this._core["OuterConstant"];if(s.conversationType===e&&!0!==(null==s?void 0:s._onlineOnlyFlag)){let e=this._core.appStore["groupStore"],t=e.getGroup(s.to);return t?(s=t["type"],s===r?Cl:El):null}}_insertToLastCycle(e,t){t.dirty&&(t.sortedSequences.sort((e,t)=>e-t),t.dirty=!1);var s=this._findInsertPos(t.sortedSequences,e);t.sortedSequences.splice(s,0,e),t.minSeq=Math.min(t.minSeq,e),t.maxSeq=Math.max(t.maxSeq,e)}_findInsertPos(e,t){let s=0,r=e.length-1;for(;s<=r;){var i=Math.floor((s+r)/2);if(e[i]===t)return i;e[i]<t?s=i+1:r=i-1}return s}_addToCurrentCycle(e,t,s){let r=this._currentCycleStats.get(e).get(t);r?(r.sortedSequences.push(s),r.minSeq=Math.min(r.minSeq,s),r.maxSeq=Math.max(r.maxSeq,s),r.dirty=!0):(r={sortedSequences:[s],minSeq:s,maxSeq:s,dirty:!1},this._currentCycleStats.get(e).set(t,r))}},Nl=new class{constructor(){this._totalDelay=0,this._totalCount=0,this._countLessThan1s=0,this._countLessThan3s=0}init(e){var{OuterEvent:{MESSAGE_RECEIVED:e},notificationCenter:t}=this._core=e;t.subscribeOuterEvent(e,this._onMessageReceived,this)}addMessageDelay(e){var t=this._core.common["timeManager"],t=t.getServerTimeSeconds()-e;0<t&&(this._totalDelay+=t,this._totalCount++,t<=1?this._countLessThan1s++:t<=3&&this._countLessThan3s++)}getStatResult(){var e;return 0===this._totalCount?null:(e={total_count:this._totalCount,success_count_business:this._countLessThan1s,success_count_platform:this._countLessThan3s,percent_business:this._calculatePercentage(this._countLessThan1s,this._totalCount),percent_platform:this._calculatePercentage(this._countLessThan3s,this._totalCount),average_value:this._calculateAverageDelay(this._totalCount)},this.reset(),e)}reset(){this._totalDelay=0,this._totalCount=0,this._countLessThan1s=0,this._countLessThan3s=0}dispose(){var{notificationCenter:e,OuterEvent:{MESSAGE_RECEIVED:t}}=this._core;e.unSubscribeOuterEvent(t,this._onMessageReceived,this),this.reset()}_onMessageReceived(e){let{data:t=[]}=e,{MSG_GRP_TIP:s,MSG_GRP_SYS_NOTICE:r}=this._core["OuterConstant"],i=[s,r];t.forEach(e=>{!i.includes(e.type)&&0<e.clientTime&&this.addMessageDelay(e.clientTime)})}_calculateAverageDelay(e){return 0===e?0:cl(this._totalDelay/e,1)}_calculatePercentage(e,t){return cl(e/t*100,2)}},Ll=new class{init(e){this.core=e}},L=new class{constructor(){this.name="MessageQualityStat",this._reportIndex=0,this._wholePeriod=!1,this._pendingReports=[],this._failedLogsCache=new Map}install(e){var{helper:t,notificationCenter:s,InnerEvent:{QUALITY_STAT:r,LOGOUT:i,DESTROY:n},constants:{WORKFLOW_NAME:o,WORKFLOW_STEP:a}}=this._core=e;Ll.init(e),Dl.init(e),bl.init(e),Nl.init(e),t.registerWorkflowStep(o.SYNC_SERVER_INFO_AFTER_LOGIN,a.QUALITY_REPORT,this.handleLoginSuccess,this),s.subscribeInnerEvent(r,this._handleQualityStat,this),s.subscribeInnerEvent(i,this._reset,this),s.subscribeInnerEvent(n,this._dispose,this)}handleLoginSuccess(){var{store:e,helper:t,utils:{isUndefined:s}}=this._core,e=(e.get("cloudConfig")||{})["q_rpt_interval"],s=s(e)?12e4:Number(e);t.taskScheduler.addTask({id:Rl,intervalMs:s,callback:this.report,context:this})}report(){this._wholePeriod=!0;var e=[...Al.map(e=>{e=this._buildQualityReportItem(e);return e?Object.assign(Object.assign({},e),{report_index:this._reportIndex,whole_period:this._wholePeriod}):null}).filter(Boolean),...this._pendingReports];this._pendingReports=[],this._needSkipReport()||this._uploadQualityReports(e)}_handleQualityStat(e){var t=this._core["constants"]["QUALITY_METRICS"],{label:e,data:s}=e;e===t.MESSAGE_SEND_SUCCESS_RATE&&Dl.dispatchSendStats(s)}_needSkipReport(){return this._isSDKAppIDInBlacklist()&&!this._isTinyIDInWhitelist()}_isSDKAppIDInBlacklist(){var{store:e,utils:t}=this._core,s=e.get("cloudConfig")||{},e=(e.get("instance")||{})["sdkAppId"],{q_rpt_sdkappid_bl:s=[]}=s;if(!t.isEmpty(s))return s.split(",").map(e=>Number(e)).includes(e)}_isTinyIDInWhitelist(){var{store:e,utils:t}=this._core,s=e.get("cloudConfig")||{},e=e.get("login")||{},e=Number(e.tinyID),{q_rpt_tinyid_wl:s=[]}=s;if(!t.isEmpty(s))return s.split(",").includes(e)}_buildQualityReportItem(e){var t=this._getStatResultByKey(e);return null===t?null:(e={quality_type:Ml[e],timestamp:Date.now(),network_type:ka.ONLINE,extension:""},Object.assign(Object.assign({},e),t))}_getStatResultByKey(e){switch(e){case pl:return Nl.getStatResult();case _l:case ml:case vl:case fl:case Il:return Dl.getStatResult(e);case El:case Sl:case Cl:return bl.getStatResult(e);default:return null}}_uploadQualityReports(t){return I(this,void 0,void 0,function*(){try{var r={header:this._core.common.getCommonHead(),quality:t};yield function(){var{common:e,channel:t}=Ll.core,s="imopenstat.tim_web_report_v2",e=e.generateSSOLogProtocolData({servcmd:s,data:r}),s=e.head.seq+s;t.sendPacket(e,{requestId:s})}(),this._reportIndex++,this._wholePeriod=!1}catch(e){console.warn("doReport failed. error:",e),this._pendingReports=this._pendingReports.concat(t),this._cacheFailedLogs()}})}_cacheFailedLogs(){var e=this._pendingReports,t=dl+"._cacheFailedLogs";let s=[...this._failedLogsCache.get(hl)||[],...e];10<s.length&&(s=s.slice(s.length-10),console.log(t+" logs overflow, keeping last 10 items")),this._failedLogsCache.set(hl,s),console.log(t+" count: "+s.length),this._pendingReports=[]}_reset(){var e=this._core["helper"];e.taskScheduler.removeTask(Rl)}_dispose(){var{notificationCenter:e,InnerEvent:{QUALITY_STAT:t,LOGOUT:s,DESTROY:r}}=this._core;e.unSubscribeInnerEvent(t,this._handleQualityStat,this),e.unSubscribeInnerEvent(s,this._reset,this),e.unSubscribeInnerEvent(r,this._dispose,this),this._reset(),Nl.dispose(),bl.dispose()}};let Pl=new class{constructor(){this.name="OfflineMessageSynchronizer",this._lastMessageSequenceMapOnDisconnect=new Map}install(e){var{common:{workflowManager:t},constants:{WORKFLOW_NAME:s,WORKFLOW_STEP:r,InnerEvent:i}}=this._core=e;t.registerWorkflowStep(s.SYNC_SERVER_INFO_AFTER_RE_ONLINE,r.HISTORY_MESSAGE_RECOVER,this._syncOfflineMessage,this),e.notificationCenter.subscribeInnerEvent(i.SOCKET_DISCONNECTED,this._updateLastMessageSequenceMapOnDisconnect,this)}_syncOfflineMessage(e){let t=((null==e?void 0:e.result)||{})["conversationList"],{OuterConstant:s,utils:{isArray:r}}=this._core;if(r(t)){let e=t.filter(e=>e.type===s.CONV_GROUP&&e.groupProfile.type!==s.GRP_AVCHATROOM);return this._recoverGroupHistoryMessage(e)}}_recoverGroupHistoryMessage(e){return I(this,void 0,void 0,function*(){let i=this._core["OuterConstant"],n=[],o=[];return yield Promise.all(null==e?void 0:e.map(r=>I(this,void 0,void 0,function*(){var{groupProfile:{groupID:e}={},lastMessage:{lastSequence:t}={}}=r,e=""+i.CONV_GROUP+e,s=this._getLocalLastMessageSequence(e);this._shouldRecoverHistory({localLastMessageSequence:s,serverLastMessageSequence:t})&&(yield this._recoverHistoryForConversation({conversationID:e,localLastMessageSequence:s,serverLastMessageSequence:t,groupTipList:o})),n.push(e.replace(i.CONV_GROUP,""))}))),{recoverRevokeNoticeGroupIDList:n,groupTipList:o}})}_recoverHistoryForConversation(e){return I(this,arguments,void 0,function*({conversationID:I,localLastMessageSequence:E,serverLastMessageSequence:S,groupTipList:C}){try{let{utils:{isArray:e,isObject:t,isEmpty:s},OuterEvent:r,OuterConstant:i,notificationCenter:n,message:o,appStore:a,common:{getMessagePreviewText:l}}=this._core,u=S-E,c=Math.min(20,u),d={},h=yield o.messageHistory.getGroupRoamingMessagesByAnchor({conversationID:I,sequence:E+c,direction:i.Direction.FORWARD,count:c}),{nextReqMessageIDFromServer:g,hasNoMoreHistoryMessage:p,messageList:_,serverGroupTipList:m}=h,v=(e(m)&&C.push(...m),p&&g<0),f=[];if(e(_)&&(_.forEach(e=>{o.messageReceiver.groupMessageReceiver.updateMessageProfile(e),e.from===i.CONV_SYSTEM&&(e.isSystemMessage=!1),o.messageDataHandler.storeConversationMessage(e)&&!s(e.payload)&&(f.push(e),e._isExcludedFromLastMessage||(d.lastMessage=Object.assign({},e)))}),0<f.length)&&n.emitOuterEvent(r.MESSAGE_RECEIVED,{name:r.MESSAGE_RECEIVED,data:f}),!v&&0<_.length){let e=_[_.length-1].sequence;yield this._recoverHistoryForConversation({conversationID:I,localLastMessageSequence:e,serverLastMessageSequence:S,groupTipList:C})}t(d.lastMessage)&&(d.lastMessage.messageForShow=l(d.lastMessage.type,d.lastMessage.payload),a.conversationStore.updateConversation(I,d))}catch(E){this._core.ssoLog.error("_recoverHistoryForConversation","Recovery failed for conversation:"+I,{error:E})}})}_updateLastMessageSequenceMapOnDisconnect(){let e=this._core["message"],r=e.messageDataHandler.getContinuousMessagesByConversation();for(let[t,s]of r)if(!t.startsWith("C2C")){let e=Array.from(s.values());var i;0<(null==e?void 0:e.length)&&(i=e[e.length-1].sequence,this._lastMessageSequenceMapOnDisconnect.set(t,i))}}_getLocalLastMessageSequence(e){var t=this._core["message"];return this._lastMessageSequenceMapOnDisconnect.has(e)?this._lastMessageSequenceMapOnDisconnect.get(e):null==(e=(t=t.messageDataHandler.getLocalMessageList(e))[t.length-1])?void 0:e.sequence}_shouldRecoverHistory(e){var t,{localLastMessageSequence:e,serverLastMessageSequence:s}=e;return"number"==typeof e&&"number"==typeof s&&(t=s-e,0!==s)&&0<e&&1<=t&&t<300}},Gl,wl;Gl=us.STANDARD,wl=[hr,t,gr,m,Cr,L,Pl,S,bn,ro,Ma,n,ul,Fr];var Ul=Object.freeze({__proto__:null,ChatError:_,WorkflowManager:g,buildAndSendPacket:Hs,get builtInPlugins(){return wl},checkBusinessCapabilityBits:qs,deepMerge:Js,getCurrentUserID:p,getErrorMessage:Ds,getMessagePreviewText:Qs,isC2CConv:e=>w(e)&&e.slice(0,3)===ts.CONV_C2C,isCommunity:Vs,isGroupConv:e=>w(e)&&e.slice(0,5)===ts.CONV_GROUP,isTopic:Bs,isUnlimitedAVChatRoom:function(){var e;return!(null==(e=k.store.get("instance"))||!e.unlimitedAVChatRoom)},liteChatInstanceMap:xs,registerInterceptor:ks,registerValidateConfig:Fs,requireAuth:bs,get sdkEdition(){return Gl},updateGroupAtInfo:(t,s)=>{var{CONV_AT_ME:r,CONV_AT_ALL:i,CONV_AT_ALL_AT_ME:n}=C;if(!function(t,e){let{CONV_AT_ME:s,CONV_AT_ALL:r,CONV_AT_ALL_AT_ME:i}=C,{groupID:n,sequence:o}=t,a=!1;return Vs({groupID:n})&&e.forEach(e=>{e.messageSequence===o&&(e.atTypeArray.includes(s)&&t.groupAtType.includes(r)&&(e.atTypeArray=[i]),e.atTypeArray.includes(r)&&t.groupAtType.includes(s)&&(e.atTypeArray=[i],e.__random=t.__random,e.__sequence=t.__sequence),a=!0)}),a}(t,s)){let e=[...t.groupAtType];e.includes(r)&&e.includes(i)&&(e=[n]);r={from:t.from,groupID:t.groupID,topicID:t.topicID,messageSequence:t.sequence,atTypeArray:e,__random:t.__random,__sequence:t.__sequence};s.push(r)}},validateAndExecute:Us,validateParameters:Ns});class kl{constructor(){this._builtInPlugins=new Set,this._externalPlugins=new Set}static getInstance(){return kl._instance||(kl._instance=new kl),kl._instance}static setInstance(e){kl._instance=e}installBuiltInPlugin(e){e&&this._installPlugin(e,this._builtInPlugins)}installExternalPlugin(e){e&&this._installPlugin(e,this._externalPlugins)}clear(){this._builtInPlugins=new Set,this._externalPlugins=new Set}_installPlugin(e,t){var s=[];let r=(s=q(e)?e:[e]).findIndex(e=>"AVChatRoom"===(null==e?void 0:e.name)),i=-1<r?s.splice(r,1):[];s.forEach(e=>{this._isPluginInstalled(e.name)||(e&&Bt(e.install)?(t.add(e.name),Bt(e.getInstalledSubPlugins)?e.install(P.getInstance().exposeApiForPlugin(),i):e.install(P.getInstance().exposeApiForPlugin()),Bt(e.handleLoginSuccess)&&this._isLoggedIn()&&e.handleLoginSuccess()):Bt(e)?(t.add(e.name),e(P.getInstance().exposeApiForPlugin()),Bt(e.handleLoginSuccess)&&this._isLoggedIn()&&e.handleLoginSuccess()):console.warn('A plugin must either be a function or an object with an "install" function.'))})}_isPluginInstalled(e){return this._builtInPlugins.has(e)||this._externalPlugins.has(e)}_isLoggedIn(){var e;return!0===(null==(e=k.store.get("login"))?void 0:e.isLoggedIn)}}var F,Fl,ql,xl,Vl=new class{constructor(){this._conversationMap=new Map}getConversationMap(){return this._conversationMap}getConversation(e){return this._conversationMap.get(e)}updateConversation(e,t,s={emit:!0,needSort:!1}){let{emit:r,needSort:i}=s,n=this._conversationMap.get(e);n&&!je(t)&&(Object.keys(t).forEach(e=>{n[e]=t[e]}),r)&&k.notificationCenter.emitInnerEvent(d.CONVERSATION_UPDATED,{needSort:i})}deleteConversation(e){this._conversationMap.has(e)&&(this._conversationMap.delete(e),k.notificationCenter.emitInnerEvent(d.CONVERSATION_UPDATED))}},Bl=new class{constructor(){this._groupMap=new Map}getGroupMap(){return this._groupMap}getGroup(e){return this._groupMap.get(e)}updateGroup(e,t){let s=this._groupMap.get(e);s&&!je(t)&&Object.keys(t).forEach(e=>{s[e]=t[e]})}},jl=new class{constructor(){this._messagesByConversation=new Map}updateMessage(s,t,e){let r,{operation:i,updateUnreadCount:n=!0}=e,o=f(e,["operation","updateUnreadCount"]),a=[];for(let e of t){let t=null==(r=this._messagesByConversation.get(s))?void 0:r.get(e);if(!t)return!1;Object.keys(o).forEach(e=>{t[e]=o[e]}),a.push(t)}return this._emitMessageStoreOperationEvent(i,{conversationID:s,messageList:a,updateUnreadCount:n}),a}getMessagesByConversation(e){return[...(null==(e=this._messagesByConversation.get(e))?void 0:e.values())||[]]}getMessages(){return this._messagesByConversation}_emitMessageStoreOperationEvent(e,t){var s=t["conversationID"];Bs(s)?k.notificationCenter.emitInnerEvent(Xt[e],t):k.notificationCenter.emitInnerEvent(e,t)}},Kl=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)}},Hl=Object.freeze({__proto__:null,conversationStore:Vl,groupStore:Bl,messageStore:jl,userStore:Kl});class P{static getInstance(){return P._instance||(P._instance=new P),P._instance}static setInstance(e){P._instance=e}constructor(){this._experimentalApiMap={statTUIKeyFeatures:this.statKeyFeatureUsage.bind(this),setApplicationID:this.setApplicationID.bind(this),reportModalView:this.reportModalView.bind(this)},this._apiHandlersMap={},this._apiMap={on:k.notificationCenter.subscribeOuterEvent.bind(k.notificationCenter),off:k.notificationCenter.unSubscribeOuterEvent.bind(k.notificationCenter),destroy:this.destroy.bind(this),callExperimentalAPI:this.callExperimentalAPI.bind(this),use:kl.getInstance().installExternalPlugin.bind(kl.getInstance()),registerPlugin:this.registerPlugin.bind(this),setLogLevel:this.setLogLevel.bind(this)}}registerPlugin(e){k.ssoLog.debug("registerPlugin",e)}statKeyFeatureUsage(e){k.ssoLog.debug("statTUIKeyFeatures",e)}setLogLevel(e){k.ssoLog.debug("setLogLevel",e),k.ssoLog.setLogLevel(e)}setApplicationID(e){k.store.set("instance",{applicationID:e})}getApiMap(){return this._apiMap}setApiMap(e){this._apiMap=e}registerApi(e){let{common:{timeManager:n},utils:{safeStringify:t}}=k,{apiName:o,context:s,methodName:a=o,matcher:r}=e;this._apiHandlersMap[o]||(this._apiHandlersMap[o]=[]),this._apiHandlersMap[o].push({context:s,methodName:a,matcher:r}),this._apiMap[o]&&1!==this._apiHandlersMap[o].length||(this._apiMap[o]=(...s)=>{let r=n.getServerTimeMs(),i=0;"login"===o&&(i=4),gs.includes(o)&&k.ssoLog.debug(o,o+" start params: "+t(s)),Us(a,s);for(let t of this._apiHandlersMap[o])if(!t.matcher||t.matcher(s))try{let e=t.context[t.methodName].bind(t.context)(...s);return this._isPromiseLike(e)?this._handleAsyncResult(e,o,i,r):(this._reportApiSuccessLog({result:e,apiName:o,eventType:i,startTime:r}),e)}catch(s){throw k.ssoLog.error(o,`${o} fail ${null==s?void 0:s.message})`,{error:s,costTime:n.getServerTimeMs()-r,eventType:i,method:o}),s}})}registerExperimentalAPI(e,t,s){this._experimentalApiMap[e]=t[s||e].bind(t)}destroy(){return I(this,void 0,void 0,function*(){var e,t;try{null!=(e=k.store.get("login"))&&e.isLogin&&(yield this._apiMap.logout()),k.notificationCenter.emitInnerEvent(d.DESTROY)}catch(e){console.debug("destroy error: ",e)}finally{k.notificationCenter.emitOuterEvent(Kt.SDK_DESTROY,{SDKAppID:null==(t=k.store.get("instance"))?void 0:t.sdkAppId}),xs.clear(),kl.getInstance().clear(),g.getInstance().destroy(),k.destroy()}})}exposeApiForClient(){return this._apiMap}exposeApiForPlugin(){return Object.assign(Object.assign({InnerEvent:d,InnerEventSubType:k.notificationCenter.InnerEventSubType,OuterEvent:Kt,OuterConstant:C,SignalingEvent:Yt,helper:Object.assign(Object.assign(Object.assign({},k.utils),k.common),{registerApi:this.registerApi.bind(this),registerExperimentalAPI:this.registerExperimentalAPI.bind(this),registerInterceptor:ks,registerValidateConfig:Fs,checkBusinessCapabilityBits:qs,registerWorkflowStep:g.getInstance().registerWorkflowStep.bind(g.getInstance()),ChatError:_}),apiMap:this._apiMap},k),{constants:Object.assign(Object.assign({},ms),k.constants),common:Object.assign(Object.assign(Object.assign({},Ul),k.common),{workflowManager:g.getInstance()}),utils:k.utils,appStore:Hl})}callExperimentalAPI(e,t){return k.ssoLog.debug(`callExperimentalAPI.${e} start params: `+k.utils.safeStringify(t)),this._experimentalApiMap[e]?this._experimentalApiMap[e](t):Promise.reject(new _({code:ls.INVALID_OPERATION}))}reportModalView(e){var{ssoLog:t,utils:{safeStringify:s}}=k;try{t.createSSOLogData({method:"reportModalView",message:e,eventType:30}).end(!0)}catch(e){t.debug("reportModalView Report failed: "+s(e))}}_isPromiseLike(e){return null!==e&&"object"==typeof e&&"function"==typeof e.then}_handleAsyncResult(e,t,s,r){return e.then(e=>(this._reportApiSuccessLog({result:e,apiName:t,eventType:s,startTime:r}),e)).catch(e=>{throw k.ssoLog.error(t,`${t} fail ${null==e?void 0:e.message})`,{error:e,costTime:k.common.timeManager.getServerTimeMs()-r,eventType:s,method:t}),e})}_reportApiSuccessLog(e){let{result:t,apiName:s,startTime:r,eventType:i}=e;var e=k.common["timeManager"],{successLog:{message:n,moreMessage:o}={message:"",moreMessage:""}}=t||{},a=e.getServerTimeMs();"login"===s&&(r+=e.getTimeOffsetWithServer()),gs.includes(s)&&k.ssoLog.info(s,s+` success ${n} `+o,{costTime:a-r,eventType:i,message:n,moreMessage:o}),null!=t&&t.successLog&&delete t.successLog}}class Wl{constructor(){this._latestLoginAt=0,this._latestSendOnlinePresenceRequestTime=0,this._helloInterval=120,this._customLoginInfo=""}init(){var{notificationCenter:e,store:t}=k;t.set("login",{isReady:!1}),P.getInstance().registerApi({apiName:"login",context:this}),P.getInstance().registerApi({apiName:"logout",context:this}),P.getInstance().registerApi({apiName:"getLoginUser",context:this}),P.getInstance().registerApi({apiName:"isReady",context:this}),P.getInstance().registerExperimentalAPI("setCustomLoginInfo",this),e.subscribeInnerEvent(d.RECONNECTED,this._reLogin,this),k.notificationCenter.subscribeInnerEvent(d.DESTROY,this._dispose,this)}login(l){return I(this,void 0,void 0,function*(){var e;let t=(k.store.get("instance")||{})["sdkEdition"];try{if(this._isLoginIn())return this._createRepeatLoginResponse();if(this._isLoginFrequencyExceeded())throw new _({functionName:"login",code:ls.REPEAT_LOGIN});var s=yield this._performLogin(l),r=(this._validateAfterLogin(s),this._handleLoginSuccess(s),yield this._ensureAsyncComplete(),this._updateAndEmitSDKReady(),this._latestLoginAt=0,null==(e=k.channel.getSocketAdapter())?void 0:e.getId()),{appId:i,href:n}=k.store.get("instance")||{},{instanceID:o,customStatus:a}=s||{};return{code:0,data:s,successLog:{message:t,moreMessage:`socketID:${r} instanceID:${o} customStatus:${a} href: ${n} appId: `+i}}}catch(e){let t=e["errorCode"],s=(t!==ls.REPEAT_LOGIN&&(this._latestLoginAt=0),new _({functionName:"login",code:t}));throw console.error(s),s}})}_reLogin(){return I(this,void 0,void 0,function*(){var e,t,s,r,i;try{this._isLoginIn()&&(t=yield Rs(this._customLoginInfo))&&({instanceID:s,customStatus:r}=t,k.store.set("login",{statusInstanceId:s}),g.getInstance().executeWorkflow(h.SYNC_SERVER_INFO_AFTER_RE_ONLINE,{customStatus:r,statusType:Zt.USER_STATUS_ONLINE}),i=null==(e=k.channel.getSocketAdapter())?void 0:e.getId(),k.ssoLog.info("reLogin",`socketId:${i} instanceId:`+s))}catch(e){console.warn(e)}})}logout(){return I(this,arguments,void 0,function*(t=ps.USER_INITIATED){let e=k["ssoLog"];e.debug("logout","logout start logoutReason: "+t);try{yield this._performLogout(t),e.info("logout","logout success"),k.ssoLog.uploadSSOLogData()}catch(t){let e=t["errorCode"];throw new _({functionName:"logout",code:e})}finally{this._handleLogoutCompleted()}return{code:0,data:{}}})}getLoginUser(){return this._isLoginIn()?p():""}isReady(){var e;return null==(e=k.store.get("login"))?void 0:e.isReady}setCustomLoginInfo(e=""){this._customLoginInfo=e}_updateAndEmitSDKReady(){k.store.set("login",{isReady:!0}),setTimeout(()=>{k.notificationCenter.emitOuterEvent(Kt.SDK_READY,{name:Kt.SDK_READY})},1)}_updateAndEmitSDKNotReady(){k.store.set("login",{isReady:!1}),k.notificationCenter.emitOuterEvent(Kt.SDK_NOT_READY,{name:Kt.SDK_NOT_READY})}_validateAfterLogin(e){if(!e)throw new _({functionName:"login",message:"login response is empty"});var{tinyID:e,a2Key:t}=e||{};if(!e)throw new _({functionName:"login",code:ls.NO_TINYID});if(!t)throw new _({functionName:"login",code:ls.NO_A2KEY})}_createRepeatLoginResponse(){var e;return{code:0,data:{actionStatus:"OK",errorCode:0,errorInfo:Ds({code:"RepeatLogin",replacement1:null==(e=k.store.get("login"))?void 0:e.userId}),repeatLogin:!0}}}_performLogin(s){return I(this,void 0,void 0,function*(){var{userID:e,userSig:t}=s;return k.store.set("login",{userId:e,userSig:t}),this._latestLoginAt=Date.now(),Rs(this._customLoginInfo)})}_ensureAsyncComplete(){return I(this,void 0,void 0,function*(){yield new Promise(e=>{setTimeout(()=>e(null),1)})})}_handleLoginSuccess(e){var t=k.common["timeManager"],{helloInterval:s,timeStamp:r,customStatus:i,purchaseBits:n}=e;t.calculateTimeOffsetWithServer(this._latestLoginAt,1e3*r),this._helloInterval=s||120,this._updateLoginStore(e),k.user.userStatus.setCustomStatus(i),g.getInstance().executeWorkflow(h.SYNC_SERVER_INFO_AFTER_LOGIN,{purchaseBits:n}),k.common.taskScheduler.addTask({id:fs,intervalMs:1e3*this._helloInterval,callback:this._sendOnlinePresenceRequest,context:this})}_performLogout(e){return function(s){return I(this,void 0,void 0,function*(){var e=s["logoutReason"],t="im_open_status.wslogout",e=k.common.generateProtocolData({servcmd:t,data:{wslogout_type:e,isWebUniapp:0}}),t=e.head.seq+t;return yield k.channel.sendPacket(e,{requestId:t})})}({logoutReason:e})}_handleLogoutCompleted(){this._updateAndEmitSDKNotReady(),this._reset(),g.getInstance().reset(),k.notificationCenter.emitInnerEvent("logout")}_updateLoginStore(e){var{a2Key:e,tinyID:t,instanceID:s,authKey:r}=e;k.store.set("login",{a2Key:e,tinyID:t,statusInstanceId:s,authKey:r,isLoggedIn:!0})}_sendOnlinePresenceRequest(){return I(this,void 0,void 0,function*(){this._latestSendOnlinePresenceRequestTime=Date.now();try{e="im_open_status.wshello",t=k.common.generateProtocolData({servcmd:e,data:{isWebUniapp:0}}),e=t.head.seq+e,yield k.channel.sendPacket(t,{requestId:e})}catch(e){k.ssoLog.warn("_sendOnlinePresenceRequest"," error:"+e.message)}var e,t})}_isLoginIn(){var e;return!0===(null==(e=k.store.get("login"))?void 0:e.isLoggedIn)}_isLoginFrequencyExceeded(){return Date.now()-this._latestLoginAt<=15e3}_reset(){k.common.taskScheduler.removeTask(fs),this._helloInterval=120,this._latestSendOnlinePresenceRequestTime=0,this._latestLoginAt=0,this._customLoginInfo="",k.store.clear("login"),k.store.set("login",{isReady:!1}),k.store.set("instance",{applicationID:0})}_dispose(){this._reset();var e=k["notificationCenter"];e.unSubscribeInnerEvent(d.RECONNECTED,this._reLogin,this),e.unSubscribeInnerEvent(d.DESTROY,this._dispose,this)}}let Yl={login:{userID:{required:!0,rules:["string"],allowEmpty:!1},userSig:{required:!0,rules:["string"],allowEmpty:!1}}},$l={logout:!0};class zl{constructor(){this.loginAction=new Wl,this.kickedOutHandler=new Ts,this.loginAction.init(),this.kickedOutHandler.init(),Fs({auth:$l,params:Yl})}}(y=F=F||{}).CONV_C2C="C2C",y.CONV_GROUP="GROUP",y.CONV_TOPIC="TOPIC",y.CONV_SYSTEM="@TIM#SYSTEM",(hr=Fl=Fl||{}).MSG_PRIORITY_HIGH="High",hr.MSG_PRIORITY_NORMAL="Normal",hr.MSG_PRIORITY_LOW="Low",hr.MSG_PRIORITY_LOWEST="Lowest",(t=ql=ql||{}).MSG_TEXT="TIMTextElem",t.MSG_CUSTOM="TIMCustomElem",t.MSG_LOCATION="TIMLocationElem",t.MSG_FACE="TIMFaceElem",t.MSG_IMAGE="TIMImageElem",t.MSG_AUDIO="TIMSoundElem",t.MSG_FILE="TIMFileElem",t.MSG_VIDEO="TIMVideoFileElem",t.MSG_GRP_TIP="TIMGroupTipElem",t.MSG_GRP_SYS_NOTICE="TIMGroupSystemNoticeElem",t.MSG_MERGER="TIMRelayElem";let Jl={1:Fl.MSG_PRIORITY_HIGH,2:Fl.MSG_PRIORITY_NORMAL,3:Fl.MSG_PRIORITY_LOW,4:Fl.MSG_PRIORITY_LOWEST},Ql=((gr=xl=xl||{}).IN="in",gr.OUT="out",{});function Xl(e){var t,s,r;return e?(void 0===Ql[e]?(t=("3"+(r=new Date).getHours()).slice(-2),s=("0"+r.getMinutes()).slice(-2),r=("0"+r.getSeconds()).slice(-2),Ql[e]=parseInt([t,s,r,"0001"].join(""),10),console.log("autoIncrementIndex start index:"+Ql[e])):Ql[e]+=1,Ql[e]):0}class Zl{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=Fl.MSG_PRIORITY_NORMAL,this._relayFlag=!1;var t,{clientTime:s=k.common.timeManager.getServerTimeSeconds()||0,senderTinyID:r,currentUser:i,needReadReceipt:n,isSupportExtension:o,customModerationConfigurationId:a,to:l,from:u,nick:c="",avatar:d="",time:h,messageControlInfo:g,tinyID:p,cloudCustomData:_="",messageLifeTime:m,messageVersion:v=0,conversationType:f,sequence:I,checkResult:E=0,isPlaceMessage:S=0,messageFlagBits:C,receiverList:M,isSystemMessage:y=!1,status:O=Ht.SUCCESS,revokeReason:A="",conversationSubType:T,clientSequence:R,protocol:D="JSON",revokerInfo:b={userID:"",nick:"",avatar:""},readReceiptInfo:N={readCount:void 0,unreadCount:void 0,isPeerRead:void 0,timestamp:0},random:L,groupProfile:P,atUserList:G,flow:w,isRead:U=!1}=e;this.clientTime=s,this.senderTinyID=r||p,this.needReadReceipt=!0===n||1===n,this.isSupportExtension=!0===o||1===o,this._cmConfigID=a,this.to=l,this.nick=c,this.avatar=d,this.protocol=D,this.random=void 0===L?(t=t||99999999,Math.round(Math.random()*t)):L,this.time=h||Math.ceil(Date.now()/1e3),this._isExcludedFromLastMessage=!(null==g||!g.excludedFromLastMessage),this._isExcludedFromUnreadCount=!(null==g||!g.excludedFromUnreadCount),this.isModified=!!v,this.cloudCustomData=_,this.messageLifeTime=m,this.from=u||null,this.sequence=I||0,this.conversationType=f||F.CONV_C2C,this.hasRiskContent=1<E,this.version=v,this.isPlaceMessage=S,this.isRevoked=2===S||8===C,this.isSystemMessage=y,this.readReceiptInfo=N,this.revokeReason=A,this.revokerInfo=b,this._receiverList=M,this.conversationSubType=T,this.revoker=(null==b?void 0:b.revoker)||"",this.clientSequence=R||I||0,this.status=O,this.atUserList=G||[],this.flow=w,this.isRead=U,this.reInitialize(i),this._initC2CReadReceiptInfo(e),this._extractGroupInfo(P)}getElements(){return this._elements}isOnlineMessage(){return 0===this.messageLifeTime}setElement(e){Array.isArray(e)?this._elements=e:this._elements=[e],this._updatePayloadAndType()}transformElementsToServerFormat(){return this._elements?Array.isArray(this._elements)?this._elements.map(e=>e.transformToServerFormat()):this._elements.transformToServerFormat():null}setRelayFlag(e){this._relayFlag=e}validateBeforeSend(){var e,t;return this._relayFlag?{isValid:!0}:0<(null==(e=this._elements)?void 0:e.length)?null==(t=null==(e=this._elements[0])?void 0:e.validateBeforeSend)?void 0:t.call(e):{isValid:!1}}_updatePayloadAndType(){this._elements[0]&&(this.payload=this._elements[0].content,this.type=this._elements[0].type)}_initC2CReadReceiptInfo(e){var{readReceiptSentByPeer:e,timestamp:t=0}=e;this.conversationType===F.CONV_C2C&&!0===this.needReadReceipt&&(this.readReceiptInfo.isPeerRead=1===e,this.readReceiptInfo.timestamp=t)}_extractGroupInfo(e){var t,s;e&&({From_AccountNick:e,From_AccountHeadurl:t,MsgFrom_AccountExtraInfo:s}=e,s=(s||{})["NameCard"],"string"==typeof e&&(this.nick=e),"string"==typeof t&&(this.avatar=t),"string"==typeof s)&&(this.nameCard=s)}reInitialize(e){e===this.from&&(this.isRead=!0),this._initSequence(e),this._concatConversationID(e),this.generateMessageID()}_concatConversationID(e){var t=this.conversationType;t!==F.CONV_SYSTEM?(e=t!==F.CONV_C2C||e===this.from?this.to:this.from,this.conversationID=e?""+t+e:null):this.conversationID=F.CONV_SYSTEM}_initSequence(e){0===this.clientSequence&&e&&(this.clientSequence=Xl(e)),0===this.sequence&&this.conversationType===F.CONV_C2C&&(this.sequence=this.clientSequence)}generateMessageID(){this.from===F.CONV_SYSTEM&&(this.senderTinyID="144115198244471703"),this.ID=`${this.senderTinyID}-${this.clientTime}-`+this.random}setIsRead(e){this.isRead=e}}class eu{static parseServerPushElement(e){var{MsgContent:e={}}=e,{Data:e,Ext:t,Desc:s}=e;return new eu({data:e,description:s,extension:t})}constructor(e){this.type=ql.MSG_CUSTOM;var{data:e="",description:t="",extension:s=""}=e;this.content={data:e,description:t,extension:s}}transformToServerFormat(e){var{isMergerMessage:e=!1}=e||{},{data:e,description:t,extension:s}=e?this.payload:this.content;return{MsgType:this.type,MsgContent:{Data:e,Ext:s,Desc:t}}}validateBeforeSend(){let t=k.utils["isEmpty"],e=[this.content.data,this.content.description,this.content.extension].some(e=>!t(e));return{isValid:e,error:e?null:{message:"content can not be empty"}}}}class tu{static parseServerPushElement(e){var{MsgContent:e={Text:""}}=e,e=e["Text"];return new tu({text:e})}constructor(e){this.type=zt.MSG_TEXT,this.content={text:e.text||""}}validateBeforeSend(){var e;return 0<(null==(e=null==(e=this.content)?void 0:e.text)?void 0:e.length)?{isValid:!0}:{isValid:!1,error:{message:"content can not be empty"}}}transformToServerFormat(e){var{isMergerMessage:e=!1}=e||{},e=(e?this.payload:this.content)["text"];return{MsgType:this.type,MsgContent:{Text:e}}}}var su=new class{constructor(){this._elementClassMap={[ql.MSG_CUSTOM]:eu,[ql.MSG_TEXT]:tu}}init(){P.getInstance().registerApi({apiName:"createCustomMessage",context:this}),P.getInstance().registerApi({apiName:"createTextMessage",context:this})}registerElementClass(e,t){void 0!==t.prototype&&"constructor"in t.prototype&&(this._elementClassMap[e]=t)}getElementClass(e){return this._elementClassMap[e]}createMessage(e){var{from:t,flow:s=xl.OUT}=e,r=(k.store.get("login")||{})["userId"],t=(this._isSendByCurrentInstance({from:t,flow:s,currentUser:r})?this._updateWithSenderInfo(e):this._isMultiEndpointSyncMessage({from:t,flow:s,currentUser:r})&&(e.flow=xl.OUT),Object.assign(Object.assign({},e),{currentUser:r}));return new Zl(t)}createCustomMessage(t){let e=p(),s=this.createMessage(Object.assign(Object.assign({},t),{from:e})),r=this._elementClassMap[ql.MSG_CUSTOM];if(!s)return null;if(r){let e=new r(t.payload);s.setElement(e)}return s}createTextMessage(e){var t,s;return e?(t="string"==typeof e.payload?e.payload:(null==(t=null==e?void 0:e.payload)?void 0:t.text)||"",t=new tu({text:t}),s=p(),(e=k.message.messageFactory.createMessage(Object.assign(Object.assign({},e),{from:s}))).setElement(t),e):null}_updateWithSenderInfo(e){var{nick:t,avatar:s}=e,{userId:r,tinyID:i}=k.store.get("login")||{},n=Kl.getUserProfile(r);return e.nick=t||(null==n?void 0:n.nick)||"",e.avatar=s||(null==n?void 0:n.avatar)||"",e.tinyID=e.tinyID||i||"",e.from=r,e.status=Ht.UNSENT,e.flow=xl.OUT,e}_isMultiEndpointSyncMessage(e){var{from:e,flow:t,currentUser:s}=e;return e===s&&t===xl.IN}_isSendByCurrentInstance(e){var{from:e,flow:t,currentUser:s}=e;return e===s&&t===xl.OUT}};let ru={PushFlag:0,Title:"",Desc:"",Ext:"",ApnsInfo:{Sound:"",BadgeMode:0,IsVoipPush:void 0,Image:"",InterruptionLevel:"active",ContentAvailable:0},AndroidInfo:{Sound:"",XiaoMiChannelID:"",OPPOChannelID:"",GoogleChannelID:"",VIVOClassification:1,VIVOCategory:"",HuaWeiCategory:"",OPPOCategory:"",HuaWeiImage:"",HonorImage:"",GoogleImage:"",HonorImportance:"",MeizuNotifyType:void 0}},iu={HonorImportance:{range:["LOW","NORMAL"],defaultValue:void 0},MeizuNotifyType:{range:[0,1],defaultValue:void 0}},nu={enableIOSBackgroundNotification:{range:[!0,!1],defaultValue:!1},interruptionLevel:{range:["passive","active","time-sensitive","critical"],defaultValue:"active"}};function ou(r,i){return Object.keys(i).forEach(e=>{var{range:t,defaultValue:s}=i[e];r[e]=t.includes(r[e])?r[e]:s}),r}function au(e){return k.utils.isPlainObject(e)?{PushFlag:!0===e.disablePush?1:0,Title:e.title||"",Desc:e.description||"",Ext:e.extension||"",ApnsInfo:function(e){var{apnsInfo:e={},ignoreIOSBadge:t=!1,disableVoipPush:s}=e,{ignoreIOSBadge:r,disableVoipPush:i,enableIOSBackgroundNotification:n}=e=ou(e,nu),e=f(e,["ignoreIOSBadge","disableVoipPush","enableIOSBackgroundNotification"]),r=!0===r||!0===t?1:0;let o;return G(s)||(o=!1===s?1:0),G(i)||(o=!1===i?1:0),Object.assign(Object.assign({},e),{BadgeMode:r,IsVoipPush:o,ContentAvailable:n?1:0})}(e),AndroidInfo:function(e){var{androidInfo:e={},androidOPPOChannelID:t=""}=e,t=e.OPPOChannelID||t,{sound:s="",FCMChannelID:r=""}=e=ou(e,iu),e=f(e,["sound","FCMChannelID"]);return Object.assign(Object.assign({},e),{Sound:-1===(s=(e=s).lastIndexOf("."))?e:e.slice(0,s),OPPOChannelID:t,GoogleChannelID:r})}(e)}:ru}function lu(e){let{From_AccountHeadurl:t,From_AccountNick:s,IsNeedReadReceipt:r,IsPeerRead:i,IsSyncMsg:n,MsgBody:o,MsgClientTime:a,MsgLifeTime:l,MsgRandom:u,MsgSeq:c,MsgTimeStamp:d,SendMsgControl:h,SupportMessageExtension:g,TinyId:p,MsgCheckResult:_,CloudCustomData:m,MsgVersion:v,MsgFlagBits:f,RevokerInfo:I}=e,E,{From_Account:S,To_Account:C}=e;if(1===n){let e=C;C=S,S=e}if(I){let{Reason:e,Revoker_Account:t,Revoker_FromUin:s}=I;E={reason:e,revoker:t,revokerFromUin:s,userID:t}}return{from:S,avatar:t,nick:s,needReadReceipt:1===r,isSyncMessage:n,clientTime:a,messageLifeTime:l,random:u,sequence:c,time:d,messageControlInfo:{excludedFromLastMessage:1===(null==h?void 0:h.NoLastMsg),excludedFromUnreadCount:1===(null==h?void 0:h.NoUnread)},isSupportExtension:g,to:C,tinyID:p,checkResult:_,cloudCustomData:m,revokerInfo:E,messageVersion:v,messageFlagBits:f,readReceiptSentByPeer:i,elements:du(o)}}function uu(e){var{From_Account:e,MsgBody:t,MsgClientTime:s,MsgRandom:r,MsgSeq:i,MsgTimeStamp:n,To_Account:o,MsgVersion:a,CloudCustomData:l}=e;return{from:e,clientTime:s,random:r,sequence:i,time:n,to:o,elements:du(t),messageVersion:a,cloudCustomData:l}}function cu(e){let{ClientSeq:t,From_Account:s,GroupInfo:r,MsgBody:i,MsgClientTime:n,MsgRandom:o,MsgSeq:a,MsgTimeStamp:l,SendMsgControl:u,SupportMessageExtension:c,TinyId:d,CloudCustomData:h,MsgVersion:g,MsgCheckResult:p,NeedReadReceipt:_,IsPlaceMsg:m,RevokerInfo:v,GroupAtInfo:f}=e,I,E=Fl.MSG_PRIORITY_NORMAL;if(Object.keys(Jl).includes(String(e.MsgPriority))&&(E=Jl[e.MsgPriority]),v){let{Reason:e,Revoker_Account:t,Revoker_FromUin:s}=v;I={reason:e,revoker:t,revokerFromUin:s,userID:t}}var S=function(e){let t=[];return Array.isArray(e)&&e.forEach(e=>{0===e.GroupAtAllFlag?t.push(e.GroupAt_Account):1===e.GroupAtAllFlag&&t.push(C.MSG_AT_ALL)}),t}(f);return{clientSequence:t,from:s,groupProfile:r,clientTime:n,priority:E,random:o,sequence:a,time:l,messageControlInfo:{excludedFromLastMessage:1===(null==u?void 0:u.NoLastMsg),excludedFromUnreadCount:1===(null==u?void 0:u.NoUnread)},isSupportExtension:c,tinyID:d,cloudCustomData:h,messageVersion:g,messageCheckResult:p,needReadReceipt:_,isPlaceMessage:m,revokerInfo:I,atUserList:S,elements:du(i),to:function(e){var{utils:{isEmpty:t},constants:{IS_TOPIC_MESSAGE:s}}=k,{ToGroupId:e,GroupInfo:{MillionGroupFlag:r=0,TopicId:i}={}}=e;return r!==s||t(i)?e:i}(e)}}function du(e){var t;return e?Array.isArray(e)?e.map(e=>{var t=k.message.messageFactory.getElementClass(e.MsgType);return null==t?void 0:t.parseServerPushElement(e)}):null==(t=k.message.messageFactory.getElementClass(e.MsgType))?void 0:t.parseServerPushElement(e):null}function hu(e){var{From_Account:e,MsgBody:t,MsgClientTime:s,MsgRandom:r,MsgSeq:i,MsgTimeStamp:n,GroupId:o,TopicId:a,MsgVersion:l,CloudCustomData:u}=e;return{from:e,clientTime:s,random:r,sequence:i,time:n,groupID:o,topicID:a,elements:du(t),messageVersion:l,cloudCustomData:u}}function gu({conversationUpdateFields:e,message:t}){var{conversationID:s,conversationType:r,conversationSubType:i,flow:n,_isExcludedFromUnreadCount:o,_isExcludedFromLastMessage:a}=t,a=a?"":t,t=!o&&n===xl.IN;e.has(s)?(e.get(s).lastMessage=a,t&&e.get(s).unreadCount++):e.set(s,{conversationID:s,type:r,subType:i,unreadCount:t?1:0,lastMessage:a})}function pu(e){return e.filter(e=>{var t=!je(null==e?void 0:e.getElements()),s=1===(null==e?void 0:e.isPlaceMessage);return t||k.ssoLog.error("emptyMessageBody",`from:${e.from} to:${e.to} sequence:`+e.sequence),t&&!s})}function _u(e){var t=k.message["messageDataHandler"];return!t.isInMessageList(e)&&!t.isMessageSentByCurrentInstance(e)}var mu=Object.freeze({__proto__:null,autoIncrementIndex:Xl,filterValidMessages:pu,parseServerGroupMessage:cu,parseServerPushC2CModifyMessage:uu,parseServerPushGroupModifyMessage:hu,parseServerPushMessage:lu,parseServerPushMessageElement:du,shouldStoreMessage:_u,updateConversationFields:gu});let vu=k.utils["isPlainObject"];function fu(e,t={}){let{onlineUserOnly:s,messageControlInfo:r}=t,i=t["offlinePushInfo"],n=(e.conversationType===F.CONV_C2C&&!0===s&&(i?i.disablePush=!0:i={disablePush:!0}),"");"string"==typeof e.cloudCustomData&&0<e.cloudCustomData.length&&(n=e.cloudCustomData);var o=[];if(r&&vu(r)){let{excludedFromUnreadCount:e,excludedFromLastMessage:t,excludedFromContentModeration:s}=r;!0===e&&o.push("NoUnread"),!0===t&&o.push("NoLastMsg"),!0===s&&o.push("NoMsgCheck")}return{onlineUserOnly:s,cloudCustomData:n,messageControlInfo:o,offlinePushInfo:i}}function Iu(e){var t,{webhookInfo:{disableCloudMessagePreHook:e=!1,disableCloudMessagePostHook:s=!1}={}}=e||{};if(e||s)return t=[],e&&t.push("ForbidBeforeSendMsgCallback"),s&&t.push("ForbidAfterSendMsgCallback"),t}function Eu(t,s){return I(this,void 0,void 0,function*(){var e=yield Hs((t.conversationType===F.CONV_GROUP?function(e,t){var s,{onlineUserOnly:r,cloudCustomData:i,messageControlInfo:n,offlinePushInfo:o}=fu(e,t),a=JSON.parse(JSON.stringify(e.transformElementsToServerFormat()));let l;return q(e._receiverList)&&0<e._receiverList.length&&(l=e._receiverList,50<e._receiverList.length)&&(l=e._receiverList.slice(0,50),console.warn("ReceiverListLimit")),{servcmd:"group_open_http_svc.send_group_msg",data:{From_Account:null==(s=k.store.get("login"))?void 0:s.userId,GroupId:e.to,MsgBody:a,CloudCustomData:i,Random:e.random,MsgPriority:e.priority,ClientSeq:e.clientSequence,GroupAtInfo:e._groupAtInfoList,OnlineOnlyFlag:r?1:0,MsgClientTime:e.clientTime,OfflinePushInfo:au(o),SendMsgControl:r?void 0:n,NeedReadReceipt:!0===e.needReadReceipt?1:0,To_Account:l,SupportMessageExtension:!0===e.isSupportExtension?1:0,IsRelayMsg:!0===e._relayFlag?1:0,CustomModerationConfigID:e._cmConfigID,ForbidCallbackControl:Iu(t)}}}:function(e,t){var s,{onlineUserOnly:r,cloudCustomData:i,messageControlInfo:n,offlinePushInfo:o}=fu(e,t),r=!0===r?0:void 0,a=JSON.parse(JSON.stringify(e.transformElementsToServerFormat()));return{servcmd:"openim.sendmsg",data:{From_Account:null==(s=k.store.get("login"))?void 0:s.userId,To_Account:e.to,MsgBody:a,CloudCustomData:i,MsgSeq:e.sequence,MsgRandom:e.random,MsgLifeTime:r,From_AccountNick:e.nick,From_AccountHeadurl:e.avatar,SendMsgControl:0!==r?n:void 0,MsgClientTime:e.clientTime,IsNeedReadReceipt:!0===e.needReadReceipt?1:0,SupportMessageExtension:!0===e.isSupportExtension?1:0,IsRelayMsg:!0===e._relayFlag?1:0,CustomModerationConfigID:e._cmConfigID,OfflinePushInfo:au(o),forbidCallbackControl:Iu(t)}}})(t,s));return e?{time:e.MsgTime,messageDropReason:e.MsgDropReason,sequence:e.MsgSeq}:null})}let Su=k.utils["isPlainObject"],{MSG_AUDIO:Cu,MSG_FILE:Mu,MSG_IMAGE:yu,MSG_VIDEO:Ou,MSG_MERGER:Au}=C;class Tu{init(){P.getInstance().registerApi({apiName:"sendMessage",context:this,matcher:e=>![Cu,Mu,yu,Ou,Au].includes(e[0].type)})}sendMessage(c,d){return I(this,void 0,void 0,function*(){let{TOTAL_COUNT:e,SEND_COST:o,SUCCESS_COUNT:a,FAILED_COUNT:t}=hs;if(!(c instanceof Zl))throw new _({code:ls.MSG_INSTANCE_REQUIRED});let s=c.validateBeforeSend();if(!s.isValid){let{code:e,message:t=""}=s.error||{};throw new _({code:e,message:t})}this._reportMessageSendQuality({name:e,message:c});let l=!1;var u=(k.message||{})["messageDataHandler"];try{let r=(d||{})["messageControlInfo"],i=null,n=(u.addRandomOfSentMessage(c.random),Date.now());if(c.conversationType===F.CONV_C2C?(l=!0===(null==d?void 0:d.onlineUserOnly),i=yield Eu(c,d)):c.conversationType===F.CONV_GROUP&&(yield this._validateBeforeSendGroupMessage(c),i=yield Eu(c,d)),i){let{messageDropReason:e,sequence:t,time:s}=i;if(this._updateNickAndAvatarOfSentMessageByMe(c),e&&this._logRateLimitInfo(c,t,e),this._reportMessageSendQuality({name:a,message:c}),this._reportMessageSendQuality({name:o,message:c,startTs:n}),!0===c.isResend){let e=u.findMessage(c.ID);e&&(k.ssoLog.debug("sendMessage","sendMessage resend ok. ID:"+e.ID),u.deleteConversationMessage(e))}return c.status=Ht.SUCCESS,c.time=s,c.conversationType===F.CONV_GROUP&&(c.sequence=t),l?c._onlineOnlyFlag=!0:(u.storeConversationMessage(c),this._applySentMessageControlInfo(c,r),this._emitOnlineMessageSent(c)),{code:0,data:{message:c}}}}catch(e){c.status=Ht.FAIL,u.removeRandomOfSentMessage(c.random);var r=(e||{})["errorCode"],i=(null==e?void 0:e.errorInfo)||(null==e?void 0:e.message)||"";throw this._hasRiskContent(r)&&(c.hasRiskContent=!0),l||this._isRejectedByRestApi(r)||u.storeConversationMessage(c),this._reportMessageSendQuality({name:t,message:c,error:e}),i=`type:${c.type} from:${c.from} to:${c.to} `+i,new _({code:r,message:i,data:{message:c}})}})}_hasRiskContent(e){return 80001===e||80004===e}_isRejectedByRestApi(e){return 10100<=e&&e<=10200||120001<=e&&e<=13e4}_emitOnlineMessageSent(e){var t=e._isExcludedFromLastMessage?"":e,{conversationID:s,conversationType:r}=e,i=Bs(s)?d.TOPIC_NEW_MESSAGE:d.NEW_MESSAGE;k.notificationCenter.emitInnerEvent(i,{result:{conversationUpdateFieldList:[{conversationID:s,type:r,message:e,lastMessage:t,unreadCount:0}]}})}_applySentMessageControlInfo(e,t){t&&Su(t)&&(!0===t.excludedFromLastMessage&&(e._isExcludedFromLastMessage=!0),!0===t.excludedFromUnreadCount)&&(e._isExcludedFromUnreadCount=!0)}_logRateLimitInfo(e,t,s){e=`from:${e.from} to:${e.to} sequence:${t} messageDropReason:`+s;k.ssoLog.warn("messageDropReason",e)}_updateNickAndAvatarOfSentMessageByMe(e){var t=(k.message||{})["messageDataHandler"];let s=!1;var r,i=e["conversationID"],n=t.getLatestMsgSentByMe(i);n&&({nick:n,avatar:r}=n,s=n!==e.nick||r!==e.avatar||s)&&t.updateNickAndAvatarOfSentMessage({conversationID:i,latestNick:e.nick,latestAvatar:e.avatar,isSentByMe:!0})}_validateBeforeSendGroupMessage(i){return I(this,void 0,void 0,function*(){var{to:t,from:s}=i;let r=t,e=Bl.getGroup(r);if(Vs({groupID:r})&&null!=e&&e.isSupportTopic)throw new _({code:ls.MSG_SEND_GRP_WITH_TOPIC_FAIL});if(Bs(t)&&([r]=t.split(ns.TOPIC),e=Bl.getGroup(r)),!e&&"function"==typeof(null==(t=P.getInstance().getApiMap())?void 0:t.getGroupProfile)){let e=yield P.getInstance().getApiMap().getGroupProfile({groupID:r});if((null==(t=null==(t=null==e?void 0:e.data)?void 0:t.group)?void 0:t.type)===C.GRP_AVCHATROOM){let e=Ds({code:ls.MSG_SEND_FAIL_NOT_IN_AV,replacement1:s,replacement2:r});throw new _({code:ls.MSG_SEND_FAIL_NOT_IN_AV,message:e})}}return!0})}_reportMessageSendQuality(e){k.notificationCenter.emitInnerEvent(d.QUALITY_STAT,{label:ds.MESSAGE_SEND_SUCCESS_RATE,data:e})}}class Ru{constructor(e){this.value=e,this.next=null}}class Du{constructor(e){this.head=null,this.tail=null,this.size=0,this.capacity=e}append(e){this.size>=this.capacity&&this.removeHead();e=new Ru(e);this.head?this.tail.next=e:this.head=e,this.tail=e,this.size+=1}delete(t){if(this.head)if(this.head.value===t)this.head=this.head.next;else{let e=this.head;for(;e.next;){if(e.next.value===t)return void(e.next=e.next.next);e=e.next}}}has(e){if(!this.head)return!1;let t=this.head,s=!1;for(;t;)t.value===e&&(s=!0),t=t.next;return s}removeHead(){this.head&&(this.head===this.tail?(this.head=null,this.tail=null):this.head=this.head.next,--this.size)}peek(){var e;return null==(e=this.head)?void 0:e.value}length(){return this.size}isEmpty(){return 0===this.size}isFull(){return this.size===this.capacity}clear(){this.head=null,this.tail=null,this.size=0}}var bu=new class{constructor(){this._sparseMessagesByConversation=new Map,this._latestMessageSentByPeerMap=new Map,this._latestMessageSentByMeMap=new Map,this._randomOfSentMessageList=new Du(100)}init(){k.notificationCenter.subscribeInnerEvent(d.LOGOUT,this._reset,this),k.notificationCenter.subscribeInnerEvent(d.DESTROY,this._dispose,this)}get _messagesByConversation(){return jl.getMessages()}storeConversationMessage(e,t=!1){var s=e["conversationID"];return!!s&&(this._messagesByConversation.has(s)||this._messagesByConversation.set(s,new Map),!this._shouldSkipStoreMessage(e,t))&&(t=this._getUniqueIdOfMessage(e),this._messagesByConversation.get(s).set(t,e),this._updateLatestMessageMap(e),!0)}_updateLatestMessageMap(e){var t=e["conversationID"];"out"===e.flow?this._setLatestMsgSentByMe(t,e):t.startsWith("C2C")&&this._setLatestMsgSentByPeer(t,e)}_shouldSkipStoreMessage(e,t){var s=this._getUniqueIdOfMessage(e),r=this._messagesByConversation.get(e.conversationID);if(null!=r&&r.has(s)){let e=null==r?void 0:r.get(s);if(!t||!0===(null==e?void 0:e.isModified))return!0}return!1}deleteConversationMessage(e){var{conversationID:t=""}=e,e=this._getUniqueIdOfMessage(e);this._messagesByConversation.has(t)&&null!=(t=this._messagesByConversation.get(t))&&t.delete(e)}modifyConversationMessage(a,t){var l;if(this._messagesByConversation.has(a)||this._sparseMessagesByConversation.has(a)){let e=this._getUniqueIdOfMessage(t),o=this._getMessageFromLocalMessage(a,e);if(o){let{messageVersion:s,elements:r,cloudCustomData:i,checkResult:e=0}=t,n=1<e;if(console.log(`conversationToMessageMap modifyConversationMessage localVersion:${o.version} remoteVersion:`+s),o.version<s){let e=this._getUniqueIdOfMessage(o),t=Ke(r);return null!=(l=this._messagesByConversation.get(a))&&l.has(e)?jl.updateMessage(a,[e],{isModified:!0,version:s,_elements:t,payload:t[0].content,type:t[0].type,cloudCustomData:i,hasRiskContent:n,operation:Jt.modify}):(o.version=s,o._elements=t,o.payload=o._elements[0].content,o.type=o._elements[0].type,o.cloudCustomData=i,o.isModified=!0,o.hasRiskContent=n),{isUpdated:!0,message:o}}return{isUpdated:!1,message:o}}}return{isUpdated:!1,message:null}}_getMessageFromLocalMessage(e,s){var t;if(this._messagesByConversation.has(e))return null==(t=this._messagesByConversation.get(e))?void 0:t.get(s);if(this._sparseMessagesByConversation.has(e)){let t=[...this._sparseMessagesByConversation.get(e).values()];for(let e=0;e<t.length;e++)if(this._getUniqueIdOfMessage(t[e])===s)return t[e]}return null}findMessage(t){let s=null,e=Array.from(this._messagesByConversation.values());for(var r of e)if(s=Array.from(r.values()).find(e=>e.ID===t)||null)break;if(!s){let e=Array.from(this._sparseMessagesByConversation.values());for(var i of e)if(s=i.get(t)||null,s)break}return s}deleteConversationMessageList(e){this._messagesByConversation.has(e)&&(this._messagesByConversation.delete(e),this._latestMessageSentByMeMap.delete(e),this._latestMessageSentByPeerMap.delete(e)),this._sparseMessagesByConversation.has(e)&&this._sparseMessagesByConversation.delete(e)}revokeMessage({conversationID:t,sequence:s,random:r,revoker:i}){let e=this._messagesByConversation.get(t),n=null;if(e){var o=Array.from(e.values());if(n=this._findMessageBySequenceAndRandom({messageList:o,random:r,sequence:s})){let e=this._getUniqueIdOfMessage(n);return jl.updateMessage(t,[e],{isRevoked:!0,revoker:i,operation:Jt.revoke}),n}}if(this._sparseMessagesByConversation.has(t)){let e=Array.from(this._sparseMessagesByConversation.get(t).values());if(n=this._findMessageBySequenceAndRandom({messageList:e,random:r,sequence:s}))return n.isRevoked=!0,n.revoker=i,n}}_findMessageBySequenceAndRandom({messageList:t,sequence:s,random:r}){for(let e=0;e<t.length;e+=1){var i=t[e];if(i.sequence===s&&(G(r)||i.random===r))return i}return null}prependLocalMessageList(e){let{messageList:s,conversationID:t}=e;if(0===s.length)return[];var r=[],i=[],n=this._messagesByConversation.get(t)||new Map;for(let t of s){let e=this._getUniqueIdOfMessage(t);n.has(e)||(r.push(t),i.push([e,t]))}if(0<i.length){let e=new Map([...i,...n.entries()]);this._messagesByConversation.set(t,e),this._updateLatestMessageSentByMe(t),this._updateLatestMessageSentByPeer(t)}return r}storeSparseMessageList(r){if(0!==r.length){let e=r[0]["conversationID"],s=r.length;this._sparseMessagesByConversation.has(e)||this._sparseMessagesByConversation.set(e,new Map);var i=this._sparseMessagesByConversation.get(e);for(let t=0;t<s;t++){let e=r[t];i.has(e.ID)||i.set(e.ID,e)}}}_updateLatestMessageSentByMe(t){var e,s=Array.from((null==(e=this._messagesByConversation.get(t))?void 0:e.values())||[]);if(0!==s.length)for(let e=s.length-1;0<=e;e--)if("out"===s[e].flow){this._setLatestMsgSentByMe(t,s[e]);break}}_updateLatestMessageSentByPeer(t){var e,s=Array.from((null==(e=this._messagesByConversation.get(t))?void 0:e.values())||[]);if(0!==s.length&&t.startsWith("C2C"))for(let e=s.length-1;0<=e;e--)if("in"===s[e].flow){this._setLatestMsgSentByPeer(t,s[e]);break}}_getUniqueIdOfMessage(e){var{from:e,to:t,random:s,sequence:r,time:i}=e;return e+`-${t}-${s}-${r}-`+i}_setLatestMsgSentByPeer(e,t){this._latestMessageSentByPeerMap.set(e,t)}_setLatestMsgSentByMe(e,t){this._latestMessageSentByMeMap.set(e,t)}getLatestMsgSentByPeer(e){return this._latestMessageSentByPeerMap.get(e)}getLatestMsgSentByMe(e){return this._latestMessageSentByMeMap.get(e)}addRandomOfSentMessage(e){this._randomOfSentMessageList.append(e)}removeRandomOfSentMessage(e){this._randomOfSentMessageList.delete(e)}updateNickAndAvatarOfSentMessage(e){let{conversationID:t="",latestAvatar:n,latestNick:o,isSentByMe:s=!0}=e,r=this._messagesByConversation.get(t);if(r){let e=Array.from(r.values()),i=s?"out":"in";e.forEach(e=>{var{nick:t,avatar:s,flow:r}=e;r===i&&(t!==o&&(e.nick=o),s!==n)&&(e.avatar=n)})}}isInMessageList(e){var t=e["conversationID"];return!!t&&!!this._messagesByConversation.has(t)&&(e=this._getUniqueIdOfMessage(e),null==(t=this._messagesByConversation.get(t))?void 0:t.has(e))}isMessageSentByCurrentInstance(e){e=e.random;return this._randomOfSentMessageList.has(e)}getContinuousMessagesByConversation(){return this._messagesByConversation}getLocalMessageList(e){e=this._messagesByConversation.get(e);return e?[...e.values()]:[]}getSparseMessageList(e){e=this._sparseMessagesByConversation.get(e);return e?[...e.values()]:[]}_reset(){this._messagesByConversation.clear(),this._latestMessageSentByPeerMap.clear(),this._latestMessageSentByMeMap.clear(),this._randomOfSentMessageList.clear()}_dispose(){this._reset(),k.notificationCenter.unSubscribeInnerEvent(d.LOGOUT,this._reset,this),k.notificationCenter.unSubscribeInnerEvent(d.DESTROY,this._dispose,this)}};function Nu(e,t){var s,r,i,n,o,a,l,u=Vl.getConversation(e);null!=u&&u.lastMessage&&(u=u["lastMessage"],{lastTime:s,lastSequence:r,version:i}=u,{time:t,sequence:n,messageVersion:o,elements:a,cloudCustomData:l}=t,s===t)&&r===n&&i!==o&&(u.type=a[0].type,u.payload=a[0].content,u.messageForShow=Qs(u.type,u.payload),u.cloudCustomData=l,u.version=o,Vl.updateConversation(e,{lastMessage:u}))}class Lu{init(){P.getInstance().registerApi({apiName:"modifyMessage",context:this})}modifyMessage(u){return I(this,void 0,void 0,function*(){let{to:r,payload:t,sequence:i,conversationType:n,random:o,time:a,from:l,type:s}=u;if(this._canModifyMessageElement(s)){let e=u.getElements();1<e.length&&(e[0].type=s,e[0].content=t)}try{let t=null,s;if(n===F.CONV_C2C?t=yield function(c){return I(this,void 0,void 0,function*(){let{from:e,to:t,version:s=0,sequence:r,random:i,time:n,type:o,cloudCustomData:a}=c,l={From_Account:e,To_Account:t,MsgVersion:s,MsgSeq:r,MsgRandom:i,MsgTime:n,MsgType:o,MsgBody:c.transformElementsToServerFormat(),CloudCustomData:a},u=yield Hs({servcmd:"openim.modify_c2c_msg",data:l});if(u){let{MsgBody:e,MsgVersion:t,CloudCustomData:s}=u;return{elements:du(e),messageVersion:t,cloudCustomData:s}}})}(u):n===F.CONV_GROUP&&(t=yield function(o){return I(this,void 0,void 0,function*(){let{to:e,version:t=0,sequence:s,cloudCustomData:r}=o,i={GroupId:e,MsgVersion:t,MsgSeq:s,MsgBody:o.transformElementsToServerFormat(),CloudCustomData:r},n=yield Hs({servcmd:"openim.modify_group_msg",data:i});if(n){let{MsgBody:e,MsgVersion:t,CloudCustomData:s}=n;return{elements:du(e),messageVersion:t,cloudCustomData:s}}})}(u)),t){let e=""+n+r;return r===p()&&n===F.CONV_C2C&&(e=""+n+l),s={conversationType:n,from:l,to:r,time:a,random:o,sequence:i,elements:null==t?void 0:t.elements,cloudCustomData:null==t?void 0:t.cloudCustomData,messageVersion:null==t?void 0:t.messageVersion,conversationID:e},this._handleModifyMessageSuccess(s),{code:0,data:{message:u},successLog:{message:"to:"+r}}}}catch(e){let t=(e||{})["errorCode"];throw new _({functionName:"modifyMessage",code:t})}})}_handleModifyMessageSuccess(e){var t=e["conversationID"],{isUpdated:s,message:r}=k.message.messageDataHandler.modifyConversationMessage(t,e);!0===s&&k.notificationCenter.emitOuterEvent(Kt.MESSAGE_MODIFIED,{name:Kt.MESSAGE_MODIFIED,data:[r]}),k.notificationCenter.emitInnerEvent(d.MESSAGE_MODIFIED,{conversationID:t,message:r}),Nu(t,e)}_canModifyMessageElement(e){return[ql.MSG_TEXT,ql.MSG_CUSTOM,ql.MSG_LOCATION,ql.MSG_FACE].includes(e)}}class Pu{init(){var e=k["notificationCenter"],t=e["InnerEventSubType"];g.getInstance().registerWorkflowStep(h.RECEIVE_C2C_NEW_MESSAGE,o.HANDLE_C2C_NEW_MESSAGE,this._handleC2CMessagePush,this),g.getInstance().registerWorkflowStep(h.RECEIVE_C2C_NEW_MESSAGE,o.EMIT_C2C_MESSAGE_EVENT,this._emitMessageEventsAfterReceiveNewMessage,this),g.getInstance().registerWorkflowStep(h.SYNC_SERVER_INFO_AFTER_RE_ONLINE,o.EMIT_C2C_MESSAGE_EVENT,this._emitMessageEventsAfterSyncUnreadMessage,this),e.subscribeInnerEvent(d.MESSAGE_PUSH,t.C2C_REALTIME_MESSAGE,this._executeReceiverNewMessageWorkFlow,this),e.subscribeInnerEvent(d.MESSAGE_PUSH,t.C2C_MESSAGE_MODIFIED,this._handleC2CMessageModify,this),e.subscribeInnerEvent(d.DESTROY,this._dispose,this)}_executeReceiverNewMessageWorkFlow(e){g.getInstance().executeWorkflow(h.RECEIVE_C2C_NEW_MESSAGE,e)}_handleC2CMessagePush(e){let t=e.data||{},s=(k.message||{})["messageDataHandler"],r=[],i=new Map;return t.C2cMsgArray.forEach(e=>{e=this._generateC2CMessage(e);this._updateMessageProfile(e);let t=1===e.isModified;s.isMessageSentByCurrentInstance(e)?e.isModified=t:t=!1,e.isOnlineMessage()?(e._onlineOnlyFlag=!0,s.isMessageSentByCurrentInstance(e)||r.push(e)):_u(e)&&(s.storeConversationMessage(e)&&gu({conversationUpdateFields:i,message:e}),s.isMessageSentByCurrentInstance(e)&&!t||r.push(e))}),{conversationUpdateFieldList:[...i.values()],messages:r}}_emitMessageEventsAfterReceiveNewMessage(e){var{messages:e=[]}=(null==(e=e.result)?void 0:e[o.HANDLE_C2C_NEW_MESSAGE])||{};this._emitMessageEvents(e)}_emitMessageEventsAfterSyncUnreadMessage(e){var{messages:e=[]}=(null==(e=e.result)?void 0:e[o.UNREAD_MESSAGE_SYNC])||{};this._emitMessageEvents(e)}_emitMessageEvents(e){var t=(null==e?void 0:e.filter(e=>!0===(null==e?void 0:e.isModified)))||[],t=(0<t.length&&k.notificationCenter.emitOuterEvent("onMessageModified",{name:"onMessageModified",data:t}),null==e?void 0:e.filter(e=>!(null!=e&&e.isModified)));0<t.length&&k.notificationCenter.emitOuterEvent("onMessageReceived",{name:"onMessageReceived",data:t})}_generateC2CMessage(e){var t=F.CONV_C2C,e=lu(e),t=k.message.messageFactory.createMessage(Object.assign(Object.assign({},e),{conversationType:t,flow:xl.IN})),e=e["elements"];return t.setElement(e),t}_updateMessageProfile(r){var e;let i=(k.message||{})["messageDataHandler"],t=null==(e=k.store.get("login"))?void 0:e.userId,{from:s,nick:n,avatar:o,conversationID:a=""}=r;if(s!==t){let s=i.getLatestMsgSentByPeer(a);if(s){let{nick:e,avatar:t}=s;G(n)||G(o)?(r.nick=w(e)?e:r.nick,r.avatar=w(t)?t:r.avatar):n===e&&o===t||(i.updateNickAndAvatarOfSentMessage({conversationID:a,latestNick:n,latestAvatar:o,isSentByMe:!1}),this._updateConversationUserProfile({conversationID:a,nick:n,avatar:o}))}}else{let e=i.getLatestMsgSentByMe(a);!e||n===e.nick&&o===e.avatar||i.updateNickAndAvatarOfSentMessage({conversationID:a,latestNick:n,latestAvatar:o,isSentByMe:!0})}}_updateConversationUserProfile(e){var{conversationID:e,nick:t,avatar:s}=e,{userProfile:r={}}=Vl.getConversation(e)||{};r.avatar===s&&r.nick===t||Vl.updateConversation(e,{userProfile:Object.assign(Object.assign({},r),{nick:t,avatar:s})})}_updateMessageListDueToModify(e){var t=e["conversationID"],{isUpdated:s,message:r}=k.message.messageDataHandler.modifyConversationMessage(t,e);!0===s&&k.notificationCenter.emitOuterEvent("onMessageModified",{name:"onMessageModified",data:[r]}),k.notificationCenter.emitInnerEvent("ModifyMessageSuccess",e),Nu(t,e)}_handleC2CMessageModify(e){e.C2cMsgModNotifys.forEach(e=>{var t=F.CONV_C2C,e=uu(e),{to:s,from:r}=e;let i=""+t+s;s===(null==(s=k.store.get("login"))?void 0:s.userId)&&(i=""+t+r),e=Object.assign({conversationType:t,conversationID:i},e),this._updateMessageListDueToModify(e)})}_dispose(){var e=k["notificationCenter"],e=e["InnerEventSubType"];k.notificationCenter.unSubscribeInnerEvent(d.MESSAGE_PUSH,e.C2C_REALTIME_MESSAGE,this._handleC2CMessagePush,this),k.notificationCenter.unSubscribeInnerEvent(d.MESSAGE_PUSH,e.C2C_MESSAGE_MODIFIED,this._handleC2CMessageModify,this),k.notificationCenter.unSubscribeInnerEvent(d.DESTROY,this._dispose,this)}}class Gu{init(){var e=k["notificationCenter"],t=e["InnerEventSubType"];g.getInstance().registerWorkflowStep(h.RECEIVE_GROUP_NEW_MESSAGE,o.HANDLE_GROUP_NEW_MESSAGE,this._handleGroupMessagePush,this),g.getInstance().registerWorkflowStep(h.RECEIVE_GROUP_NEW_MESSAGE,o.EMIT_GROUP_MESSAGE_EVENT,this._emitMessageEvents,this),e.subscribeInnerEvent(d.MESSAGE_PUSH,t.GROUP_REALTIME_MESSAGE,this._executeReceiverNewMessageWorkFlow,this),e.subscribeInnerEvent(d.MESSAGE_PUSH,t.GROUP_MESSAGE_MODIFIED,this._handleGroupMessageModify,this),e.subscribeInnerEvent(d.DESTROY,this._dispose,this)}_executeReceiverNewMessageWorkFlow(e){this._canExecuteReceiverNewMessageWorkFlow(e)&&g.getInstance().executeWorkflow(h.RECEIVE_GROUP_NEW_MESSAGE,e)}_handleGroupMessagePush(e){let t=e.data||{},s=k.message["messageDataHandler"],r=[],i=new Map,n=null==t?void 0:t.GroupMsgArray;return null!=n&&n.forEach(e=>{var t;1!==e.GroupInfo.NotVisible&&(e=this._generateGroupMessage(e),this.updateMessageProfile(e),t=1===e.isModified,s.isMessageSentByCurrentInstance(e)&&(e.isModified=t),e.isOnlineMessage()?(e._onlineOnlyFlag=!0,s.isMessageSentByCurrentInstance(e)||r.push(e)):_u(e)&&s.storeConversationMessage(e)&&(r.push(e),gu({conversationUpdateFields:i,message:e})))}),{conversationUpdateFieldList:[...i.values()],messages:r}}_emitMessageEvents(e){var e=((null==(e=e.result)?void 0:e[o.HANDLE_GROUP_NEW_MESSAGE])||{})["messages"],t=(null==e?void 0:e.filter(e=>!0===(null==e?void 0:e.isModified)))||[],t=(0<t.length&&k.notificationCenter.emitOuterEvent("onMessageModified",{name:"onMessageModified",data:t}),(null==e?void 0:e.filter(e=>!(null!=e&&e.isModified)))||[]);0<t.length&&k.notificationCenter.emitOuterEvent("onMessageReceived",{name:"onMessageReceived",data:t})}_generateGroupMessage(e){var t=F.CONV_GROUP,e=cu(e),t=k.message.messageFactory.createMessage(Object.assign(Object.assign({},e),{conversationType:t,flow:xl.IN})),e=e["elements"];return t.setElement(e),t}updateMessageProfile(i){var e;let t=(k.message||{})["messageDataHandler"],s=null==(e=k.store.get("login"))?void 0:e.userId,{from:r,nick:n,avatar:o,conversationID:a="",_elements:l}=i;if(r===s){let e=t.getLatestMsgSentByMe(a);!e||n===e.nick&&o===e.avatar||t.updateNickAndAvatarOfSentMessage({conversationID:a,latestNick:n,latestAvatar:o,isSentByMe:!0})}else if(r===C.CONV_SYSTEM){let{operationType:e,memberInfoList:t,operatorInfo:s}=l,r={};if(je(t)?je(s)||(r=s):[os.JOINED,os.KICKED,os.ADMIN_SET,os.ADMIN_CANCELED].includes(e)&&(r=Object.assign({},t[0])),!je(r)){let{nick:e="",avatar:t=""}=r;i.nick=e,i.avatar=t}}}_updateMessageListDueToModify(e){var t=e["conversationID"],{isUpdated:s,message:r}=k.message.messageDataHandler.modifyConversationMessage(t,e);!0===s&&k.notificationCenter.emitOuterEvent("onMessageModified",{name:"onMessageModified",data:[r]}),Nu(t,e)}_handleGroupMessageModify(e){e.GroupMsgModNotifys.forEach(e=>{var t=F.CONV_GROUP,{topicID:s,groupID:r}=e=hu(e),s=s||r,e=Object.assign({conversationType:t,conversationID:""+t+s,to:s},e);this._updateMessageListDueToModify(e)})}_dispose(){var e=k["notificationCenter"],{GROUP_REALTIME_MESSAGE:t,GROUP_MESSAGE_MODIFIED:s}=e["InnerEventSubType"];e.unSubscribeInnerEvent(d.MESSAGE_PUSH,t,this._handleGroupMessagePush,this),e.unSubscribeInnerEvent(d.MESSAGE_PUSH,s,this._handleGroupMessageModify,this),e.unSubscribeInnerEvent(d.DESTROY,this._dispose,this)}_canExecuteReceiverNewMessageWorkFlow(e){var{GroupId:e,GroupType:t}=(null==(e=null==(e=null==e?void 0:e.GroupMsgArray)?void 0:e[0])?void 0:e.GroupInfo)||{},t=t===is.GRP_AVCHATROOM;return!(!Bl.getGroup(e)&&t)}}var wu=new class{constructor(){this.c2cMessageReceiver=new Pu,this.groupMessageReceiver=new Gu}init(){this.c2cMessageReceiver.init(),this.groupMessageReceiver.init()}};let Uu={createCustomMessage:{to:{required:!0,rules:["string"],allowEmpty:!1},conversationType:{required:!0,rules:["string"],allowEmpty:!1},payload:{required:!0,rules:["object"],allowEmpty:!1},cloudCustomData:{required:!1,rules:["string"],allowEmpty:!1},priority:{required:!1,rules:["string"],allowEmpty:!1},customModerationConfigurationID:{required:!1,rules:["string"],allowEmpty:!1}},sendMessage:[{key:"message",required:!0,rules:["object"],allowEmpty:!1},{key:"options",required:!1,rules:["object"],allowEmpty:!1}],createTextMessage:{to:{required:!0,rules:["string"],allowEmpty:!1},conversationType:{required:!0,rules:["string"],allowEmpty:!1,customValidator:e=>!(!e.startsWith("C2C")&&!e.startsWith("GROUP"))||"conversationType is invalid."},payload:{required:!0,rules:["object"],allowEmpty:!1,customValidator:e=>{return"string"==typeof(null==e?void 0:e.text)&&("string"!=typeof e.text||0!==(null==(e=null==e?void 0:e.text)?void 0:e.length))||"payload.text must be a string"}}}},ku={createCustomMessage:!0,sendMessage:!0,modifyMessage:!0};var Fu=new class{getGroupRoamingMessagesByAnchor(i){return I(this,void 0,void 0,function*(){try{var{conversationID:t,count:s,direction:l,sequence:u,messageSequenceList:e,getType:r}=i,c=t.replace(ts.CONV_GROUP,""),d=[];let a=u;if(l===Wt.BACKWARD){if("number"!=typeof u)return{messageList:[],hasNoMoreHistoryMessage:!1,nextReqMessageIDFromServer:""};a=u+s-1}var h=yield function(n){return I(this,void 0,void 0,function*(){var{groupID:e,count:t,messageSequence:s,messageSequenceList:r,getType:i}=n,e={GroupId:e,ReqMsgNumber:t,WithRecalledMsg:1,Version:1,GetType:i};return s&&(e.ReqMsgSeq=s),q(r)&&0<r.length&&(e.ReqMsgSeqList=r),yield Hs({servcmd:"group_open_http_svc.group_msg_get",data:e})})}({groupID:c,count:s,messageSequence:a,messageSequenceList:e,getType:r});if(h){let{RspMsgList:s=[],NextReqMsgSeq:e=0,IsFinished:t,InvisibleMsgSeq:r}=h,i=`groupID:${c} sequence:${u} reqSeq:${a} direction:${l} complete:${t} nextSequence:${e} remoteMsgCount:${s.length} invisibleSequenceList:`+r,n=[];for(let t=0;t<s.length;t++){var g=s[t];g.From_Account===C.CONV_SYSTEM&&d.push(g);let e=this._parseMessage(g);n.push(e)}n.reverse();let o=2===t;l===Wt.BACKWARD&&(o=n[n.length-1].sequence>=u);var p=pu(n);return k.ssoLog.info("getGroupRoamingMessagesByAnchor",i),{messageList:p,invisibleSequenceList:r,nextReqMessageIDFromServer:e,hasNoMoreHistoryMessage:o,serverGroupTipList:d}}}catch(e){var{errorCode:t,errorInfo:s}=e||{};throw new _({code:t,message:s})}})}_parseMessage(e){var t=ts.CONV_GROUP,e=(4===e.Event&&(e.MsgBody.MsgType=C.MSG_GRP_TIP),cu(e)),t=su.createMessage(Object.assign(Object.assign({},e),{conversationType:t,flow:"in"}));return t.setElement(e.elements),t}};class qu{constructor(){this.messageHelper=mu,this.messageFactory=su,this.messageSender=new Tu,this.messageAction=new Lu,this.messageReceiver=wu,this.messageDataHandler=bu,this.messageHistory=Fu,this.messageSender.init(),this.messageFactory.init(),this.messageAction.init(),this.messageReceiver.init(),this.messageDataHandler.init(),Fs({auth:ku,params:Uu})}}let xu="Tag_Profile_IM_",Vu={NICK:xu+"Nick",GENDER:xu+"Gender",BIRTHDAY:xu+"BirthDay",LOCATION:xu+"Location",SELFSIGNATURE:xu+"SelfSignature",ALLOWTYPE:xu+"AllowType",LANGUAGE:xu+"Language",AVATAR:xu+"Image",MESSAGESETTINGS:xu+"MsgSettings",ADMINFORBIDTYPE:xu+"AdminForbidType",LEVEL:xu+"Level",ROLE:xu+"Role"},Bu="Tag_Profile_Custom",ju="profileCustomField",Ku={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:[]},Hu=new Map([[Vu.NICK,"nick"],[Vu.GENDER,"gender"],[Vu.BIRTHDAY,"birthday"],[Vu.LOCATION,"location"],[Vu.SELFSIGNATURE,"selfSignature"],[Vu.ALLOWTYPE,"allowType"],[Vu.LANGUAGE,"language"],[Vu.AVATAR,"avatar"],[Vu.MESSAGESETTINGS,"messageSettings"],[Vu.ADMINFORBIDTYPE,"adminForbidType"],[Vu.LEVEL,"level"],[Vu.ROLE,"role"]]);var Wu=new class{createProfile(e,t){let s={userID:e,profileCustomField:[]};return t.forEach(e=>{var{tag:e,value:t}=e;e&&-1<e.indexOf(Bu)?s.profileCustomField.push({key:e,value:t}):Hu.has(e)&&(s[Hu.get(e)]=t)}),Object.assign(Object.assign({},Ku),s)}parseProfileItem(e=[]){let t=[];return e.forEach(e=>{t.push({tag:e.Tag,value:e.Value})}),t}parseProfileList(e=[]){let t=[];return e.forEach(e=>{t.push({tag:e.Tag,value:e.ValueBytes})}),t}convertParamsToProfile(t){let s=[];return Object.keys(t).forEach(e=>{e!==ju&&s.push({tag:Vu[e.toUpperCase()],value:t[e]})}),t.profileCustomField&&q(t.profileCustomField)&&t.profileCustomField.forEach(e=>{s.push({tag:e.key,value:e.value})}),s}normalizeProfileFields(e){let r={},i=[];return e.forEach(e=>{var{tag:t,value:s}=e;if(t&&-1<t.indexOf(Bu)&&i.push({key:t,value:s}),Hu.has(t)&&void 0!==s){let e=Hu.get(t);r[e]=s}}),0<i.length&&(r.profileCustomField=i),r}};let Yu=k.common["generateProtocolData"];function $u(r){return I(this,void 0,void 0,function*(){let e="profile.portrait_get_all",t={From_Account:p(),UserItem:[]};r.forEach(e=>{t.UserItem.push({CustomSequence:0,StandardSequence:0,To_Account:e})});var n=Yu({servcmd:e,data:t}),s=n.head.seq+e,n=yield k.channel.sendPacket(n,{requestId:s});if(n){let{ActionStatus:e,ErrorCode:t,ErrorDisplay:s,ErrorInfo:r,UserProfileItem:i}=n,o=[];return i.map(e=>{var{To_Account:e,CustomSequence:t,ResultCode:s,ResultInfo:r,StandardSequence:i,ProfileItem:n}=e,n=Wu.parseProfileItem(n);o.push({userId:e,customSequence:t,resultCode:s,resultInfo:r,standardSequence:i,profileItem:n})}),{actionStatus:e,errorCode:t,errorDisplay:s,errorInfo:r,userProfile:o}}})}function zu(e){return Kl.getFriendMap().has(e)}let Ju=k.utils["isEmpty"];class Qu{constructor(){this._strangerProfileMap=new Map}init(){P.getInstance().registerApi({apiName:"getMyProfile",context:this}),P.getInstance().registerApi({apiName:"getUserProfile",context:this}),P.getInstance().registerApi({apiName:"updateMyProfile",context:this}),this.createProfile=Wu.createProfile.bind(Wu);var e=k["notificationCenter"];g.getInstance().registerWorkflowStep(h.SYNC_SERVER_INFO_AFTER_LOGIN,o.USER_PROFILE_SYNC,this.getMyProfileCacheThenServer,this),e.subscribeInnerEvent(d.MESSAGE_PUSH,e.InnerEventSubType.PROFILE_MODIFIED,this._onProfileDataModify,this),e.subscribeInnerEvent(d.LOGOUT,this._reset,this),e.subscribeInnerEvent(d.DESTROY,this._dispose,this)}getMyProfile(){return I(this,void 0,void 0,function*(){try{var e,t=p(),s=yield $u([t]);if(s)return e=this._handleProfileFormResponse(s)[0],Kl.getUserProfileMap().set(t,e),{code:0,data:e}}catch(e){var{errorCode:s,errorInfo:t}=e;throw new _({functionName:"getMyProfile",code:s,message:t})}})}getUserProfile(l){return I(this,void 0,void 0,function*(){try{var t=l["userIDList"],{userIdListToRequest:e,profileFromCache:s}=this._filterRequestAndCacheUsers(t);if(0===e.length)return{code:0,data:s,successLog:{message:"userIDList.length:"+t.length}};1e3<e.length&&(k.ssoLog.warn("getUserProfile","userIdListToRequest.length > 1000"),e.length=1e3);var{data:r,error:i}=yield this._batchFetchUserProfiles(e),n=e.length,o=r.length,a=n-o;if(0===s.length&&n===a&&!Ju(i))throw i;if(q(r)){r.forEach(e=>{(zu(e.userID)?Kl.getUserProfileMap():this._strangerProfileMap).set(e.userID,e)});let e=r.concat(s);return{code:0,data:e,successLog:{message:`getUserProfile query:${n} success:${o} fail:${a} from cache:`+s.length}}}}catch(e){t=e["errorCode"];throw new _({functionName:"getUserProfile",code:t})}})}getMyProfileCacheThenServer(){return I(this,void 0,void 0,function*(){var e=p(),e=Kl.getUserProfileMap().has(e);return e?{code:0,data:e}:this.getMyProfile()})}updateMyProfile(a){return I(this,void 0,void 0,function*(){let t=p(),s={};for(let e in a)void 0!==a[e]&&(s[e]=a[e]);var r=Wu.convertParamsToProfile(s);try{let e={From_Account:t,ProfileItem:r};yield function(r){return I(this,void 0,void 0,function*(){let e="profile.portrait_set",t=Yu({servcmd:e,data:r}),s=""+t.head.seq+e,i=yield k.channel.sendPacket(t,{requestId:s});if(i){let{ActionStatus:e,ErrorCode:t,ErrorDisplay:s,ErrorInfo:r}=i;return{actionStatus:e,errorCode:t,errorDisplay:s,errorInfo:r}}})}(e);var i=Kl.getUserProfile(t),n=i?Object.assign(Object.assign({},i),s):Wu.createProfile(t,r),o=!jt(i,n,["lastUpdatedTime"]);return n.lastUpdatedTime=Date.now(),Kl.getUserProfileMap().set(t,n),o&&this._emitProfileUpdated(n),{code:0,data:n,successLog:{message:"profileArray: "+k.utils.safeStringify(r)}}}catch(e){let{errorCode:t,errorInfo:s}=e;throw new _({functionName:"updateMyProfile",code:t,message:s})}})}updateMyNickAndAvatar(i){return I(this,void 0,void 0,function*(){var e=p(),t=Date.now(),s=Kl.getUserProfile(e),r={};(r=s?Object.assign(s,i):Wu.createProfile(e,i)).lastUpdatedTime=t,Kl.getUserProfileMap().set(e,r)})}_onProfileDataModify(r){var e,t=function(){var{Profile_Account:e,PushType:t,ProfileList:s}=r.ProfileDataMod[0];return{userId:e,pushType:t,profileList:Wu.parseProfileList(s)}}();Ju(t)||({isProfileUpdated:t,profile:e}=this._handleProfileModified(t),t&&this._emitProfileUpdated(e))}_emitProfileUpdated(e){k.notificationCenter.emitInnerEvent(d.PROFILE_UPDATE,{name:d.PROFILE_UPDATE,data:[e]}),k.notificationCenter.emitOuterEvent(Kt.PROFILE_UPDATED,{name:Kt.PROFILE_UPDATED,data:[e]}),Vl.updateConversation("C2C"+(null==e?void 0:e.userID),{userProfile:e})}_dispose(){var e=k["notificationCenter"];e.unSubscribeInnerEvent(d.LOGOUT,this._reset,this),e.unSubscribeInnerEvent(d.MESSAGE_PUSH,e.InnerEventSubType.PROFILE_MODIFIED,this._onProfileDataModify,this),e.unSubscribeInnerEvent(d.DESTROY,this._dispose,this),this._reset()}_handleProfileModified(e){let{userId:t,profileList:s}=e,r=Kl.getUserProfile(t);if(!(p()===t||zu(t)&&r))return{isProfileUpdated:!1,profile:null};let i=Wu.normalizeProfileFields(s),n=Object.keys(i).some(e=>e===ju?!jt(r.profileCustomField,i.profileCustomField):r[e]!==i[e]);return n?(e=Date.now(),e=Object.assign(Object.assign(Object.assign({},r),i),{lastUpdatedTime:e}),Kl.getUserProfileMap().set(t,e),{isProfileUpdated:n,profile:e}):{isProfileUpdated:!1,profile:r}}_filterRequestAndCacheUsers(e){let s=[],r=[];return e.forEach(e=>{var t=Kl.getUserProfileMap().has(e);zu(e)&&t?r.push(Kl.getUserProfile(e)):this._isStrangerAndProfileValid(e)?r.push(this._strangerProfileMap.get(e)):s.push(e)}),{userIdListToRequest:s,profileFromCache:r}}_handleProfileFormResponse(e){e=e.userProfile;if(!Array.isArray(e))return[];let t=e.filter(e=>"@TLS#NOT_FOUND"!==e.userId&&""!==e.userId&&!Ju(e.profileItem)),s=Date.now();return t.map(e=>{e=Wu.createProfile(e.userId,e.profileItem);return e.lastUpdatedTime=s,e})}_isStrangerAndProfileValid(e){var t;return!zu(e)&&({lastUpdatedTime:e=0}=this._strangerProfileMap.get(e)||{},t=(null==(t=k.store.get("cloudConfig"))?void 0:t.stranger_profile_expiration_time)||6e5,Date.now()-e<=t)}_chunkUserIDList(s,r){return Array.from({length:Math.ceil(s.length/r)},(e,t)=>s.slice(t*r,(t+1)*r))}_batchFetchUserProfiles(e){return I(this,void 0,void 0,function*(){let t=[],r=[],i={};return this._chunkUserIDList(e,100).forEach(e=>{t.push($u(e))}),(yield Promise.allSettled(t)).forEach(s=>{if("fulfilled"===s.status){let e=s.value,t=this._handleProfileFormResponse(e);q(t)&&r.push(...t)}else if("rejected"===s.status){let{code:e,message:t}=s.reason||{};i={errorCode:e,message:t}}}),{data:r,error:i}})}_reset(){Kl.getUserProfileMap().clear(),this._strangerProfileMap.clear()}}var Xu,Zu,ec,tc=new Map,sc=["0","1","2","3","4","5","6","7","8","9","A","B","C","D","E","F"];for(let e=0,t=sc.length;e<t;e++)tc.set(e,sc[e]);function rc(e){if(!e)return"";var i=String(e).replace(/[=]+$/,"");let n="";if(i.length%4==1)return"";for(let e,t,s=0,r=0;t=i.charAt(r++);~t&&(e=s%4?64*e+t:t,s++%4)&&(n+=String.fromCharCode(255&e>>(-2*s&6))))t="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=".indexOf(t);try{return decodeURIComponent(escape(n))}catch(e){return console.warn(e),""}}let ic=k.utils["isEmpty"],nc=k.common["generateProtocolData"];function oc(i){return I(this,void 0,void 0,function*(){var e,t,s="im_open_status.ws_get_user_status",r=nc({servcmd:s,data:{To_Account:i}}),s=r.head.seq+s,r=yield k.channel.sendPacket(r,{requestId:s});if(r)return{ErrorCode:s,ErrorInfo:r,ErrorList:e=[],UserStatusList:t=[]}=r,{errorCode:s,errorInfo:r,successUserList:t.map(e=>{var{To_Account:e,Status:t,CustomStatus:s}=e;return{userID:e,statusType:t,customStatus:rc(s)}}),failureUserList:e.map(e=>{var{To_Account:e,Invalid_Account:t,ErrorCode:s,ErrorInfo:r}=e;return{userID:ic(t)?e:t,code:s,message:r}})}})}class ac{constructor(){this._customStatus=""}init(){var e=k["notificationCenter"];P.getInstance().registerApi({apiName:"getUserStatus",context:this}),P.getInstance().registerApi({apiName:"setSelfStatus",context:this}),P.getInstance().registerApi({apiName:"subscribeUserStatus",context:this}),P.getInstance().registerApi({apiName:"unsubscribeUserStatus",context:this}),g.getInstance().registerWorkflowStep(h.SYNC_SERVER_INFO_AFTER_RE_ONLINE,o.USER_STATUS_UPDATE,this._onReOnline,this),e.subscribeInnerEvent(d.MESSAGE_PUSH,e.InnerEventSubType.USER_STATUS_UPDATE,this._onUserStatusUpdate,this),e.subscribeInnerEvent(d.LOGOUT,this._reset,this),e.subscribeInnerEvent(d.DESTROY,this._dispose,this)}setSelfStatus(s){return I(this,void 0,void 0,function*(){let e=p(),t=s["customStatus"];try{return yield function(i){return I(this,void 0,void 0,function*(){let e="im_open_status.ws_set_custom_status",t=nc({servcmd:e,data:{CustomStatus:i}}),s=""+t.head.seq+e,r=yield k.channel.sendPacket(t,{requestId:s});if(r){let{ErrorCode:e,ErrorInfo:t}=r;return{errorCode:e,errorInfo:t}}})}(t),this._customStatus=t,{code:0,data:{userID:e,statusType:1,customStatus:t},successLog:{message:"customStatus: "+t}}}catch(e){let{errorCode:t,errorInfo:s}=e;throw new _({functionName:"setSelfStatus",code:t,message:s})}})}getUserStatus(s){return I(this,void 0,void 0,function*(){var{userIDList:e=[]}=s;let t={};return this._isOnlyMeInArray(e)&&(t=this._getMyStatus()),t=yield this._getUserStatus(e),Object.assign(Object.assign({},t),{successLog:{message:"userIDList length: "+e.length}})})}setCustomStatus(e){e=rc(e);this._customStatus=e}subscribeUserStatus(i){return I(this,void 0,void 0,function*(){try{var{userIDList:e=[]}=i,t=(this._checkBusinessCapabilityBits("subscribeUserStatus"),this._getMaxUserCount("subscribe")),s=yield function(r){return I(this,void 0,void 0,function*(){var e=k["channel"],t="im_open_status.ws_status_subscribe",s=nc({servcmd:t,data:{To_Account:r}}),t=s.head.seq+t;return yield e.sendPacket(s,{requestId:t})})}(this._sliceUserIDList(e,t)),r=this._parseResponse(s);return{code:0,data:{failureUserList:r},successLog:{message:`userID length:${e.length} failCount: `+r.length}}}catch(e){t=e["errorCode"];throw new _({functionName:"subscribeUserStatus",code:t})}})}unsubscribeUserStatus(i){return I(this,void 0,void 0,function*(){try{this._checkBusinessCapabilityBits("unsubscribeUserStatus");var{userIDList:e=[]}=i,t=this._getMaxUserCount("unsubscribe"),s=yield function(r){return I(this,void 0,void 0,function*(){var e=k["channel"],t="im_open_status.ws_status_unsubscribe",s=0===r.length?{UnsubscribeAll:1}:{To_Account:r},s=nc({servcmd:t,data:s}),t=s.head.seq+t;return yield e.sendPacket(s,{requestId:t})})}(this._sliceUserIDList(e,t)),r=this._parseResponse(s);return{code:0,data:{failureUserList:r},successLog:{message:`userID length:${e.length} failCount: `+r.length}}}catch(e){t=e["errorCode"];throw new _({functionName:"unsubscribeUserStatus",code:t})}})}_onUserStatusUpdate(e){var{UserStatusList:e=[]}=e||{},e=e.map(e=>{var{To_Account:e,Status:t,CustomStatus:s}=e;return{userID:e,statusType:t,customStatus:rc(s)}});this._emitUserStatusUpdatedEvent(e)}_onReOnline(e){var e=rc(e.data.customStatus);this._customStatus!==e&&(this._customStatus=e,e={userID:p(),statusType:1,customStatus:e},this._emitUserStatusUpdatedEvent(e))}_emitUserStatusUpdatedEvent(e){k.notificationCenter.emitOuterEvent(Kt.USER_STATUS_UPDATED,{name:Kt.USER_STATUS_UPDATED,data:e})}_sliceUserIDList(e,t){return e.slice(0,t)}_parseResponse(e){var{ErrorList:e=[]}=e;return e.map(e=>{var{To_Account:e,Invalid_Account:t,ErrorCode:s,ErrorInfo:r}=e;return{userID:k.utils.isEmpty(t)?e:t,code:s,message:r}})}_checkBusinessCapabilityBits(e){if(!k.store.get("commercialConfig").get("USER_STATUS"))throw new _({functionName:e,code:ls.NO_USE,replacement1:e})}_getMaxUserCount(e){var t=k.store.get("cloudConfig")||{},{key:e,default:s}={query:{key:"status_query_count",default:500},subscribe:{key:"status_sub_count",default:100},unsubscribe:{key:"status_unsub_count",default:100}}[e],t=t[e]||s;return parseInt(t,10)}_getMyStatus(){return{code:0,data:{successUserList:[{userID:p(),statusType:1,customStatus:this._customStatus}],failureUserList:[]}}}_getUserStatus(r){return I(this,void 0,void 0,function*(){try{this._checkBusinessCapabilityBits("getUserStatus");var t=this._getMaxUserCount("query"),{successUserList:e,failureUserList:s}=(yield oc(this._sliceUserIDList(r,t)))||{};return{code:0,data:{successUserList:e,failureUserList:s}}}catch(e){t=e["errorCode"];throw new _({functionName:"getUserStatus",code:t})}})}_isOnlyMeInArray(e){var t=p();return 1===e.length&&-1<e.indexOf(t)}_dispose(){var e=k["notificationCenter"];e.unSubscribeInnerEvent(d.MESSAGE_PUSH,e.InnerEventSubType.USER_STATUS_UPDATE,this._onUserStatusUpdate,this),e.unSubscribeInnerEvent(d.DESTROY,this._dispose,this),e.unSubscribeInnerEvent(d.LOGOUT,this._reset,this),this._reset()}_reset(){this._customStatus=""}}let lc={getUserProfile:{userIDList:{required:!0,rules:["array"],allowEmpty:!1}},updateMyProfile:{nick:{required:!1,rules:["string"],allowEmpty:!0},avatar:{required:!1,rules:["string"],allowEmpty:!0},gender:{required:!1,rules:["string"],allowEmpty:!0},selfSignature:{required:!1,rules:["string"],allowEmpty:!0},allowType:{required:!1,rules:["string"],allowEmpty:!0},birthday:{required:!1,rules:["number"],allowEmpty:!1},language:{required:!1,rules:["string"],allowEmpty:!0},messageSettings:{required:!1,rules:["string"],allowEmpty:!0},adminForbidType:{required:!1,rules:["string"],allowEmpty:!0},level:{required:!1,rules:["number"],allowEmpty:!1},role:{required:!1,rules:["number"],allowEmpty:!0},profileCustomField:{required:!1,rules:["array"],allowEmpty:!0,customValidator:function(e){for(var t of e){if("object"!=typeof t)return"Each item in profileCustomField must be an object";if("string"!=typeof(null==t?void 0:t.key))return"Each item.key in profileCustomField must be a string";if(null==t||!t.key.startsWith(Bu))return'Each item.key in profileCustomField must start with "Tag_Profile_Custom"'}return!0}}},setSelfStatus:{customStatus:{required:!0,rules:["string"],allowEmpty:!0}},getUserStatus:{userIDList:{required:!0,rules:["array"],allowEmpty:!1}},subscribeUserStatus:{userIDList:{required:!0,rules:["array"],allowEmpty:!1}},unsubscribeUserStatus:{userIDList:{required:!1,rules:["array"],allowEmpty:!0}}},uc={getMyProfile:!0,getUserProfile:!0,updateMyProfile:!0,setSelfStatus:!0,getUserStatus:!0,subscribeUserStatus:!0,unsubscribeUserStatus:!0};class cc{constructor(){this.userProfile=new Qu,this.userStatus=new ac,this.userProfile.init(),this.userStatus.init(),Fs({auth:uc,params:lc})}}function dc(t){var s=[];if(w(t)){var r=t.length;if(0!==r)for(let e=r-1;0<=e;e--)"1"===t[e]&&s.push(2**(r-e-1))}return s}(m=Xu=Xu||{}).NOT_START="notStart",m.PENDING="pending",m.RESOLVED="resolved",m.REJECTED="rejected",(L=Zu=Zu||{})[L.C2C=1]="C2C",L[L.GROUP=2]="GROUP",(S=ec=ec||{})[S.C2C=8]="C2C",S[S.GROUP=2]="GROUP";class hc{constructor(){this._name="SyncConversationHandler",this._pagingStatus=Xu.NOT_START,this._pagingTimeStamp=0,this._pagingStartIndex=0,this._pagingPinnedTimeStamp=0,this._pagingPinnedStartIndex=0}init(){var e=k["notificationCenter"];g.getInstance().registerWorkflowStep(h.SYNC_SERVER_INFO_AFTER_RE_ONLINE,o.CONVERSATION_RECOVER,this._syncConversationList,this),g.getInstance().registerWorkflowStep(h.SYNC_SERVER_INFO_AFTER_LOGIN,o.CONVERSATION_LIST_SYNC,this._syncConversationListAfterLogin,this),e.subscribeInnerEvent(d.LOGOUT,this._reset,this),e.subscribeInnerEvent(d.DESTROY,this._dispose,this),k.ssoLog.debug(this._name+".init")}isSyncCompleted(){return this._pagingStatus===Xu.RESOLVED}_syncConversationListAfterLogin(){return I(this,void 0,void 0,function*(){return this._pagingStatus=Xu.NOT_START,this._pagingTimeStamp=0,this._pagingStartIndex=0,this._pagingPinnedTimeStamp=0,this._pagingPinnedStartIndex=0,this._syncConversationList()})}_syncConversationList(){return I(this,void 0,void 0,function*(){let{ssoLog:t,utils:{safeStringify:s}}=k;t.debug("_syncConversationList","start");try{let e=yield this._pagingGetConversationList(!0);this._pagingStatus=Xu.RESOLVED;var{conversationList:r=[]}=e||{};return t.info("_syncConversationList","success count:"+r.length),e}catch(e){var{errorCode:r,errorInfo:i}=e,r=new _({code:r,message:i});t.error("_syncConversationList","fail "+s(e),{error:r})}})}_pagingGetConversationList(c){return I(this,void 0,void 0,function*(){try{var e,t=[],s=(this._pagingStatus=Xu.PENDING,yield function(n){return I(this,void 0,void 0,function*(){var{fromAccount:e,pagingTimeStamp:t,pagingStartIndex:s,pagingPinnedTimeStamp:r,pagingPinnedStartIndex:i}=n;return Hs({servcmd:"recentcontact.page_get",data:{AssistFlags:31,MsgAssistFlags:15,OrderType:1,From_Account:e,StartIndex:s,TimeStamp:t,TopStartIndex:i,TopTimeStamp:r}})})}({fromAccount:p(),pagingTimeStamp:c?this._pagingTimeStamp:0,pagingStartIndex:c?this._pagingStartIndex:0,pagingPinnedTimeStamp:c?this._pagingPinnedTimeStamp:0,pagingPinnedStartIndex:c?this._pagingPinnedStartIndex:0})),{CompleteFlag:r,SessionItem:i=[],TimeStamp:n,StartIndex:o,TopTimeStamp:a,TopStartIndex:l}=s||{};if(0<i.length){let e=this._getConversationOptions(i);t.push(...e);var u=k["notificationCenter"];u.emitInnerEvent(d.SYNC_CONVERSATION_LIST,{conversationUpdateFieldList:e})}return this._pagingTimeStamp=n,this._pagingStartIndex=o,this._pagingPinnedTimeStamp=a,this._pagingPinnedStartIndex=l,1!==r&&(e=(yield this._pagingGetConversationList(c))["conversationList"],t.push(...e)),{conversationList:t}}catch(e){throw e}})}_getConversationOptions(e){let{isUndefined:t}=k["utils"],s=this._convertConversationKey(e);return this._filterValidConversations(s).map(e=>(t(e.lastMsg)&&(e.lastMsg={elements:[]}),e.type===Zu.C2C?this._assembleC2COption(e):this._assembleGroupOption(e)))}_filterValidConversations(e){return e.filter(({type:e,userID:t})=>e===Zu.C2C&&!function(e){let t;return"@TLS#ERROR"===(t=e.startsWith(C.CONV_C2C)?e.replace(C.CONV_C2C,""):t)||"@TLS#NOT_FOUND"===t}(t)||2===e)}_assembleC2COption(e){var t,s=this._createUserprofile(e);return{conversationID:""+C.CONV_C2C+e.userID,type:C.CONV_C2C,lastMessage:{lastTime:e.time,lastSequence:e.sequence,fromAccount:e.lastC2CMsgFromAccount,type:null!=(t=e.lastMsg)&&t.elements[0]?null==(t=e.lastMsg)?void 0:t.elements[0].type:null,payload:null!=(t=e.lastMsg)&&t.elements[0]?this._amendLayersOverLimitProp(e.lastMsg.elements[0].content):null,cloudCustomData:(null==(t=e.lastMsg)?void 0:t.cloudCustomData)||"",isRevoked:e.lastMessageFlag===ec.C2C,onlineOnlyFlag:!1,nick:"",nameCard:"",version:0,isPeerRead:this._computeIsPeerRead(e),revoker:(null==(t=null==(t=e.lastMsg)?void 0:t.revokerInfo)?void 0:t.revoker)||null},unreadCount:0,userProfile:s,peerReadTime:e.peerReadTime,isPinned:1===e.isPinned,customData:e.customMark||"",markList:dc(e.standardMark),conversationGroupList:[],remark:e.friendRemark||"",messageRemindType:this._transMsgRemindType(e.messageRemindType)}}_createUserprofile(e){var{userID:e,nick:t,peerAvatar:s}=e,t=[{tag:"Tag_Profile_IM_Nick",value:t},{tag:"Tag_Profile_IM_Image",value:s}];return null==(s=k.user.userProfile)?void 0:s.createProfile(e,t)}_computeIsPeerRead(e){var{lastC2CMsgFromAccount:e,time:t,c2cPeerReadTime:s}=e;return e===p()&&t<=s}_assembleGroupOption(e){var t;return{conversationID:""+C.CONV_GROUP+e.groupID,type:C.CONV_GROUP,lastMessage:Object.assign(Object.assign({lastTime:e.time,lastSequence:e.sequence,fromAccount:e.msgGroupFromAccount},this._patchTypeAndPayload(e)),{cloudCustomData:(null==(t=e.lastMsg)?void 0:t.cloudCustomData)||"",isRevoked:e.lastMessageFlag===ec.GROUP,onlineOnlyFlag:!1,nick:e.msgGroupFromNickName||"",nameCard:e.msgGroupFromCardName||"",revoker:(null==(t=null==(t=e.lastMsg)?void 0:t.revokerInfo)?void 0:t.revoker)||null}),groupProfile:{groupID:e.groupID,name:e.groupNick,avatar:e.groupImage,type:e.groupType,nextMessageSeq:e.nextMessageSeq},unreadCount:this._computeGroupUnreadCount(e),peerReadTime:0,isPinned:1===e.isPinned,version:0,customData:e.customMark||"",markList:dc(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.C2cPeerReadTime,peerReadTime:e.C2cPeerReadTime,friendRemark:e.C2cRemark,isPinned:e.TopFlags,standardMark:e.StandardMark,customMark:e.CustomMark,messageRemindType:e.MsgRecvOption,groupID:e.ToAccount,groupNick:e.GroupNick,groupImage:e.GroupImage,groupType:e.GroupType,nextMessageSeq:e.GroupNextMsgSeq,msgGroupFromAccount:e.MsgGroupFrom_Account,msgGroupFromNickName:e.MsgGroupFromNickName,MsgGroupFromCardName:e.MsgGroupFromCardName,unreadCount:e.UnreadMsgCount,noUnreadCount:e.GroupIgnoredUnreadSeqCount}))}_convertLastMsgKey(s){var e,t,r=k["utils"]["isEmpty"];if(r(s))return null;let i="",n=null;if(!r(s.GroupTips)){let{From_Account:e,GroupName:t}=(null==(r=s.GroupTips)?void 0:r.GroupInfo)||{};i=C.MSG_GRP_TIP,n=Object.assign(Object.assign({},this._parseContent(i,s.GroupTips.MsgBody)),{groupProfile:{from:e,groupName:t}})}return s.MsgBody&&(i=null==(e=s.MsgBody[0])?void 0:e.MsgType,n=this._parseContent(i,s.MsgBody[0])),{event:s.Event,elements:[{type:i,content:n,cloudCustomData:s.CloudCustomData}],revokerInfo:{revoker:null==(t=s.RevokerInfo)?void 0:t.Revoker_Account}}}_parseContent(e,t){return t&&((e=k.message.messageFactory.getElementClass(e))?null==(e=e.parseServerPushElement(t))?void 0:e.content:t)}_amendLayersOverLimitProp(e){var t=e["LayersOverLimit"];return f(e,["LayersOverLimit"]).layersOverLimit=1===t,e}_transMsgRemindType(e){let t="";return 0===e?t=C.MSG_REMIND_ACPT_AND_NOTE:1===e?t=C.MSG_REMIND_DISCARD:2===e?t=C.MSG_REMIND_ACPT_NOT_NOTE:3===e&&(t=C.NOT_RECEIVE_OFFLINE_PUSH_EXCEPT_AT),t}_patchTypeAndPayload(e){var t=k["utils"]["isUndefined"],{event:e,elements:s=[]}=e.lastMsg||{};return t(e)?{type:s[0]?s[0].type:null,payload:s[0]?this._amendLayersOverLimitProp(s[0].content):null}:{type:C.MSG_GRP_TIP,payload:(null==(t=null==s?void 0:s[0])?void 0:t.content)||{}}}_computeGroupUnreadCount(e){var{unreadCount:e=0,noUnreadCount:t=0}=e,e=e-t;return 0<e?e:0}_reset(){this._pagingStatus=Xu.NOT_START,this._pagingTimeStamp=0,this._pagingStartIndex=0,this._pagingPinnedTimeStamp=0,this._pagingPinnedStartIndex=0}_dispose(){this._reset();var e=k["notificationCenter"];e.unSubscribeInnerEvent(d.LOGOUT,this._reset,this),e.unSubscribeInnerEvent(d.DESTROY,this._dispose,this)}}class gc{constructor(){this.syncConversationHandler=new hc,this.syncConversationHandler.init()}}return k.ssoLog.debug("TencentCloudLiteChat.VERSION:1.6.4"),{create:function(e){var{SDKAppID:e,testEnv:t=!1,devMode:s=!1,unlimitedAVChatRoom:r=!1,scene:i="",oversea:n=!1,instance:o,disableIndependentDomain:a=!1}=e,l=e;if("number"!=typeof l&&(e=Number(l),Number.isNaN(e)))return console.error("Create SDK instance failed. Failed to parse the SDKAppID, please check the arguments"),null;if(l=Number(l),xs.has(l))return xs.get(l);let u=null;if(o)(u=o)._workflowManager&&g.setInstance(u._workflowManager),u._pluginManager&&u._pluginManager.installBuiltInPlugin(wl),!o.isReady()||null!=(o=(e=g.getInstance()).executeWorkflow)&&o.call(e,h.SYNC_SERVER_INFO_AFTER_LOGIN);else{let e=""+(c()+c())+c()+c()+c()+c()+c()+c();k.init({sdkAppId:l,instanceId:e,testEnv:t,devMode:s,unlimitedAVChatRoom:r,disableIndependentDomain:a,scene:i,oversea:n,sdkEdition:Gl}),g.getInstance().init(),k.message=new qu,k.user=new cc,k.login=new zl,k.conversation=new gc,kl.getInstance().installBuiltInPlugin(wl),(u=P.getInstance().exposeApiForClient())._workflowManager=g.getInstance(),u._pluginManager=kl.getInstance()}function c(){return(65536*(1+Math.random())|0).toString(16).substring(1)}return xs.set(l,u),u},TSignaling:Yt,EVENT:Kt,VERSION:ct,TYPES:C}});
|
|
1
|
+
!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?module.exports=t():"function"==typeof define&&define.amd?define(t):(e="undefined"!=typeof globalThis?globalThis:e||self).TencentCloudChat=t()}(this,function(){"use strict";const e=e=>void 0===e,t=e=>"string"==typeof e,s=e=>{var t;return null===(t=Object.prototype.toString.call(e).match(/^\[object (.*)\]$/))||void 0===t?void 0:t[1].toLowerCase()},n=e=>"function"==typeof Array.isArray?Array.isArray(e):"array"===s(e),o=e=>null!==e&&"object"==typeof e,i=e=>n(e)||o(e),r=e=>{if("string"!=typeof e)return!1;const t=e[0];return!/[^a-zA-Z0-9]/.test(t)},a=e=>{if("object"!=typeof e||null===e)return!1;const t=Object.getPrototypeOf(e);if(null===t)return!0;let s=t;for(;null!==Object.getPrototypeOf(s);)s=Object.getPrototypeOf(s);return t===s};function c(e=99999999){return Math.round(Math.random()*e)}const u=(t,s,n,o)=>{if(!i(t)||!i(s))return 0;let r=0;const a=Object.keys(s);let c;for(let l=0,d=a.length;l<d;l++)if(c=a[l],!(e(s[c])||n&&n.includes(c)))if(i(t[c])&&i(s[c]))r+=u(t[c],s[c],n,o);else{if(o&&o.includes(s[c]))continue;t[c]!==s[c]&&(t[c]=s[c],r+=1)}return r};function l(e){let t,s,n=e;e.length%8!=0&&(n="0".repeat(8-e.length%8)+e);let o="";for(let e=0,{length:i}=n;e<i;e+=8)t=parseInt(n.slice(e,e+4),2),s=parseInt(n.slice(e+4,e+8),2),o+=base16Map.get(t)+base16Map.get(s);return o}const d={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},h=["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 g;!function(e){e[e.DEBUG=0]="DEBUG",e[e.INFO=1]="INFO",e[e.WARN=2]="WARN",e[e.ERROR=3]="ERROR",e[e.NONE=4]="NONE"}(g||(g={}));const p="LiteChat",_={[g.DEBUG]:console.debug,[g.INFO]:console.info,[g.WARN]:console.warn,[g.ERROR]:console.error},m={[g.INFO]:4,[g.WARN]:5,[g.ERROR]:6},v=1e3,f=2,I=5e3,E=50;var S;!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"}(S||(S={}));var C=Object.freeze({__proto__:null,CONSOLE_METHOD:_,CloudConfigReportLevelMap:m,get ConvModifyPushType(){return S},DEFAULT_GLOBAL_MAX_TOTAL_COUNT:E,DEFAULT_GLOBAL_THROTTLE_TIME:I,DEFAULT_SINGLE_MAX_TOTAL_COUNT:f,DEFAULT_SINGLE_THROTTLE_TIME:v,ENUM_PLATFORM:d,IS_TOPIC_MESSAGE:2,get LogLevel(){return g},NOT_NEED_CRC_SERVCMD:h,SDK_NAME:p});const M="undefined"!=typeof wx&&"function"==typeof wx.getSystemInfoSync&&("mac"===wx.getSystemInfoSync().platform||"windows"===wx.getSystemInfoSync().platform)&&"undefined"===wx.getSystemInfoSync().uniPlatform,y="undefined"!=typeof wx&&"function"==typeof wx.getSystemInfoSync&&Boolean(wx.getSystemInfoSync().fontSizeSetting)||M,O=y&&"function"==typeof wx.createGamePortal,A="undefined"!=typeof qq&&"function"==typeof qq.getSystemInfoSync&&Boolean(qq.getSystemInfoSync().fontSizeSetting),T="undefined"!=typeof tt&&"function"==typeof tt.getSystemInfoSync&&Boolean(tt.getSystemInfoSync().fontSizeSetting),R=T&&"function"==typeof tt.onShow,D="undefined"!=typeof swan&&"function"==typeof swan.getSystemInfoSync&&Boolean(swan.getSystemInfoSync().fontSizeSetting),b="undefined"!=typeof my&&"function"==typeof my.getSystemInfoSync&&Boolean(my.getSystemInfoSync().fontSizeSetting),N="undefined"!=typeof jd&&"function"==typeof jd.getSystemInfoSync,L="undefined"!=typeof uni&&"undefined"==typeof window&&"function"==typeof uni.requireNativePlugin,P=y&&"object"==typeof wx.miniapp,w="undefined"!=typeof uni,G=y||A||T||D||b||L||N,U="undefined"==typeof window&&!G&&"undefined"!=typeof global&&void 0!==global.NativeScriptGlobals,k="undefined"!=typeof global&&(void 0!==global.nativeModuleProxy||void 0!==global.ReactNative),F="undefined"!=typeof wx&&"function"==typeof wx.getAccountInfoSync&&Boolean(wx.getAccountInfoSync().plugin),$="undefined"!=typeof uni?!G:"undefined"!=typeof window&&!G&&!k,q=A?qq:T?tt:D?swan:b?my:y?wx:L?uni:N?jd:{},x=$&&window&&window.navigator&&window.navigator.userAgent||"",V=/(micromessenger|webbrowser)/i.test(x),B=function(){let e="WEB";return V?e="WEB":A?e="QQ_MP":T?e="TT_MP":D?e="BAIDU_MP":b?e="ALI_MP":y?e=P?"DONUT_NATIVE_APP":"WX_MP":L?e="UNI_NATIVE_APP":U?e="NS_NATIVE_APP":k&&(e="RN_NATIVE_APP"),d[e]}(),j=/iPad/i.test(x),K=/iPhone/i.test(x)&&!j,H=/iPod/i.test(x),W=K||j||H,Y=function(){const e=x.match(/OS (\d+)_/i);return e&&e[1]?e[1]:null}(),z=/Android/i.test(x),J=function(){const e=x.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}(),Q=/Firefox/i.test(x),X=/Edge/i.test(x),Z=!X&&/Chrome/i.test(x),ee=/MSIE/.test(x)||x.indexOf("Trident")>-1&&x.indexOf("rv:11.0")>-1,te=function(){const e=/MSIE\s(\d+)\.\d/.exec(x);let t=e&&parseFloat(e[1]);return!t&&/Trident\/7.0/i.test(x)&&/rv:11.0/.test(x)&&(t=11),t}(),se=/Safari/i.test(x)&&!Z&&!z&&!X,ne=/Windows/i.test(x),oe=/MAC OS X/i.test(x),ie=$&&"undefined"!=typeof Worker&&!ee,re=z||W,ae=$&&void 0!==window.tencent_cloud_im_csig_flutter_for_web_25F_cy,ce=function(){if("undefined"==typeof window||void 0===window.navigator)return!1;const{standalone:e}=window.navigator;return!(!W||e||se)}();function ue(){let e="unknown";if(oe&&(e="mac"),ne&&(e="windows"),W&&(e="ios"),z&&(e="android"),G)try{const{platform:t}=q.getSystemInfoSync();void 0!==t&&(e=t)}catch(e){console.error(e)}return e}function le(e,t){var s={};for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&t.indexOf(n)<0&&(s[n]=e[n]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var o=0;for(n=Object.getOwnPropertySymbols(e);o<n.length;o++)t.indexOf(n[o])<0&&Object.prototype.propertyIsEnumerable.call(e,n[o])&&(s[n[o]]=e[n[o]])}return s}function de(e,t,s,n){return new(s||(s=Promise))(function(o,i){function r(e){try{c(n.next(e))}catch(e){i(e)}}function a(e){try{c(n.throw(e))}catch(e){i(e)}}function c(e){var t;e.done?o(e.value):(t=e.value,t instanceof s?t:new s(function(e){e(t)})).then(r,a)}c((n=n.apply(e,t||[])).next())})}"function"==typeof SuppressedError&&SuppressedError;const he=2800,ge=2801,pe=3e3,_e="application/x-www-form-urlencoded;charset=UTF-8";function me(e){return de(this,arguments,void 0,function*({method:e,url:t,data:s,timeout:n=pe}){return new Promise(G?(o,i)=>{q.request({url:t,data:s,method:e,timeout:n,header:{"content-type":_e},success:e=>o(e.data),fail:()=>i(new Error(`{"message":"Network error","code":${he}}`))})}:(o,i)=>{const r=new XMLHttpRequest,a=setTimeout(()=>{r.abort(),i(new Error(`{"message":"Request timeout","code":${ge}}`))},n);r.onreadystatechange=function(){if(4===r.readyState)if(clearTimeout(a),200===r.status||304===r.status)try{o(r.responseText?JSON.parse(r.responseText):null)}catch(e){o(r.responseText)}else i(new Error(`{"message":"Network error","code":${he}}`))},r.open(e,t,!0),r.setRequestHeader("Content-type",_e),r.send(s||null)})})}function ve(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(a(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 fe(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(fe(s),fe(e))}),t}if(e instanceof Set){const t=new Set;return e.forEach(e=>{t.add(fe(e))}),t}if(Array.isArray(e))return e.map(e=>fe(e));const t=Object.getPrototypeOf(e),s=Object.create(t);return[...Object.getOwnPropertyNames(e),...Object.getOwnPropertySymbols(e)].forEach(t=>{const n=Object.getOwnPropertyDescriptor(e,t);n&&(n.get||n.set?Object.defineProperty(s,t,n):s[t]=fe(e[t]))}),s}function Ie(e,t,s){const n=new WeakSet,o=(e,s)=>{if(t&&(s=t(e,s)),void 0===s)return"undefined";if(null===s)return null;if(Number.isNaN(s))return"NaN";if(s===1/0)return"Infinity";if(s===-1/0)return"-Infinity";if("function"==typeof s)return`[Function: ${s.name||"anonymous"}]`;if("symbol"==typeof s)return s.toString();if("bigint"==typeof s)return`${s.toString()}n`;if("object"==typeof s&&null!==s){if(n.has(s))return"[Circular]";n.add(s)}return s instanceof Date?s.toISOString():s instanceof Error?{name:s.name,message:s.message,stack:s.stack}:s instanceof Map?{dataType:"Map",value:Array.from(s.entries())}:s instanceof Set?{dataType:"Set",value:Array.from(s.values())}:s};try{return JSON.stringify(e,o,s)}catch(e){return console.error("Failed to stringify:",e),""}}function Ee(){let e,t;return{promise:new Promise((s,n)=>{e=s,t=n}),resolve:e,reject:t}}var Se,Ce=Object.freeze({__proto__:null,ANDROID_VERSION:J,IE_VERSION:te,IN_ALIPAY_MINI_APP:b,IN_BAIDU_MINI_APP:D,IN_BROWSER:$,IN_DONUT_NATIVE_APP:P,IN_JD_MINI_APP:N,IN_MINI_APP:G,IN_NS_NATIVE_APP:U,IN_QQ_MINI_APP:A,IN_RN_APP:k,IN_TT_MINI_APP:T,IN_TT_MINI_GAME:R,IN_UNI_APP:w,IN_UNI_NATIVE_APP:L,IN_WX_MINI_APP:y,IN_WX_MINI_APP_DESK:M,IN_WX_MINI_GAME:O,IN_WX_MINI_PLUGIN:F,IOS_VERSION:Y,IS_ANDROID:z,IS_CHROME:Z,IS_EDGE:X,IS_FIREFOX:Q,IS_IE:ee,IS_IOS:W,IS_IPAD:j,IS_IPHONE:K,IS_IPOD:H,IS_MAC:oe,IS_SAFARI:se,IS_WECHAT:V,IS_WIN:ne,IS_WORKER_AVAILABLE:ie,MINI_APP_NAMESPACE:q,USER_AGENT:x,base16EncodeBinaryString:l,deepCopyWithMethods:fe,deepMerge:u,generatePromise:Ee,getPlatformType:ue,getType:s,httpRequest:me,isArray:n,isArrayOrObject:i,isEmpty:ve,isFlutterWeb:ae,isH5:re,isIOSWebView:ce,isNumber:e=>null!==e&&("number"==typeof e&&!Number.isNaN(e-0)||"object"==typeof e&&e.constructor===Number),isObject:o,isPlainObject:a,isString:t,isUndefined:e,isUniIOSApp:function(){return L&&"ios"===uni.getDeviceInfo().platform.toLocaleLowerCase()},isValidRequestKey:r,platform:B,randomInt:c,randomString:function(){const e="0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";let t="";for(let s=32;s>0;--s)t+=e[Math.floor(62*Math.random())];return t},safeStringify:Ie});class Me{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 n;t&&(this.listeners[e]=null===(n=this.listeners[e])||void 0===n?void 0:n.filter(e=>{const n=e.fn===t,o=!s||e.context===s;return!(n&&o)}))}emit(e,...t){const s=this.listeners[e];s&&s.forEach(s=>{const{fn:n,context:o}=s;try{n.apply(o,t)}catch(t){console.warn(`Error in event handler for ${e} error: ${Ie(t)}`)}})}once(e,t,s){const n=(...o)=>{t.apply(s,o),this.off(e,n)};this.on(e,n)}}!function(e){e.BUSINESS_COMMAND="business_command",e.C2C_REALTIME_MESSAGE="c2c_realtime_message",e.C2C_MESSAGE_MODIFIED="c2c_message_modified",e.C2C_REVOKED_MESSAGE="c2c_message_revoked",e.GROUP_REALTIME_MESSAGE="group_realtime_message",e.GROUP_MESSAGE_MODIFIED="group_message_modified",e.GROUP_MESSAGE_REVOKED="group_message_revoked",e.C2C_MESSAGE_READ_RECEIPT="c2c_message_read_receipt",e.MESSAGE_REACTION_UPDATED="message_reaction_updated",e.MESSAGE_REACTION_UPDATED_SYNC="message_reaction_updated_sync",e.GROUP_AT_TIPS="group_at_tips",e.USER_STATUS_UPDATE="user_status_update",e.FRIEND_LIST_MODIFIED="friend_list_modified",e.PROFILE_MODIFIED="profile_modified",e.CONV_MODIFIED="conversation_modified",e.GROUP_TIPS_NOTIFICATION="group_tips_notification",e.GROUP_MESSAGE_READ_RECEIPT="group_message_read_receipt",e.GROUP_MESSAGE_READ_SYNC="group_message_read_sync",e.GROUP_SYSTEM_NOTIFICATION="group_system_notification",e.C2C_MESSAGE_PEER_READ="c2c_message_peer_read",e.C2C_MESSAGE_READ_SYNC="c2c_message_read_sync",e.C2C_REMIND_TYPE_SYNC="c2c_remind_type_sync",e.FOLLOW_LIST_UPDATED="follow_list_updated",e.MESSAGE_EXTENSIONS_UPDATED="message_extensions_updated",e.ALL_MESSAGE_READ="all_message_read",e.CONVERSATION_MARK_UPDATED="conversation_mark_updated",e.CONVERSATION_GROUP_ADD="conversation_group_add",e.CONVERSATION_GROUP_DELETED="conversation_group_deleted",e.CONVERSATION_GROUP_UPDATED="conversation_group_updated",e.ALL_RECEIVE_MESSAGE_OPTION="all_receive_message_option",e.TOPIC_AT_TIPS="topic_at_tips",e.TOPIC_TIPS_NOTIFICATION="topic_tips_notification",e.TOPIC_SYSTEM_NOTIFICATION="topic_system_notification",e.TOPIC_MESSAGE_READ_SYNC="topic_message_read_sync",e.TOPIC_LATEST_MESSAGE="topic_latest_message",e.GROUP_MESSAGE_PINNED="group_message_pinned"}(Se||(Se={}));const ye=[16,17];function Oe(e){var t;const s=[];return null===(t=null==e?void 0:e.GroupTips)||void 0===t||t.forEach(e=>{var t;2===e.GroupInfo.MillionGroupFlag?s.push(Se.TOPIC_TIPS_NOTIFICATION):ye.includes(null===(t=null==e?void 0:e.MsgBody)||void 0===t?void 0:t.OpType)?s.push(Se.GROUP_MESSAGE_PINNED):s.push(Se.GROUP_TIPS_NOTIFICATION)}),s}const Ae=[{conditions:[{type:"event",value:100}],subType:Se.BUSINESS_COMMAND},{conditions:[{type:"event",value:24}],subType:Se.ALL_RECEIVE_MESSAGE_OPTION},{conditions:[{type:"event",value:26}],subType:Se.TOPIC_LATEST_MESSAGE},{conditions:[{type:"hasKey",value:"C2cMsgArray"}],subType:Se.C2C_REALTIME_MESSAGE},{conditions:[{type:"hasKey",value:"C2cMsgModNotifys"}],subType:Se.C2C_MESSAGE_MODIFIED},{conditions:[{type:"hasKey",value:"ProfileDataMod"}],subType:Se.PROFILE_MODIFIED},{conditions:[{type:"hasKey",value:"UserStatusList"}],subType:Se.USER_STATUS_UPDATE},{conditions:[{type:"hasKey",value:"FriendListMod"}],subType:Se.FRIEND_LIST_MODIFIED},{conditions:[{type:"hasKey",value:"GroupMsgArray"}],subType:Se.GROUP_REALTIME_MESSAGE},{conditions:[{type:"hasKey",value:"GroupMsgModNotifys"}],subType:Se.GROUP_MESSAGE_MODIFIED},{conditions:[{type:"hasKey",value:"C2cNotifyMsgArray"}],subTypeParser:function(e){var t;const s=[];return null===(t=null==e?void 0:e.C2cNotifyMsgArray)||void 0===t||t.forEach(e=>{e.WithdrawC2cMsgNotify&&s.push(Se.C2C_REVOKED_MESSAGE),e.C2cReadedReceipt&&s.push(Se.C2C_MESSAGE_PEER_READ),e.ReadC2cMsgNotify&&s.push(Se.C2C_MESSAGE_READ_SYNC),e.MuteNotificationsSync&&s.push(Se.C2C_REMIND_TYPE_SYNC)}),s}},{conditions:[{type:"hasKey",value:"GroupTips"},{type:"event",value:4}],subTypeParser:Oe},{conditions:[{type:"hasKey",value:"GroupTips"},{type:"event",value:5}],subTypeParser:function(e){var t;const s=[];return null===(t=null==e?void 0:e.GroupTips)||void 0===t||t.forEach(e=>{Array.isArray(e.MsgBody.GroupWithdrawInfoArray)?s.push(Se.GROUP_MESSAGE_REVOKED):Array.isArray(e.MsgBody.GroupMsgReceiptList)?s.push(Se.GROUP_MESSAGE_READ_RECEIPT):Array.isArray(e.MsgBody.GroupReadInfoArray)?e.MsgBody.GroupReadInfoArray[0].TopicId?s.push(Se.TOPIC_MESSAGE_READ_SYNC):s.push(Se.GROUP_MESSAGE_READ_SYNC):2===e.GroupInfo.MillionGroupFlag?s.push(Se.TOPIC_SYSTEM_NOTIFICATION):s.push(Se.GROUP_SYSTEM_NOTIFICATION)}),s}},{conditions:[{type:"hasKey",value:"GroupTips"},{type:"event",value:6}],subTypeParser:Oe},{conditions:[{type:"hasKey",value:"GroupTips"},{type:"event",value:12}],subTypeParser:function(e){var t;const s=[];return null===(t=null==e?void 0:e.GroupTips)||void 0===t||t.forEach(e=>{const{GroupAtTips:{TopicId:t}}=e;t?s.push(Se.TOPIC_AT_TIPS):s.push(Se.GROUP_AT_TIPS)}),s}},{conditions:[{type:"hasKey",value:"RecentContactMod"}],subTypeParser:function(e){var t;const s=[];return null===(t=null==e?void 0:e.RecentContactMod)||void 0===t||t.forEach(e=>{switch(e.PushType){case S.CONV_MARK_UPDATED:s.push(Se.CONVERSATION_MARK_UPDATED);break;case S.CONV_GROUP_ADDED:s.push(Se.CONVERSATION_GROUP_ADD);break;case S.CONV_GROUP_DELETED:s.push(Se.CONVERSATION_GROUP_DELETED);break;case S.CONV_GROUP_UPDATED:s.push(Se.CONVERSATION_GROUP_UPDATED);break;default:s.push(Se.CONV_MODIFIED)}}),s}},{conditions:[{type:"hasKey",value:"MsgReactionNotifyList"}],subType:Se.MESSAGE_REACTION_UPDATED},{conditions:[{type:"hasKey",value:"MsgReactionNotify"}],subType:Se.MESSAGE_REACTION_UPDATED_SYNC},{conditions:[{type:"hasKey",value:"C2cMsgInfo"}],subType:Se.C2C_MESSAGE_READ_RECEIPT},{conditions:[{type:"hasKey",value:"FollowChangeList"}],subType:Se.FOLLOW_LIST_UPDATED},{conditions:[{type:"hasKey",value:"MsgExtensionNotify"}],subType:Se.MESSAGE_EXTENSIONS_UPDATED},{conditions:[{type:"hasKey",value:"C2CReadAllMsg"}],subType:Se.ALL_MESSAGE_READ}];var Te;function Re(e){var t;const s=Array.isArray(null===(t=null==e?void 0:e.body)||void 0===t?void 0:t.EventArray)?e.body.EventArray:[],n=[];return s.forEach(t=>{t.Flag=e.body.Flag;const s=Ae.find(e=>e.conditions.every(e=>{switch(e.type){case"event":return t.Event===e.value;case"hasKey":return Object.prototype.hasOwnProperty.call(t,e.value);default:return!1}}));if(!s)return null;let o=[];"function"==typeof s.subTypeParser?o=s.subTypeParser(t):s.subType&&(o=s.subType),Array.isArray(o)?o.forEach(e=>{n.push({type:`${Te.SERVER_PUSH_MESSAGE}:${e}`,data:t})}):n.push({type:`${Te.SERVER_PUSH_MESSAGE}:${o}`,data:t})}),n}!function(e){e.SERVER_PUSH_MESSAGE="im_open_push.msg_push",e.SERVER_PUSH_MESSAGE_MULTIPLE="im_open_push.multi_msg_push_ws",e.ERROR="error"}(Te||(Te={}));const De={[Te.SERVER_PUSH_MESSAGE]:Re,[Te.SERVER_PUSH_MESSAGE_MULTIPLE]:Re,[Te.ERROR]:function(e){const{errorCode:t}=e;return[{type:`error:${t}`,data:e}]}};const be=new class{constructor(){this._outerEventEmitter=null,this._innerEventEmitter=null,this._outerEventEmitter=new Me,this._innerEventEmitter=new Me,this.InnerEventSubType=Se}subscribeInnerEvent(e,t,s,n){var o,i;if(["string","number"].includes(typeof t)){const i=t,r=s;null===(o=this._innerEventEmitter)||void 0===o||o.on(`${e}:${i}`,r,n)}else{const n=t;null===(i=this._innerEventEmitter)||void 0===i||i.on(e,n,s)}}emitInnerEvent(e,t){var s,n;if(null===(s=this._innerEventEmitter)||void 0===s||s.emit(e,t),Object.keys(De).includes(e)){const s=null===(n=De[e])||void 0===n?void 0:n.call(De,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,n){var o,i;if(["string","number"].includes(typeof t)){const i=t,r=s;null===(o=this._innerEventEmitter)||void 0===o||o.off(`${e}:${i}`,r,n)}else{const n=t;null===(i=this._innerEventEmitter)||void 0===i||i.off(e,n,s)}}subscribeOuterEvent(e,t,s){var n;null===(n=this._outerEventEmitter)||void 0===n||n.on(e,t,s)}unSubscribeOuterEvent(e,t,s){var n;null===(n=this._outerEventEmitter)||void 0===n||n.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}};class Ne{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:n,onError:o,onSendFail:i}=e;this._socket&&(this._socket.binaryType="arraybuffer",this._socket.onopen=t,this._socket.onmessage=s,this._socket.onclose=n,this._socket.onerror=o,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 Le{connectSocket(e){return this._socket=q.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:n,onError:o,onSendFail:i}=e;this._socket.onClose(n),this._socket.onOpen(t),this._socket.onMessage(s),this._socket.onError(o),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 Pe="CONNECT",we="SEND",Ge="DISCONNECT",Ue="OPEN",ke="MESSAGE",Fe="CLOSE",$e="ERROR",qe="SEND_FAIL";class xe{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:Pe,url:e})}send(e){var t,s;try{null===(t=this._worker)||void 0===t||t.postMessage({type:we,data:e})}catch(e){null===(s=this._onSendFail)||void 0===s||s.call(this,e)}}bindSocketHandlers(e){const{onOpen:t,onMessage:s,onClose:n,onError:o,onSendFail:i}=e;if(this._worker){const e={[Ue]:t,[ke]:s,[Fe]:n,[$e]:o,[qe]:i};this._onSendFail=i,this._worker.onmessage=t=>{var s;const{type:n}=(null==t?void 0:t.data)||{};"function"==typeof e[n]&&(null===(s=e[n])||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:Ge}),this._worker.terminate(),this._worker=null),this._blobUrl&&(URL.revokeObjectURL(this._blobUrl),this._blobUrl=null)}}var Ve,Be=new class{constructor(){this._store=new Map}get(e){return this._store.get(e)}getStorage(e){if(G){if(b){return my.getStorageSync({key:e}).data}return q.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){G?b?my.setStorageSync({key:e,data:JSON.stringify(t)}):q.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"}(Ve||(Ve={}));class je{constructor(e){this._url="",this._readyState=Ve.DISCONNECTED,this._url=e,this._id=c(),this._emitter=new Me,y||L||R?this._socket=new Le:this._canUseWebWorker()?this._socket=new xe:this._socket=new Ne,this.connect()}connect(){this.doOpen(),this._bindSocketHandlers()}doOpen(){[Ve.CONNECTED,Ve.CONNECTING].includes(this._readyState)||(this._readyState=Ve.CONNECTING,this._ws=this._socket.connectSocket(this._url))}send(e){this._readyState!==Ve.CONNECTED?this.reconnect():this._socket.send(e)}reconnect(){[Ve.CONNECTED,Ve.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===Ve.CONNECTED}disconnect(){this._readyState=Ve.DISCONNECTED,this._unbindSocketHandlers(),this._socket.disconnect()}_onOpen(e){this._readyState===Ve.CONNECTING&&(this._readyState=Ve.CONNECTED,this._emitter.emit("connect",{socketId:this._id,event:e}))}_onMessage(e){this._emitter.emit("message",e)}_onClose(e){this._readyState=Ve.DISCONNECTED,this._emitter.emit("close",{socketId:this._id,event:e})}_onError(e){this._readyState=Ve.DISCONNECTED,this._emitter.emit("error",{socketId:this._id,error:e})}_onSendFail(e){this._readyState=Ve.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 t=Be.get("cloudConfig")||{};return(e(t.isWorkerEnabled)||"1"===t.isWorkerEnabled)&&ie}}const Ke="CHINA",He="OVERSEA",We="SINGAPORE",Ye="KOREA",ze="GERMANY",Je="IND",Qe="JPN",Xe="USA",Ze="INDONESIA",et={TEST:{CHINA:{DEFAULT:"wss://wss-dev.tim.qq.com"},OVERSEA:{DEFAULT:"wss://wss-dev.tim.qq.com"},SINGAPORE:{DEFAULT:"wss://wsssgp-dev.im.qcloud.com"},KOREA:{DEFAULT:"wss://wsskr-dev.im.qcloud.com"},GERMANY:{DEFAULT:"wss://wssger-dev.im.qcloud.com"},IND:{DEFAULT:"wss://wssind-dev.im.qcloud.com"},JPN:{DEFAULT:"wss://wssjpn-dev.im.qcloud.com"},USA:{DEFAULT:"wss://wssusa-dev.im.qcloud.com"},INDONESIA:{DEFAULT:"wss://wssidn-dev.im.qcloud.com"}},PRODUCTION:{CHINA:{INITIAL:"wss://*w4c.my-imcloud.com",DEFAULT:"wss://wss.im.qcloud.com",IPV6:"wss://wssv6.im.qcloud.com",BACKUP:"wss://wss.tim.qq.com",BACKUP_WEB_ONLY:"wss://*w4c.my-cpaas.com",BACKUP_CN:"wss://wss.im.tencent.cn",STAT:"https://events.im.qcloud.com",ANYCAST:"wss://162.14.13.203"},OVERSEA:{INITIAL:"wss://*w4c.my-imcloud.com",DEFAULT:"wss://wss.im.qcloud.com",IPV6:"wss://wssv6.im.qcloud.com",BACKUP:"wss://wss.my-imcloud.com",BACKUP_WEB_ONLY:"wss://*w4c.my-cpaas.com",BACKUP_CN:"wss://wss.im.tencent.cn",STAT:"https://api.my-imcloud.com"},SINGAPORE:{INITIAL:"wss://*w4s.my-imcloud.com",DEFAULT:"wss://wsssgp.im.qcloud.com",IPV6:"wss://wsssgpv6.im.qcloud.com",BACKUP:"wss://wsssgp.my-imcloud.com",BACKUP_WEB_ONLY:"wss://*w4s.my-cpaas.com",STAT:"https://apisgp.my-imcloud.com",ANYCAST:"wss://162.14.19.159"},KOREA:{INITIAL:"wss://*w4k.my-imcloud.com",DEFAULT:"wss://wsskr.im.qcloud.com",IPV6:"wss://wsskrv6.im.qcloud.com",BACKUP:"wss://wsskr.my-imcloud.com",BACKUP_WEB_ONLY:"wss://*w4k.my-cpaas.com",STAT:"https://apikr.my-imcloud.com",ANYCAST:"wss://162.14.13.104"},GERMANY:{INITIAL:"wss://*w4g.my-imcloud.com",DEFAULT:"wss://wssger.im.qcloud.com",IPV6:"wss://wssgerv6.im.qcloud.com",BACKUP:"wss://wssger.my-imcloud.com",BACKUP_WEB_ONLY:"wss://*w4g.my-cpaas.com",STAT:"https://apiger.my-imcloud.com",ANYCAST:"wss://162.14.3.17"},IND:{INITIAL:"wss://*w4i.my-imcloud.com",DEFAULT:"wss://wssind.my-imcloud.com",IPV6:"wss://wssindv6.im.qcloud.com",BACKUP:"wss://wssind.im.qcloud.com",BACKUP_WEB_ONLY:"wss://*w4i.my-cpaas.com",STAT:"https://apiind.my-imcloud.com",ANYCAST:"wss://162.14.19.46"},JPN:{INITIAL:"wss://*w4j.my-imcloud.com",DEFAULT:"wss://wssjpn.im.qcloud.com",IPV6:"wss://wssjpnv6.im.qcloud.com",BACKUP:"wss://wssjpn.my-imcloud.com",BACKUP_WEB_ONLY:"wss://*w4j.my-cpaas.com",STAT:"https://apijpn.my-imcloud.com",ANYCAST:"wss://162.14.13.254"},USA:{INITIAL:"wss://*w4u.my-imcloud.com",DEFAULT:"wss://wssusa.im.qcloud.com",IPV6:"wss://wssusav6.im.qcloud.com",BACKUP:"wss://wssusa.my-imcloud.com",BACKUP_WEB_ONLY:"wss://*w4u.my-cpaas.com",STAT:"https://apiusa.my-imcloud.com",ANYCAST:"wss://162.14.10.42"},INDONESIA:{INITIAL:"wss://*w4y.my-imcloud.com",DEFAULT:"wss://wssidn.im.qcloud.com",IPV6:"wss://wssidnv6.im.qcloud.com",BACKUP:"wss://wssidn.my-imcloud.com",BACKUP_WEB_ONLY:"wss://*w4y.my-cpaas.com",STAT:"https://apiidn.my-imcloud.com",ANYCAST:"wss://43.129.34.169"}}},st={[We]:[[2e7,3e7],[172e7,173e7]],[Ye]:[[3e7,4e7],[173e7,174e7]],[ze]:[[4e7,5e7],[174e7,175e7]],[Je]:[[5e7,6e7],[175e7,176e7]],[Qe]:[[6e7,7e7],[176e7,177e7]],[Xe]:[[7e7,8e7],[177e7,178e7]],[Ze]:[[8e7,9e7],[178e7,179e7]]};function nt(e){var t;if(null===(t=Be.get("instance"))||void 0===t?void 0:t.oversea)return He;for(const t of Object.keys(st))for(const[s,n]of st[t])if(e>=s&&e<n)return t;return Ke}var ot,it="1.6.5";!function(e){e.INITIAL="INITIAL",e.DEFAULT="DEFAULT",e.BACKUP="BACKUP",e.BACKUP_WEB_ONLY="BACKUP_WEB_ONLY",e.BACKUP_CN="BACKUP_CN",e.ANYCAST="ANYCAST",e.IPV6="IPV6"}(ot||(ot={}));let rt=ot.INITIAL;function at(){const e=Math.random();return 0===e?at():e}function ct(e,t){const{isBinary:s=!1}=t||{},n=Be.get("instance"),{sdkAppId:o,instanceId:i}=n,r=at(),a=ue(),c=function(){const e=ue();let t=-1;"ios"===e?t=Y||-1:"android"===e&&(t=J||-1);return t}(),u=(l={sdkappid:o,instanceid:i,random:r,platform:B,host:a,version:c,sdkversion:it},Object.keys(l).map(e=>`${e}=${l[e]}`).join("&"));var l;return s?`${e}/binfo?${u}&compress=gzip`:`${e}/info?${u}`}function ut(e){const t=Be.get("instance"),{sdkAppId:s,testEnv:n}=t,o=nt(s);if(n){return ct(et.TEST[o].DEFAULT,{isBinary:e})}const i=et.PRODUCTION[o],r=$&&i.ANYCAST,a=$,c=!!i.BACKUP_CN;return ct({[ot.INITIAL]:()=>(rt=ot.DEFAULT,i.DEFAULT),[ot.DEFAULT]:()=>(rt=ot.IPV6,i.IPV6),[ot.IPV6]:()=>(rt=ot.BACKUP,i.BACKUP),[ot.BACKUP]:()=>a?(rt=ot.BACKUP_WEB_ONLY,function(e){const t=Math.floor(10001*Math.random())+1e4;return e.replace("*",String(t))}(i.BACKUP_WEB_ONLY)):c?(rt=ot.BACKUP_CN,i.BACKUP_CN):r?(rt=ot.ANYCAST,i.ANYCAST):i.DEFAULT,[ot.BACKUP_WEB_ONLY]:()=>c?(rt=ot.BACKUP_CN,i.BACKUP_CN):r?(rt=ot.ANYCAST,i.ANYCAST):i.DEFAULT,[ot.BACKUP_CN]:()=>(rt=r?ot.ANYCAST:ot.DEFAULT,i[rt]),[ot.ANYCAST]:()=>(rt=ot.DEFAULT,i.ANYCAST="",i.DEFAULT)}[rt](),{isBinary:e})}var lt=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(),n=s-e;this._timeOffsetWithServer=t+n-s}};const dt=16;var ht=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:n,isOnce:o=!1,intervalMs:i=dt}=e,r=Math.max(i,dt);return{id:t,nextExecuteTime:Date.now()+r,intervalMs:i,callback:s,context:n,isOnce:o}}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 gt(e){const t=[];for(let s=0;s<e.length;s+=1){const n=e.charCodeAt(s);if(n>=55296&&n<=56319){const o=e.charCodeAt(++s)-56320+(n-55296<<10)+65536;t.push(240|o>>18,128|o>>12&63,128|o>>6&63,128|63&o)}else n<=127?t.push(n):n<=2047?t.push(192|n>>6,128|63&n):t.push(224|n>>12,128|n>>6&63,128|63&n)}return new Uint8Array(t)}function pt(e){const t=Array.isArray(e)?[]:Object.create(null);for(const s in e)Object.prototype.hasOwnProperty.call(e,s)&&r(s)&&null!=e[s]&&(null===e[s]||"object"!=typeof e[s]?t[s]=e[s]:t[s]=pt(e[s]));return t}function _t(e,t){if(h.includes(e))return 0;const s=gt(JSON.stringify(t));let n=4294967295;const{length:o}=s;for(let e=0;e<o;e++){n^=s[e];for(let e=0;e<8;e++)1&~n?n>>>=1:n=n>>>1^3988292384}return(4294967295^n)>>>0}function mt(e){const{servcmd:t,data:s}=e,n=function(e){const t=Be.get("login")||{},s=Be.get("instance")||{};return{servcmd:e,ver:"v4",platform:B,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:l(""),cappid:s.applicationID||0,tjgID:"",seq:It(),cs:0}}(t),o=pt(s);return n.cs=_t(t,o),{head:n,body:o}}function vt(e){const{servcmd:t,data:s}=e,n=function(e){const t=Be.get("login")||{},s=Be.get("instance")||{};return{servcmd:e,ver:"v4",platform:B,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:l(""),cappid:s.applicationID||0,seq:It(),cs:0}}(t),o=pt(s);return n.cs=_t(t,o),{head:n,body:o}}let ft=c();function It(){return ft=ft<2415919103?ft+1:c(),ft}function Et(){const e=Be.get("login")||{},t=Be.get("instance")||{};return{sdk_type:30,sdk_app_id:t.sdkAppId,sdk_version:"1.6.5",tiny_id:Number(e.tinyID),user_id:e.userId,platform:B,instance_id:t.instanceId,trace_id:(new Date).getTime()}}var St,Ct=Object.freeze({__proto__:null,generateCosSpecifiedData:function(e){const{servcmd:t,data:s}=e,n=function(e){const t=Be.get("login")||{},s=Be.get("instance")||{};return{servcmd:e,ver:"v4",platform:B,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:l(""),cappid:s.applicationID||0,seq:It(),cs:0}}(t),o=pt(s);return n.cs=_t(t,o),{head:n,body:o}},generateProtocolData:mt,generateSSOLogProtocolData:vt,generateSequence:It,getCommonHead:Et,taskScheduler:ht,timeManager:lt});!function(e){e[e.info=4]="info",e[e.warning=5]="warning",e[e.error=6]="error"}(St||(St={}));const Mt={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 yt{constructor(e){this.level=St.info,this._canSendLog=!0,this._logCreatedAt=lt.getServerTimeMs(),this.timestamp=0,this.networkType=8,this.code=0,this.moreMessage="",this.method="",this.message="",this.costTime=0,this.duplicate=!1,this.eventType=0,this.uiPlatform=this._getUiPlatform(),this._sdkEdition=this._getSDKEdition();const{method:t,eventType:s=0,message:n="",costTime:o=0,error:i,moreMessage:r="",code:a=0}=e||{};this.eventType=s,this.method=t,this.message=n,this.costTime=o,this.moreMessage=r,this.code=a,i&&this.setError(i)}setMoreMessage(e){this.moreMessage=`${this.moreMessage} ${e}`}updateLogCreatedAtByTimeOffset(){this._logCreatedAt+=lt.getTimeOffsetWithServer()}end(e=!1){this._canSendLog&&(this._canSendLog=!1,this.timestamp=lt.getServerTimeMs(),this._ssoLogModule.pushToLogQueue(this._convertSSOLogDataKeyToServe()),e&&this._ssoLogModule.uploadSSOLogData())}setError(e){var t;if(!(e instanceof Error))return console.warn("SSOLogData.setError value not instanceof Error, please check!"),this;if(!this._canSendLog)return this;return(null===(t=Be.get("netWorkMonitor"))||void 0===t?void 0:t.isNetworkOnline)&&(e.errorCode&&(this.code=e.errorCode),e.errorMessage&&this.setMoreMessage(e.errorMessage)),this.level=St.error,this}setLogInfo(e){return Object.keys(e).forEach(t=>{Object.keys(Mt).includes(t)&&(this[t]=e[t])}),this}setSSOLogModule(e){this._ssoLogModule=e}_convertSSOLogDataKeyToServe(){const e={};return Object.keys(this).forEach(t=>{const s=t;Mt[s]&&(e[Mt[s]]=this[s])}),e}_getUiPlatform(){var e;const t=null===(e=Be.get("instance"))||void 0===e?void 0:e.scene;if("string"==typeof t){const e=Number(t);return isNaN(e)?void 0:e}}_getSDKEdition(){var e;return null===(e=Be.get("instance"))||void 0===e?void 0:e.sdkEdition}}var Ot;!function(e){e.RECONNECTED="reconnected",e.CLOUD_CONFIG_UPDATE="cloud_config_update",e.SOCKET_DISCONNECTED="socket_disconnected"}(Ot||(Ot={}));var At=Ot;const Tt=20,Rt=6e4,Dt=[4,5,6],bt=[],Nt=[],Lt="report-logger";var Pt=new class{constructor(){this._sdkAppIdBlackList=[],this._tinyIdWhiteList=[],this._reportLevel=[4,5,6],this._minThreshold=Tt,this._maxThreshold=100,this._waitingTime=Rt,this._lastReportAt=Date.now(),this._ssoLogMap=new Map,this._logLevel=g.DEBUG,this._throttleConfig={global:{throttleTime:I,maxCount:E},single:{throttleTime:v,maxCount:f}},this._globalThrottle={count:0,startTime:Date.now()},this._singleThrottleMap=new Map,be.subscribeInnerEvent(At.CLOUD_CONFIG_UPDATE,this._handleCloudConfigUpdate,this),ht.addTask({id:Lt,intervalMs:1e3,callback:this._checkAndReportIfDue,context:this}),this._logQueue=[],this._savePlatFormInfo()}_handleCloudConfigUpdate(e){const{evt_rpt_threshold:t=Tt,evt_rpt_waiting:s=Rt,evt_rpt_level:n=Dt,evt_rpt_sdkappid_bl:o=bt,evt_rpt_tinyid_wl:i=Nt,evt_rpt_global_throttle_time:r=I,evt_rpt_global_throttle_count:a=E,evt_rpt_single_throttle_time:c=v,evt_rpt_single_throttle_count:u=f}=e||{};this._sdkAppIdBlackList=o,this._waitingTime=s,this._minThreshold=t,this._reportLevel=n,this._tinyIdWhiteList=i,this._throttleConfig={global:{throttleTime:r,maxCount:a},single:{throttleTime:c,maxCount:u}}}createSSOLogData(e){const t=new yt(e);return t.setSSOLogModule(this),this._ssoLogMap.set(e.method,t),t}getSSOLogData(e){return this._ssoLogMap.get(e)||{}}pushToLogQueue(e){e&&(this._logQueue.push(e),this._shouldUploadImmediately()&&this.uploadSSOLogData())}setLogLevel(e){[g.DEBUG,g.ERROR,g.INFO,g.NONE,g.WARN].includes(e)&&(this._logLevel=e)}debug(e,t="",s){this._log(g.DEBUG,e,t,s)}info(e,t="",s){this._log(g.INFO,e,t,s)}warn(e,t="",s){this._log(g.WARN,e,t,s)}error(e,t="",s){this._log(g.ERROR,e,t,s)}_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 de(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:Et(),Event:t};ve(s.Header.user_id)||(yield function(e){const t="imopenstat.tim_web_report_v2",s=vt({servcmd:t,data:e}),n=`${s.head.seq}${t}`;es.sendPacket(s,{requestId:n})}(s)),this._lastReportAt=Date.now()})}_savePlatFormInfo(){var e,t;if(y){const s=null===(t=null===(e=wx.getAccountInfoSync)||void 0===e?void 0:e.call(wx))||void 0===t?void 0:t.miniProgram;if(s){const{appId:e,envVersion:t}=s;Be.set("instance",{appId:e,envVersion:t})}}else $&&Be.set("instance",{href:window.location.href})}_filterLogs(e){const{tinyID:t}=Be.get("login")||{},{sdkAppId:s}=Be.get("instance")||{};return this._sdkAppIdBlackList.includes(s)&&!this._tinyIdWhiteList.includes(t)?[]:e.filter(e=>this._reportLevel.includes(e.level))}_checkThrottle(e){return!!this._checkGlobalThrottle()||this._checkSingleThrottle(e)}_checkGlobalThrottle(){const e=Date.now();if(e-this._globalThrottle.startTime>=this._throttleConfig.global.throttleTime)this._globalThrottle.count=1,this._globalThrottle.startTime=e;else if(this._globalThrottle.count++,this._globalThrottle.count>this._throttleConfig.global.maxCount)return!0;return!1}_checkSingleThrottle(e){const t=Date.now(),s=this._singleThrottleMap.get(e);return s?t-s.startTime>=this._throttleConfig.single.throttleTime?(s.count=1,s.startTime=t,!1):s.count>=this._throttleConfig.single.maxCount||(s.count++,!1):(this._singleThrottleMap.set(e,{count:1,startTime:t}),!1)}_shouldLog(e){return e>=this._logLevel&&this._logLevel!==g.NONE}_shouldReport(e){return this._reportLevel.includes(m[e])}_formatLog(e,t,s){const n=new Date,o=`${n.getHours()}:${n.getMinutes()}:${n.getSeconds()}:${n.getMilliseconds()}`,i=`<${g[e]}>`;return ee||G?[`${p} [${o}] ${i} [${t}] ${s}`]:["%c%s%c%s","background:#0abf5b; padding:1px; border-radius:3px; color: #fff",p,"",`[${o}] ${i} [${t}] ${s}`]}_log(e,t,s,n){if(!this._shouldLog(e))return;const o=this._formatLog(e,t,s);if(_[e].apply(console,o),this._shouldReport(e)){const e=this._getThrottleKey(t,s,n);if(!this._checkThrottle(e)){this.createSSOLogData(Object.assign(Object.assign({message:s},n),{method:t})).end()}}}_getThrottleKey(e,t,s){const n=`${e}${t}${Ie(Object.assign(Object.assign({},s),{costTime:""}))}`,o=gt(JSON.stringify(n));let i=4294967295;const{length:r}=o;for(let e=0;e<r;e++){i^=o[e];for(let e=0;e<8;e++)1&~i?i>>>=1:i=i>>>1^3988292384}return`${(4294967295^i)>>>0}`}reset(){console.log("SSO_LOG_MODULE.reset"),ht.removeTask(Lt),be.unSubscribeInnerEvent(At.CLOUD_CONFIG_UPDATE,this._handleCloudConfigUpdate,this),this._lastReportAt=0,this.uploadSSOLogData(),this._sdkAppIdBlackList=[],this._tinyIdWhiteList=[],this._minThreshold=Tt,this._maxThreshold=100,this._waitingTime=Rt,this._logQueue=[],this._logLevel=g.DEBUG,this._globalThrottle={count:0,startTime:Date.now()},this._singleThrottleMap.clear()}};const wt=15e3,Gt="Channel",Ut="channel_schedule_task",kt="channel_reconnect_task",Ft="connected",$t="connecting",qt="disconnected",xt=1e3,Vt="network_status_change",Bt="activity_status_change",jt="send_fail",Kt="reconnect_failed",Ht="socket_error",Wt="socket_close";function Yt(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}function zt(e){return zt="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},zt(e)}function Jt(e){throw new Error('Could not dynamically require "'+e+'". Please configure the dynamicRequireTargets or/and ignoreDynamicRequires option of @rollup/plugin-commonjs appropriately for this require call to work.')}var Qt,Xt={exports:{}};var Zt=(Qt||(Qt=1,function(e){e.exports=function e(t,s,n){function o(r,a){if(!s[r]){if(!t[r]){if(!a&&Jt)return Jt(r);if(i)return i(r,!0);var c=new Error("Cannot find module '"+r+"'");throw c.code="MODULE_NOT_FOUND",c}var u=s[r]={exports:{}};t[r][0].call(u.exports,function(e){return o(t[r][1][e]||e)},u,u.exports,e,t,s,n)}return s[r].exports}for(var i=Jt,r=0;r<n.length;r++)o(n[r]);return o}({1:[function(e,t,s){var n="undefined"!=typeof Uint8Array&&"undefined"!=typeof Uint16Array&&"undefined"!=typeof Int32Array;s.assign=function(e){for(var t,s,n=Array.prototype.slice.call(arguments,1);n.length;){var o=n.shift();if(o){if("object"!=zt(o))throw new TypeError(o+"must be non-object");for(var i in o)t=o,s=i,Object.prototype.hasOwnProperty.call(t,s)&&(e[i]=o[i])}}return e},s.shrinkBuf=function(e,t){return e.length===t?e:e.subarray?e.subarray(0,t):(e.length=t,e)};var o={arraySet:function(e,t,s,n,o){if(t.subarray&&e.subarray)e.set(t.subarray(s,s+n),o);else for(var i=0;i<n;i++)e[o+i]=t[s+i]},flattenChunks:function(e){var t,s,n,o,i,r;for(t=n=0,s=e.length;t<s;t++)n+=e[t].length;for(r=new Uint8Array(n),t=o=0,s=e.length;t<s;t++)i=e[t],r.set(i,o),o+=i.length;return r}},i={arraySet:function(e,t,s,n,o){for(var i=0;i<n;i++)e[o+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,o)):(s.Buf8=Array,s.Buf16=Array,s.Buf32=Array,s.assign(s,i))},s.setTyped(n)},{}],2:[function(e,t,s){var n=e("./common"),o=!0,i=!0;try{String.fromCharCode.apply(null,[0])}catch(e){o=!1}try{String.fromCharCode.apply(null,new Uint8Array(1))}catch(e){i=!1}for(var r=new n.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&&o))return String.fromCharCode.apply(null,n.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,o,i,r,a=e.length,c=0;for(i=0;i<a;i++)55296==(64512&(s=e.charCodeAt(i)))&&i+1<a&&56320==(64512&(o=e.charCodeAt(i+1)))&&(s=65536+(s-55296<<10)+(o-56320),i++),c+=s<128?1:s<2048?2:s<65536?3:4;for(t=new n.Buf8(c),i=r=0;r<c;i++)55296==(64512&(s=e.charCodeAt(i)))&&i+1<a&&56320==(64512&(o=e.charCodeAt(i+1)))&&(s=65536+(s-55296<<10)+(o-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 n.Buf8(e.length),s=0,o=t.length;s<o;s++)t[s]=e.charCodeAt(s);return t},s.buf2string=function(e,t){var s,n,o,i,a=t||e.length,u=new Array(2*a);for(s=n=0;s<a;)if((o=e[s++])<128)u[n++]=o;else if(4<(i=r[o]))u[n++]=65533,s+=i-1;else{for(o&=2===i?31:3===i?15:7;1<i&&s<a;)o=o<<6|63&e[s++],i--;1<i?u[n++]=65533:o<65536?u[n++]=o:(o-=65536,u[n++]=55296|o>>10&1023,u[n++]=56320|1023&o)}return c(u,n)},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,n){for(var o=65535&e,i=e>>>16&65535,r=0;0!==s;){for(s-=r=2e3<s?2e3:s;i=i+(o=o+t[n++]|0)|0,--r;);o%=65521,i%=65521}return o|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 n=function(){for(var e,t=[],s=0;s<256;s++){e=s;for(var n=0;n<8;n++)e=1&e?3988292384^e>>>1:e>>>1;t[s]=e}return t}();t.exports=function(e,t,s,o){var i=n,r=o+s;e^=-1;for(var a=o;a<r;a++)e=e>>>8^i[255&(e^t[a])];return-1^e}},{}],6:[function(e,t,s){t.exports=function(){this.text=0,this.time=0,this.xflags=0,this.os=0,this.extra=null,this.extra_len=0,this.name="",this.comment="",this.hcrc=0,this.done=!1}},{}],7:[function(e,t,s){t.exports=function(e,t){var s,n,o,i,r,a,c,u,l,d,h,g,p,_,m,v,f,I,E,S,C,M,y,O,A;s=e.state,n=e.next_in,O=e.input,o=n+(e.avail_in-5),i=e.next_out,A=e.output,r=i-(t-e.avail_out),a=i+(e.avail_out-257),c=s.dmax,u=s.wsize,l=s.whave,d=s.wnext,h=s.window,g=s.hold,p=s.bits,_=s.lencode,m=s.distcode,v=(1<<s.lenbits)-1,f=(1<<s.distbits)-1;e:do{p<15&&(g+=O[n++]<<p,p+=8,g+=O[n++]<<p,p+=8),I=_[g&v];t:for(;;){if(g>>>=E=I>>>24,p-=E,0==(E=I>>>16&255))A[i++]=65535&I;else{if(!(16&E)){if(!(64&E)){I=_[(65535&I)+(g&(1<<E)-1)];continue t}if(32&E){s.mode=12;break e}e.msg="invalid literal/length code",s.mode=30;break e}S=65535&I,(E&=15)&&(p<E&&(g+=O[n++]<<p,p+=8),S+=g&(1<<E)-1,g>>>=E,p-=E),p<15&&(g+=O[n++]<<p,p+=8,g+=O[n++]<<p,p+=8),I=m[g&f];s:for(;;){if(g>>>=E=I>>>24,p-=E,!(16&(E=I>>>16&255))){if(!(64&E)){I=m[(65535&I)+(g&(1<<E)-1)];continue s}e.msg="invalid distance code",s.mode=30;break e}if(C=65535&I,p<(E&=15)&&(g+=O[n++]<<p,(p+=8)<E&&(g+=O[n++]<<p,p+=8)),c<(C+=g&(1<<E)-1)){e.msg="invalid distance too far back",s.mode=30;break e}if(g>>>=E,p-=E,(E=i-r)<C){if(l<(E=C-E)&&s.sane){e.msg="invalid distance too far back",s.mode=30;break e}if(y=h,(M=0)===d){if(M+=u-E,E<S){for(S-=E;A[i++]=h[M++],--E;);M=i-C,y=A}}else if(d<E){if(M+=u+d-E,(E-=d)<S){for(S-=E;A[i++]=h[M++],--E;);if(M=0,d<S){for(S-=E=d;A[i++]=h[M++],--E;);M=i-C,y=A}}}else if(M+=d-E,E<S){for(S-=E;A[i++]=h[M++],--E;);M=i-C,y=A}for(;2<S;)A[i++]=y[M++],A[i++]=y[M++],A[i++]=y[M++],S-=3;S&&(A[i++]=y[M++],1<S&&(A[i++]=y[M++]))}else{for(M=i-C;A[i++]=A[M++],A[i++]=A[M++],A[i++]=A[M++],2<(S-=3););S&&(A[i++]=A[M++],1<S&&(A[i++]=A[M++]))}break}}break}}while(n<o&&i<a);n-=S=p>>3,g&=(1<<(p-=S<<3))-1,e.next_in=n,e.next_out=i,e.avail_in=n<o?o-n+5:5-(n-o),e.avail_out=i<a?a-i+257:257-(i-a),s.hold=g,s.bits=p}},{}],8:[function(e,t,s){var n=e("../utils/common"),o=e("./adler32"),i=e("./crc32"),r=e("./inffast"),a=e("./inftrees"),c=1,u=2,l=0,d=-2,h=1,g=852,p=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 n.Buf16(320),this.work=new n.Buf16(288),this.lendyn=null,this.distdyn=null,this.sane=0,this.back=0,this.was=0}function v(e){var t;return e&&e.state?(t=e.state,e.total_in=e.total_out=t.total=0,e.msg="",t.wrap&&(e.adler=1&t.wrap),t.mode=h,t.last=0,t.havedict=0,t.dmax=32768,t.head=null,t.hold=0,t.bits=0,t.lencode=t.lendyn=new n.Buf32(g),t.distcode=t.distdyn=new n.Buf32(p),t.sane=1,t.back=-1,l):d}function f(e){var t;return e&&e.state?((t=e.state).wsize=0,t.whave=0,t.wnext=0,v(e)):d}function I(e,t){var s,n;return e&&e.state?(n=e.state,t<0?(s=0,t=-t):(s=1+(t>>4),t<48&&(t&=15)),t&&(t<8||15<t)?d:(null!==n.window&&n.wbits!==t&&(n.window=null),n.wrap=s,n.wbits=t,f(e))):d}function E(e,t){var s,n;return e?(n=new m,(e.state=n).window=null,(s=I(e,t))!==l&&(e.state=null),s):d}var S,C,M=!0;function y(e){if(M){var t;for(S=new n.Buf32(512),C=new n.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,S,0,e.work,{bits:9}),t=0;t<32;)e.lens[t++]=5;a(u,e.lens,0,32,C,0,e.work,{bits:5}),M=!1}e.lencode=S,e.lenbits=9,e.distcode=C,e.distbits=5}function O(e,t,s,o){var i,r=e.state;return null===r.window&&(r.wsize=1<<r.wbits,r.wnext=0,r.whave=0,r.window=new n.Buf8(r.wsize)),o>=r.wsize?(n.arraySet(r.window,t,s-r.wsize,r.wsize,0),r.wnext=0,r.whave=r.wsize):(o<(i=r.wsize-r.wnext)&&(i=o),n.arraySet(r.window,t,s-o,i,r.wnext),(o-=i)?(n.arraySet(r.window,t,s-o,o,0),r.wnext=o,r.whave=r.wsize):(r.wnext+=i,r.wnext===r.wsize&&(r.wnext=0),r.whave<r.wsize&&(r.whave+=i))),0}s.inflateReset=f,s.inflateReset2=I,s.inflateResetKeep=v,s.inflateInit=function(e){return E(e,15)},s.inflateInit2=E,s.inflate=function(e,t){var s,g,p,m,v,f,I,E,S,C,M,A,T,R,D,b,N,L,P,w,G,U,k,F,$=0,q=new n.Buf8(4),x=[16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15];if(!e||!e.state||!e.output||!e.input&&0!==e.avail_in)return d;12===(s=e.state).mode&&(s.mode=13),v=e.next_out,p=e.output,I=e.avail_out,m=e.next_in,g=e.input,f=e.avail_in,E=s.hold,S=s.bits,C=f,M=I,U=l;e:for(;;)switch(s.mode){case h:if(0===s.wrap){s.mode=13;break}for(;S<16;){if(0===f)break e;f--,E+=g[m++]<<S,S+=8}if(2&s.wrap&&35615===E){q[s.check=0]=255&E,q[1]=E>>>8&255,s.check=i(s.check,q,2,0),S=E=0,s.mode=2;break}if(s.flags=0,s.head&&(s.head.done=!1),!(1&s.wrap)||(((255&E)<<8)+(E>>8))%31){e.msg="incorrect header check",s.mode=30;break}if(8!=(15&E)){e.msg="unknown compression method",s.mode=30;break}if(S-=4,G=8+(15&(E>>>=4)),0===s.wbits)s.wbits=G;else if(G>s.wbits){e.msg="invalid window size",s.mode=30;break}s.dmax=1<<G,e.adler=s.check=1,s.mode=512&E?10:12,S=E=0;break;case 2:for(;S<16;){if(0===f)break e;f--,E+=g[m++]<<S,S+=8}if(s.flags=E,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=E>>8&1),512&s.flags&&(q[0]=255&E,q[1]=E>>>8&255,s.check=i(s.check,q,2,0)),S=E=0,s.mode=3;case 3:for(;S<32;){if(0===f)break e;f--,E+=g[m++]<<S,S+=8}s.head&&(s.head.time=E),512&s.flags&&(q[0]=255&E,q[1]=E>>>8&255,q[2]=E>>>16&255,q[3]=E>>>24&255,s.check=i(s.check,q,4,0)),S=E=0,s.mode=4;case 4:for(;S<16;){if(0===f)break e;f--,E+=g[m++]<<S,S+=8}s.head&&(s.head.xflags=255&E,s.head.os=E>>8),512&s.flags&&(q[0]=255&E,q[1]=E>>>8&255,s.check=i(s.check,q,2,0)),S=E=0,s.mode=5;case 5:if(1024&s.flags){for(;S<16;){if(0===f)break e;f--,E+=g[m++]<<S,S+=8}s.length=E,s.head&&(s.head.extra_len=E),512&s.flags&&(q[0]=255&E,q[1]=E>>>8&255,s.check=i(s.check,q,2,0)),S=E=0}else s.head&&(s.head.extra=null);s.mode=6;case 6:if(1024&s.flags&&(f<(A=s.length)&&(A=f),A&&(s.head&&(G=s.head.extra_len-s.length,s.head.extra||(s.head.extra=new Array(s.head.extra_len)),n.arraySet(s.head.extra,g,m,A,G)),512&s.flags&&(s.check=i(s.check,g,A,m)),f-=A,m+=A,s.length-=A),s.length))break e;s.length=0,s.mode=7;case 7:if(2048&s.flags){if(0===f)break e;for(A=0;G=g[m+A++],s.head&&G&&s.length<65536&&(s.head.name+=String.fromCharCode(G)),G&&A<f;);if(512&s.flags&&(s.check=i(s.check,g,A,m)),f-=A,m+=A,G)break e}else s.head&&(s.head.name=null);s.length=0,s.mode=8;case 8:if(4096&s.flags){if(0===f)break e;for(A=0;G=g[m+A++],s.head&&G&&s.length<65536&&(s.head.comment+=String.fromCharCode(G)),G&&A<f;);if(512&s.flags&&(s.check=i(s.check,g,A,m)),f-=A,m+=A,G)break e}else s.head&&(s.head.comment=null);s.mode=9;case 9:if(512&s.flags){for(;S<16;){if(0===f)break e;f--,E+=g[m++]<<S,S+=8}if(E!==(65535&s.check)){e.msg="header crc mismatch",s.mode=30;break}S=E=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(;S<32;){if(0===f)break e;f--,E+=g[m++]<<S,S+=8}e.adler=s.check=_(E),S=E=0,s.mode=11;case 11:if(0===s.havedict)return e.next_out=v,e.avail_out=I,e.next_in=m,e.avail_in=f,s.hold=E,s.bits=S,2;e.adler=s.check=1,s.mode=12;case 12:if(5===t||6===t)break e;case 13:if(s.last){E>>>=7&S,S-=7&S,s.mode=27;break}for(;S<3;){if(0===f)break e;f--,E+=g[m++]<<S,S+=8}switch(s.last=1&E,S-=1,3&(E>>>=1)){case 0:s.mode=14;break;case 1:if(y(s),s.mode=20,6!==t)break;E>>>=2,S-=2;break e;case 2:s.mode=17;break;case 3:e.msg="invalid block type",s.mode=30}E>>>=2,S-=2;break;case 14:for(E>>>=7&S,S-=7&S;S<32;){if(0===f)break e;f--,E+=g[m++]<<S,S+=8}if((65535&E)!=(E>>>16^65535)){e.msg="invalid stored block lengths",s.mode=30;break}if(s.length=65535&E,S=E=0,s.mode=15,6===t)break e;case 15:s.mode=16;case 16:if(A=s.length){if(f<A&&(A=f),I<A&&(A=I),0===A)break e;n.arraySet(p,g,m,A,v),f-=A,m+=A,I-=A,v+=A,s.length-=A;break}s.mode=12;break;case 17:for(;S<14;){if(0===f)break e;f--,E+=g[m++]<<S,S+=8}if(s.nlen=257+(31&E),E>>>=5,S-=5,s.ndist=1+(31&E),E>>>=5,S-=5,s.ncode=4+(15&E),E>>>=4,S-=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(;S<3;){if(0===f)break e;f--,E+=g[m++]<<S,S+=8}s.lens[x[s.have++]]=7&E,E>>>=3,S-=3}for(;s.have<19;)s.lens[x[s.have++]]=0;if(s.lencode=s.lendyn,s.lenbits=7,k={bits:s.lenbits},U=a(0,s.lens,0,19,s.lencode,0,s.work,k),s.lenbits=k.bits,U){e.msg="invalid code lengths set",s.mode=30;break}s.have=0,s.mode=19;case 19:for(;s.have<s.nlen+s.ndist;){for(;b=($=s.lencode[E&(1<<s.lenbits)-1])>>>16&255,N=65535&$,!((D=$>>>24)<=S);){if(0===f)break e;f--,E+=g[m++]<<S,S+=8}if(N<16)E>>>=D,S-=D,s.lens[s.have++]=N;else{if(16===N){for(F=D+2;S<F;){if(0===f)break e;f--,E+=g[m++]<<S,S+=8}if(E>>>=D,S-=D,0===s.have){e.msg="invalid bit length repeat",s.mode=30;break}G=s.lens[s.have-1],A=3+(3&E),E>>>=2,S-=2}else if(17===N){for(F=D+3;S<F;){if(0===f)break e;f--,E+=g[m++]<<S,S+=8}S-=D,G=0,A=3+(7&(E>>>=D)),E>>>=3,S-=3}else{for(F=D+7;S<F;){if(0===f)break e;f--,E+=g[m++]<<S,S+=8}S-=D,G=0,A=11+(127&(E>>>=D)),E>>>=7,S-=7}if(s.have+A>s.nlen+s.ndist){e.msg="invalid bit length repeat",s.mode=30;break}for(;A--;)s.lens[s.have++]=G}}if(30===s.mode)break;if(0===s.lens[256]){e.msg="invalid code -- missing end-of-block",s.mode=30;break}if(s.lenbits=9,k={bits:s.lenbits},U=a(c,s.lens,0,s.nlen,s.lencode,0,s.work,k),s.lenbits=k.bits,U){e.msg="invalid literal/lengths set",s.mode=30;break}if(s.distbits=6,s.distcode=s.distdyn,k={bits:s.distbits},U=a(u,s.lens,s.nlen,s.ndist,s.distcode,0,s.work,k),s.distbits=k.bits,U){e.msg="invalid distances set",s.mode=30;break}if(s.mode=20,6===t)break e;case 20:s.mode=21;case 21:if(6<=f&&258<=I){e.next_out=v,e.avail_out=I,e.next_in=m,e.avail_in=f,s.hold=E,s.bits=S,r(e,M),v=e.next_out,p=e.output,I=e.avail_out,m=e.next_in,g=e.input,f=e.avail_in,E=s.hold,S=s.bits,12===s.mode&&(s.back=-1);break}for(s.back=0;b=($=s.lencode[E&(1<<s.lenbits)-1])>>>16&255,N=65535&$,!((D=$>>>24)<=S);){if(0===f)break e;f--,E+=g[m++]<<S,S+=8}if(b&&!(240&b)){for(L=D,P=b,w=N;b=($=s.lencode[w+((E&(1<<L+P)-1)>>L)])>>>16&255,N=65535&$,!(L+(D=$>>>24)<=S);){if(0===f)break e;f--,E+=g[m++]<<S,S+=8}E>>>=L,S-=L,s.back+=L}if(E>>>=D,S-=D,s.back+=D,s.length=N,0===b){s.mode=26;break}if(32&b){s.back=-1,s.mode=12;break}if(64&b){e.msg="invalid literal/length code",s.mode=30;break}s.extra=15&b,s.mode=22;case 22:if(s.extra){for(F=s.extra;S<F;){if(0===f)break e;f--,E+=g[m++]<<S,S+=8}s.length+=E&(1<<s.extra)-1,E>>>=s.extra,S-=s.extra,s.back+=s.extra}s.was=s.length,s.mode=23;case 23:for(;b=($=s.distcode[E&(1<<s.distbits)-1])>>>16&255,N=65535&$,!((D=$>>>24)<=S);){if(0===f)break e;f--,E+=g[m++]<<S,S+=8}if(!(240&b)){for(L=D,P=b,w=N;b=($=s.distcode[w+((E&(1<<L+P)-1)>>L)])>>>16&255,N=65535&$,!(L+(D=$>>>24)<=S);){if(0===f)break e;f--,E+=g[m++]<<S,S+=8}E>>>=L,S-=L,s.back+=L}if(E>>>=D,S-=D,s.back+=D,64&b){e.msg="invalid distance code",s.mode=30;break}s.offset=N,s.extra=15&b,s.mode=24;case 24:if(s.extra){for(F=s.extra;S<F;){if(0===f)break e;f--,E+=g[m++]<<S,S+=8}s.offset+=E&(1<<s.extra)-1,E>>>=s.extra,S-=s.extra,s.back+=s.extra}if(s.offset>s.dmax){e.msg="invalid distance too far back",s.mode=30;break}s.mode=25;case 25:if(0===I)break e;if(A=M-I,s.offset>A){if((A=s.offset-A)>s.whave&&s.sane){e.msg="invalid distance too far back",s.mode=30;break}A>s.wnext?(A-=s.wnext,T=s.wsize-A):T=s.wnext-A,A>s.length&&(A=s.length),R=s.window}else R=p,T=v-s.offset,A=s.length;for(I<A&&(A=I),I-=A,s.length-=A;p[v++]=R[T++],--A;);0===s.length&&(s.mode=21);break;case 26:if(0===I)break e;p[v++]=s.length,I--,s.mode=21;break;case 27:if(s.wrap){for(;S<32;){if(0===f)break e;f--,E|=g[m++]<<S,S+=8}if(M-=I,e.total_out+=M,s.total+=M,M&&(e.adler=s.check=s.flags?i(s.check,p,M,v-M):o(s.check,p,M,v-M)),M=I,(s.flags?E:_(E))!==s.check){e.msg="incorrect data check",s.mode=30;break}S=E=0}s.mode=28;case 28:if(s.wrap&&s.flags){for(;S<32;){if(0===f)break e;f--,E+=g[m++]<<S,S+=8}if(E!==(4294967295&s.total)){e.msg="incorrect length check",s.mode=30;break}S=E=0}s.mode=29;case 29:U=1;break e;case 30:U=-3;break e;case 31:return-4;default:return d}return e.next_out=v,e.avail_out=I,e.next_in=m,e.avail_in=f,s.hold=E,s.bits=S,(s.wsize||M!==e.avail_out&&s.mode<30&&(s.mode<27||4!==t))&&O(e,e.output,e.next_out,M-e.avail_out)?(s.mode=31,-4):(C-=e.avail_in,M-=e.avail_out,e.total_in+=C,e.total_out+=M,s.total+=M,s.wrap&&M&&(e.adler=s.check=s.flags?i(s.check,p,M,e.next_out-M):o(s.check,p,M,e.next_out-M)),e.data_type=s.bits+(s.last?64:0)+(12===s.mode?128:0)+(20===s.mode||15===s.mode?256:0),(0===C&&0===M||4===t)&&U===l&&(U=-5),U)},s.inflateEnd=function(e){if(!e||!e.state)return d;var t=e.state;return t.window&&(t.window=null),e.state=null,l},s.inflateGetHeader=function(e,t){var s;return e&&e.state&&2&(s=e.state).wrap?((s.head=t).done=!1,l):d},s.inflateSetDictionary=function(e,t){var s,n=t.length;return e&&e.state?0!==(s=e.state).wrap&&11!==s.mode?d:11===s.mode&&o(1,t,n,0)!==s.check?-3:O(e,t,n,n)?(s.mode=31,-4):(s.havedict=1,l):d},s.inflateInfo="pako inflate (from Nodeca project)"},{"../utils/common":1,"./adler32":3,"./crc32":5,"./inffast":7,"./inftrees":9}],9:[function(e,t,s){var n=e("../utils/common"),o=[3,4,5,6,7,8,9,10,11,13,15,17,19,23,27,31,35,43,51,59,67,83,99,115,131,163,195,227,258,0,0],i=[16,16,16,16,16,16,16,16,17,17,17,17,18,18,18,18,19,19,19,19,20,20,20,20,21,21,21,21,16,72,78],r=[1,2,3,4,5,7,9,13,17,25,33,49,65,97,129,193,257,385,513,769,1025,1537,2049,3073,4097,6145,8193,12289,16385,24577,0,0],a=[16,16,16,16,17,17,18,18,19,19,20,20,21,21,22,22,23,23,24,24,25,25,26,26,27,27,28,28,29,29,64,64];t.exports=function(e,t,s,c,u,l,d,h){var g,p,_,m,v,f,I,E,S,C=h.bits,M=0,y=0,O=0,A=0,T=0,R=0,D=0,b=0,N=0,L=0,P=null,w=0,G=new n.Buf16(16),U=new n.Buf16(16),k=null,F=0;for(M=0;M<=15;M++)G[M]=0;for(y=0;y<c;y++)G[t[s+y]]++;for(T=C,A=15;1<=A&&0===G[A];A--);if(A<T&&(T=A),0===A)return u[l++]=20971520,u[l++]=20971520,h.bits=1,0;for(O=1;O<A&&0===G[O];O++);for(T<O&&(T=O),M=b=1;M<=15;M++)if(b<<=1,(b-=G[M])<0)return-1;if(0<b&&(0===e||1!==A))return-1;for(U[1]=0,M=1;M<15;M++)U[M+1]=U[M]+G[M];for(y=0;y<c;y++)0!==t[s+y]&&(d[U[t[s+y]]++]=y);if(0===e?(P=k=d,f=19):1===e?(P=o,w-=257,k=i,F-=257,f=256):(P=r,k=a,f=-1),M=O,v=l,D=y=L=0,_=-1,m=(N=1<<(R=T))-1,1===e&&852<N||2===e&&592<N)return 1;for(;;){for(I=M-D,d[y]<f?(E=0,S=d[y]):d[y]>f?(E=k[F+d[y]],S=P[w+d[y]]):(E=96,S=0),g=1<<M-D,O=p=1<<R;u[v+(L>>D)+(p-=g)]=I<<24|E<<16|S,0!==p;);for(g=1<<M-1;L&g;)g>>=1;if(0!==g?(L&=g-1,L+=g):L=0,y++,0==--G[M]){if(M===A)break;M=t[s+d[y]]}if(T<M&&(L&m)!==_){for(0===D&&(D=T),v+=O,b=1<<(R=M-D);R+D<A&&!((b-=G[R+D])<=0);)R++,b<<=1;if(N+=1<<R,1===e&&852<N||2===e&&592<N)return 1;u[_=L&m]=T<<24|R<<16|v-l}}return 0!==L&&(u[v+L]=M-D<<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 n=e("./zlib/inflate"),o=e("./utils/common"),i=e("./utils/strings"),r=e("./zlib/constants"),a=e("./zlib/messages"),c=e("./zlib/zstream"),u=e("./zlib/gzheader"),l=Object.prototype.toString;function d(e){if(!(this instanceof d))return new d(e);this.options=o.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=n.inflateInit2(this.strm,t.windowBits);if(s!==r.Z_OK)throw new Error(a[s]);if(this.header=new u,n.inflateGetHeader(this.strm,this.header),t.dictionary&&("string"==typeof t.dictionary?t.dictionary=i.string2buf(t.dictionary):"[object ArrayBuffer]"===l.call(t.dictionary)&&(t.dictionary=new Uint8Array(t.dictionary)),t.raw&&(s=n.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,u,d,h=this.strm,g=this.options.chunkSize,p=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]"===l.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 o.Buf8(g),h.next_out=0,h.avail_out=g),(s=n.inflate(h,r.Z_NO_FLUSH))===r.Z_NEED_DICT&&p&&(s=n.inflateSetDictionary(this.strm,p)),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),u=h.next_out-c,d=i.buf2string(h.output,c),h.next_out=u,h.avail_out=g-u,u&&o.arraySet(h.output,h.output,c,u,0),this.onData(d)):this.onData(o.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=n.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=o.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")}(Xt)),Xt.exports);var es=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=xt,this._currentConnectState=Ft,this._beforeSendInterceptors=[]}init(){ht.addTask({id:Ut,intervalMs:1e3,callback:this._executeScheduledTaskIfReady,context:this}),this._updateIsBinarySupported(),this._url=function(e){const t=Be.get("instance"),{sdkAppId:s,testEnv:n,disableIndependentDomain:o}=t,i=nt(s);let r="";return n?r=et.TEST[i].DEFAULT:o?(r=et.PRODUCTION[i].DEFAULT,rt=ot.DEFAULT):r=et.PRODUCTION[i].INITIAL.replace("*",`${s}`),ct(r,{isBinary:e})}(this._isBinarySupported),be.subscribeInnerEvent("networkStatusChange",this._handleNetworkStatusChange,this),be.subscribeInnerEvent("activityStatusChange",this._handleActivityStatusChange,this),this.connect()}sendPacket(e,t){var s;const{requestId:n,timeout:o=wt,canResend:i=!0}=t||{};if(ve(e))return Pt.warn("sendPacket",`${Gt}.sendPacket: packet is empty `),null;this._executeBeforeSendInterceptors(e),this._currentConnectState===qt&&this._handleConnectStateChange({state:qt,shouldEmitEvent:!0,shouldAttemptReconnect:!0,reason:jt});const r=JSON.stringify(e);let a=null;if(n){const{resolve:e,reject:t,promise:s}=Ee();a=s,this._pendingRequests.set(n,{resolve:e,reject:t,timestamp:Date.now(),uplinkData:r,timeout:o,canResend:i})}const c=this._isBinarySupported?gt(r).buffer:r;return null===(s=this._socketAdapter)||void 0===s||s.send(c),a}connect(){var e;this._socketAdapter=new je(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=`${Gt}.connect isWorkerEnabled: false socketID:${t} url:${this._url}`;this._connectionId=t,this._ssoLog({method:"connect",message:s})}disconnect(){var e,t;const s=null===(e=this._socketAdapter)||void 0===e?void 0:e.getId(),n=`${Gt}.disconnect socketID:${s}`;this._ssoLog({method:"disconnect",message:n}),this._removeEventListeners(),null===(t=this._socketAdapter)||void 0===t||t.disconnect()}getSocketAdapter(){return this._socketAdapter}dispose(){console.log(`${Gt}.dispose`),ht.removeTask(Ut),ht.removeTask(kt),be.unSubscribeInnerEvent("networkStatusChange",this._handleNetworkStatusChange,this),be.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=xt,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===$t&&this._isReconnecting;return!this._socketAdapter||e}reconnect(){return de(this,void 0,void 0,function*(){const e=`${Gt}.reconnect isReconnecting: ${this._isReconnecting} currentConnectState: ${this._currentConnectState}`;if(this._ssoLog({method:"reconnect",message:e}),!this._shouldSkipReconnect()){this._url=ut(this._isBinarySupported);try{this._isReconnecting=!0,this.disconnect(),this.connect()}catch(e){this._isReconnecting=!1,this._handleConnectStateChange({state:qt,shouldEmitEvent:!0,shouldAttemptReconnect:!0,reason:Kt}),console.warn(`${Gt}.reconnect failed: `,e)}}})}_addEventListeners(){var e,t,s,n,o;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===(n=this._socketAdapter)||void 0===n||n.on("error",this._onError,this),null===(o=this._socketAdapter)||void 0===o||o.on("sendFail",this._onSendFail,this)}_removeEventListeners(){var e,t,s,n,o;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===(n=this._socketAdapter)||void 0===n||n.off("error",this._onError,this),null===(o=this._socketAdapter)||void 0===o||o.off("sendFail",this._onSendFail,this)}_onClose(e){const{socketId:t,event:s}=e||{},n=0!==this._connectionEstablishedTime?Date.now()-this._connectionEstablishedTime:0,o=`${Gt}.onClose closeSocketID: ${t} currentSocketID: ${this._connectionId} connectionDuration: ${n} code: ${null==s?void 0:s.code} reason: ${null==s?void 0:s.reason}`;this._ssoLog({method:"onClose",message:o}),t===this._connectionId&&this._handleConnectStateChange({state:qt,shouldEmitEvent:!0,shouldAttemptReconnect:!0,reason:Wt}),this._isReconnecting&&(this._isReconnecting=!1)}_onError(e){const{socketId:t,error:s}=e||{},n=`${Gt}.onError sourceSocketID: ${t} currentSocketID: ${this._connectionId} isReconnecting: ${this._isReconnecting} error: ${JSON.stringify(s)}`;this._ssoLog({method:"onError",message:n}),t===this._connectionId&&this._handleConnectStateChange({state:qt,shouldEmitEvent:!0,shouldAttemptReconnect:!0,reason:Ht}),this._isReconnecting&&(this._isReconnecting=!1)}_onSendFail(e){const{socketId:t,error:s}=e||{},n=`${Gt}.onSendFail sendFailSocketId: ${t} currentSocketID: ${this._connectionId} isReconnecting: ${this._isReconnecting} error: ${s}`;this._ssoLog({method:"onSendFail",message:n}),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=Zt.inflate(t,{to:"string"})}catch(e){console.error("inflate error",e)}return s})(e.data):function(e){const t=new Uint8Array(e);let s="",n=0;const{length:o}=t;for(;n<o;){let e=t[n],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),o-n-i>0)for(let s=0;s<i;s+=1)e=t[n+s+1],r=r<<6|63&e;else r=65533,i=o-n;s+=String.fromCodePoint(r),n+=i+1}return s}(e.data):e.data,s=JSON.parse(t)}catch(t){const s=e.data;return void this._ssoLog({method:"jsonParseError",message:s})}if(!s||!s.head)return;const{seq:n,servcmd:o}=s.head,i=`${n}${o}`;this._pendingRequests.has(i)?this._handleRequestResponse(s):this._handlePushMessage(s)}_handleRequestResponse(e){var t,s;const{seq:n,servcmd:o}=e.head,{int32_error_code:i,str_error_message:r}=(null==e?void 0:e.body)||{},a=(null===(t=null==e?void 0:e.body)||void 0===t?void 0:t.ErrorCode)||i,c=(null===(s=null==e?void 0:e.body)||void 0===s?void 0:s.ErrorInfo)||r,u=`${n}${o}`,{resolve:l,reject:d,timestamp:h,headSeq:g}=this._pendingRequests.get(u);if(this._pendingRequests.delete(u),a&&0!==a)return be.emitInnerEvent("error",{errorCode:a,errorInfo:c}),void d({errorCode:a,errorInfo:c});l(e.body)}_handlePushMessage(e){const{servcmd:t}=e.head,{NeedAck:s,SessionData:n}=e.body;1===s&&this._sendAck(n),be.emitInnerEvent(t,e)}_checkPendingRequestsAndResend(){var e;Pt.debug("_checkPendingRequestsAndResend",` reConnectFlag:${this._isReconnecting} promiseMap.size:${this._pendingRequests.size}`),null===(e=this._pendingRequests)||void 0===e||e.forEach((e,t)=>{var s;const{uplinkData:n,canResend:o,resolve:i,reject:r,timeout:a}=e;if(o){this._pendingRequests.set(t,{resolve:i,reject:r,timestamp:Date.now(),uplinkData:n,timeout:a,canResend:o});const e=this._isBinarySupported?gt(n).buffer:n;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 n=Date.now()-this._connectionStartTime,o=`${Gt}.onConnect cost:${n} ms. socketID:${t} res:${JSON.stringify(s)}`;if(this._ssoLog({method:"onConnect",message:o}),this._checkPendingRequestsAndResend(),this._sendHeartbeatIfReady(),this._isReconnecting){const e=`${Gt}.reconnect success`;this._ssoLog({method:"reconnectSuccess",message:e}),be.emitInnerEvent(At.RECONNECTED),this._isReconnecting=!1}this._resetReconnectDelay(),this._handleConnectStateChange({state:Ft,shouldEmitEvent:!0,shouldAttemptReconnect:!1})}_sendAck(e){const t=mt({servcmd:"openim.ws_msg_push_ack",data:{SessionData:e}});this.sendPacket(t)}_executeScheduledTaskIfReady(){return de(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 de(this,void 0,void 0,function*(){var e;const t=mt({servcmd:"heartbeat.alive",data:{}});try{const e=`${t.head.seq}${t.head.servcmd}`;yield this.sendPacket(t,{requestId:e,timeout:3e3})}catch(t){const s=null===(e=Be.get("netWorkMonitor"))||void 0===e?void 0:e.isNetWorkOnline,n=`${Gt}.sendHeartbeat failed. isNetWorkOnline:${s} error: ${t}`;this._ssoLog({method:"sendHeartbeatError",message:n}),this._handleConnectStateChange({state:qt,shouldEmitEvent:!0,shouldAttemptReconnect:!0})}})}_sendHeartbeatIfReady(){return de(this,void 0,void 0,function*(){this._canSendHeartbeat()&&(this._isHeartbeatInProgress=!0,yield this._sendHeartbeat(),this._isHeartbeatInProgress=!1)})}_updateHeartbeatTime(){this._nextHeartbeatAt=L?Date.now()+5e3:Date.now()+1e4}_handleNetworkStatusChange(e){const t=`${Gt}.networkStatusChange ${JSON.stringify(e)}`;this._ssoLog({method:"networkStatusChange",message:t});const{isNetworkOnline:s,networkType:n}=e;s&&"none"!==n?this._handleConnectStateChange({state:Ft,shouldEmitEvent:!1,shouldAttemptReconnect:!0,reason:Vt}):this._handleConnectStateChange({state:qt,shouldEmitEvent:!1,shouldAttemptReconnect:!0,reason:Vt})}isPrivateNetWork(){const e=Be.get("instance")||{};return e.proxyServer&&!e.fileDownloadProxy}_handleConnectStateChange(e){const{state:t,shouldAttemptReconnect:s,shouldEmitEvent:n,reason:o}=e,i=`${Gt}._handleConnectStateChange currentConnectState: ${this._currentConnectState} shouldAttemptReconnect: ${s} shouldEmitEvent: ${n} reason: ${o}`;this._currentConnectState!==t&&(this._ssoLog({method:"handleConnectStateChange",message:i}),n&&(Pt.info("_handleConnectStateChange",` from ${this._currentConnectState} to ${t}`),be.emitOuterEvent("netStateChange",{name:"netStateChange",data:{state:t}}),this._currentConnectState=t,t===qt&&be.emitInnerEvent(At.SOCKET_DISCONNECTED)),s&&(this._resetReconnectDelay(),ht.addTask({id:kt,intervalMs:this._intendedDelay,callback:this._scheduleReconnectWithBackoff,context:this})))}_handleActivityStatusChange(e){var t,s;const n=null===(s=null===(t=this._socketAdapter)||void 0===t?void 0:t._ws)||void 0===s?void 0:s.readyState,o=`${Gt}.activityStatusChange ${JSON.stringify(e)} readyState: ${n}`;this._ssoLog({method:"activityStatusChange",message:o}),3===n&&this._handleConnectStateChange({state:qt,shouldEmitEvent:!0,shouldAttemptReconnect:!0,reason:Bt})}_resetReconnectDelay(){var e;Pt.debug(`${Gt}._resetReconnectDelay`),ht.removeTask(kt);const t=null===(e=Be.get("activityMonitor"))||void 0===e?void 0:e.isActive;this._intendedDelay=t?xt:1e3}_scheduleReconnectWithBackoff(){var e;const t=null===(e=Be.get("activityMonitor"))||void 0===e?void 0:e.isActive;this._intendedDelay=t?Math.min(5e3,Math.max(xt,1.5*this._intendedDelay)):Math.min(3e5,Math.max(1e3,1.5*this._intendedDelay));const s=(new Date).toTimeString().slice(0,8),n=`${Gt}.scheduleReconnectWithBackoff timeStr: ${s} intendedDelay: ${this._intendedDelay}`;Pt.debug(n),this.reconnect(),ht.updateTaskInterval(kt,this._intendedDelay)}_ssoLog(e){const{method:t,message:s}=e;Pt.info(t,s)}_diagnose(){this.isPrivateNetWork()||(this._lastDiagnoseAt=Date.now(),function(e){de(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 me({method:"GET",url:s,data:{}})}catch(e){Pt.warn("diagnoseBySSO",`diagnoseBySSO failed. error:${e.message}`)}})}(this._url),function(e){de(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 me({method:"GET",url:t,data:{}})}catch(e){Pt.warn(`diagnoseByCDN', 'diagnoseByCDN failed. error:${e.message}`)}})}(this._url),this._beforeSendInterceptors=[])}_clearTimeoutRequest(){for(const[e,t]of this._pendingRequests.entries()){const{reject:s,timestamp:n,timeout:o}=t;Date.now()-n>=o&&(this._pendingRequests.delete(e),Date.now()-this._lastDiagnoseAt>=3e4&&this._diagnose(),s({errorCode:ge,errorInfo:"NETWORK_TIMEOUT",data:{requestId:e}}))}}_updateIsBinarySupported(){var e;if(null===(e=Be.get("instance"))||void 0===e?void 0:e.devMode)return void(this._isBinarySupported=!1);const t=ue();(b||y&&"windows"===t||L)&&(this._isBinarySupported=!1)}_isCompressedData(e){const t=new Uint8Array(e);return 67===t[0]&&79===t[1]&&77===t[2]&&80===t[3]}};const ts={init:function(e){Be.set("instance",e),es.init()},destroy:function(){es.dispose(),Be.clear(),ht.dispose()},notificationCenter:be,channel:es,store:Be,ssoLog:Pt,utils:Ce,common:Ct,constants:C};const ss=e=>"function"==typeof e;function ns(e,t,s){const n=s||[];if(!e||!t)return!1;const o=Object.keys(e).filter(e=>!n.includes(e)),i=Object.keys(t).filter(e=>!n.includes(e));return o.length===i.length&&o.every(n=>!!t.hasOwnProperty(n)&&("object"==typeof e[n]&&null!==e[n]?ns(e[n],t[n],s):e[n]===t[n]))}var os;!function(e){e.SDK_READY="sdkStateReady",e.SDK_NOT_READY="sdkStateNotReady",e.SDK_DESTROY="sdkDestroy",e.MESSAGE_RECEIVED="onMessageReceived",e.ROOM_CUSTOM_DATA_RECEIVED="onRoomCustomDataReceived",e.MESSAGE_MODIFIED="onMessageModified",e.MESSAGE_REVOKED="onMessageRevoked",e.MESSAGE_READ_BY_PEER="onMessageReadByPeer",e.MESSAGE_READ_RECEIPT_RECEIVED="onMessageReadReceiptReceived",e.MESSAGE_EXTENSIONS_UPDATED="onMessageExtensionsUpdated",e.MESSAGE_EXTENSIONS_DELETED="onMessageExtensionsDeleted",e.MESSAGE_REACTIONS_UPDATED="onMessageReactionsUpdated",e.CONVERSATION_LIST_UPDATED="onConversationListUpdated",e.TOTAL_UNREAD_MESSAGE_COUNT_UPDATED="onTotalUnreadMessageCountUpdated",e.CONVERSATION_GROUP_LIST_UPDATED="onConversationGroupListUpdated",e.CONVERSATION_IN_GROUP_UPDATED="onConversationInGroupUpdated",e.GROUP_LIST_UPDATED="onGroupListUpdated",e.GROUP_ATTRIBUTES_UPDATED="groupAttributesUpdated",e.GROUP_COUNTER_UPDATED="onGroupCounterUpdated",e.TOPIC_CREATED="onTopicCreated",e.TOPIC_DELETED="onTopicDeleted",e.TOPIC_UPDATED="onTopicUpdated",e.PROFILE_UPDATED="onProfileUpdated",e.USER_STATUS_UPDATED="onUserStatusUpdated",e.BLACKLIST_UPDATED="blacklistUpdated",e.FRIEND_LIST_UPDATED="onFriendListUpdated",e.FRIEND_GROUP_LIST_UPDATED="onFriendGroupListUpdated",e.FRIEND_APPLICATION_LIST_UPDATED="onFriendApplicationListUpdated",e.MY_FOLLOWERS_LIST_UPDATED="onMyFollowersListUpdated",e.MY_FOLLOWING_LIST_UPDATED="onMyFollowingListUpdated",e.MUTUAL_FOLLOWERS_LIST_UPDATED="onMutualFollowersListUpdated",e.KICKED_OUT="kickedOut",e.ERROR="error",e.NET_STATE_CHANGE="netStateChange",e.ALL_RECEIVE_MESSAGE_OPT_UPDATED="onAllReceiveMessageOptUpdated",e.SERVER_CONFIG_UPDATED="onServerConfigUpdated",e.PINNED_GROUP_MESSAGE_UPDATED="onPinnedGroupMessageUpdated"}(os||(os={}));var is,rs=os;!function(e){e.LOGOUT="logout",e.DESTROY="destroy",e.CLOUD_CONFIG_UPDATE="cloud_config_update",e.PROFILE_UPDATE="profile_updated",e.ERROR="error",e.RECONNECTED="reconnected",e.FORCE_OFFLINE="im_open_status.stat_forceoffline",e.COMMERCIAL_CONFIG_PUSH="im_sdk_config_mgr.push_imsdk_purchase_bitsv2",e.OVERLOAD_PUSH="OverLoadPush.notify2",e.NEW_MESSAGE="new_message",e.MESSAGE_PUSH="im_open_push.msg_push",e.MESSAGE_DELETED="message_deleted",e.MESSAGE_REVOKED="message_revoked",e.MESSAGE_MODIFIED="message_modified",e.SOCKET_DISCONNECTED="socket_disconnected",e.CONVERSATION_UPDATED="conversation_updated",e.TOPIC_MESSAGE_DELETED="topic_message_deleted",e.TOPIC_MESSAGE_REVOKED="topic_message_revoked",e.TOPIC_MESSAGE_MODIFIED="topic_message_modified",e.TOPIC_NEW_MESSAGE="topic_new_message",e.QUALITY_STAT="quality_stat",e.SYNC_CONVERSATION_LIST="sync_conversation_list"}(is||(is={}));var as,cs=is;!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"}(as||(as={}));var us=as;const ls=Object.assign({},{KICKED_OUT_MULT_ACCOUNT:"multipleAccount",KICKED_OUT_MULT_DEVICE:"multipleDevice",KICKED_OUT_USERSIG_EXPIRED:"userSigExpired",KICKED_OUT_REST_API:"REST_API_Kick"}),ds={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 hs;!function(e){e.UNSENT="unSend",e.SUCCESS="success",e.FAIL="fail"}(hs||(hs={}));const gs={modify:cs.MESSAGE_MODIFIED,delete:cs.MESSAGE_DELETED,revoke:cs.MESSAGE_REVOKED};var ps;!function(e){e[e.FORWARD=0]="FORWARD",e[e.BACKWARD=1]="BACKWARD"}(ps||(ps={}));const _s=Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},ds),{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:hs,Direction:ps}),ms={[gs.modify]:cs.TOPIC_MESSAGE_MODIFIED,[gs.delete]:cs.TOPIC_MESSAGE_DELETED,[gs.revoke]:cs.TOPIC_MESSAGE_REVOKED},vs={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"},fs=Object.assign({},vs),Is={CONV_C2C:"C2C",CONV_GROUP:"GROUP",CONV_TOPIC:"TOPIC",CONV_SYSTEM:"@TIM#SYSTEM"},Es=Object.assign(Object.assign(Object.assign(Object.assign({},Is),{CONV_AT_ME:1,CONV_AT_ALL:2,CONV_AT_ALL_AT_ME:3}),{CONV_MARK_TYPE_STAR:1,CONV_MARK_TYPE_UNREAD:2,CONV_MARK_TYPE_FOLD:4,CONV_MARK_TYPE_HIDE:8}),{READ_ALL_C2C_MSG:"readAllC2CMessage",READ_ALL_GROUP_MSG:"readAllGroupMessage",READ_ALL_MSG:"readAllMessage"}),Ss=Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},{SNS_TYPE_NO_RELATION:"CheckResult_Type_NoRelation",SNS_TYPE_A_WITH_B:"CheckResult_Type_AWithB",SNS_TYPE_B_WITH_A:"CheckResult_Type_BWithA",SNS_TYPE_BOTH_WAY:"CheckResult_Type_BothWay"}),{ALLOW_TYPE_ALLOW_ANY:"AllowType_Type_AllowAny",ALLOW_TYPE_NEED_CONFIRM:"AllowType_Type_NeedConfirm",ALLOW_TYPE_DENY_ANY:"AllowType_Type_DenyAny"}),{SNS_ADD_TYPE_SINGLE:"Add_Type_Single",SNS_ADD_TYPE_BOTH:"Add_Type_Both"}),{SNS_DELETE_TYPE_SINGLE:"Delete_Type_Single",SNS_DELETE_TYPE_BOTH:"Delete_Type_Both"}),{SNS_APPLICATION_TYPE_BOTH:"Pendency_Type_Both",SNS_APPLICATION_SENT_TO_ME:"Pendency_Type_ComeIn",SNS_APPLICATION_SENT_BY_ME:"Pendency_Type_SendOut",SNS_APPLICATION_AGREE:"Response_Action_Agree",SNS_APPLICATION_AGREE_AND_ADD:"Response_Action_AgreeAndAdd"}),{SNS_CHECK_TYPE_BOTH:"CheckResult_Type_Both",SNS_CHECK_TYPE_SINGLE:"CheckResult_Type_Single"}),{FORBID_TYPE_NONE:"AdminForbid_Type_None",FORBID_TYPE_SEND_OUT:"AdminForbid_Type_SendOut"}),Cs={GRP_WORK:"Private",GRP_PUBLIC:"Public",GRP_MEETING:"ChatRoom",GRP_AVCHATROOM:"AVChatRoom",GRP_COMMUNITY:"Community",GRP_ROOM:"Room",GRP_LIVE:"Live"},Ms={COMMUNITY:"@TGS#_",TOPIC:"@TOPIC#_"},ys={JOINED:1,QUITTED:2,KICKED:3,ADMIN_SET:4,ADMIN_CANCELED:5,GROUP_PROFILE_UPDATED:6,GROUP_MEMBER_PROFILE_UPDATED:7,TOPIC_PROFILE_UPDATED:8},Os=Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},Cs),{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:Ms,GROUP_TIPS_OPERATION_TYPE:ys}),As=Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},ls),_s),fs),Es),Ss),Os),{IOS_OFFLINE_PUSH_NO_SOUND:"push.no_sound",IOS_OFFLINE_PUSH_DEFAULT_SOUND:"default"}),{NET_STATE_CONNECTING:"connecting",NET_STATE_DISCONNECTED:"disconnected"}),Ts={NO_SDKAPPID:2e3,NO_TINYID:2022,NO_A2KEY:2023,USER_NOT_LOGGED_IN:2024,REPEAT_LOGIN:2025,MSG_SEND_FAIL:2100,MSG_SEND_FAIL_NOT_IN_AV:2101,MSG_SEND_GRP_WITH_TOPIC_FAIL:2115,MSG_INSTANCE_REQUIRED:2105,MSG_INVALID_CONV_TYPE:2106,MSG_REVOKE_FAIL:2110,MSG_DELETE_FAIL:2111,MSG_UNREAD_ALL_FAIL:2112,READ_RECEIPT_MSG_LIST_EMPTY:2114,CANNOT_DELETE_GRP_SYSTEM_NOTICE:2116,NOT_MY_FRIEND:2700,NETWORK_ERROR:2800,NETWORK_TIMEOUT:2801,NO_NETWORK:2805,UNCAUGHT_ERROR:2903,INVALID_OPERATION:2905,SDK_IS_NOT_READY:2999,LOGGING_IN:3e3,LOGIN_FAILED:3001,KICKED_OUT_MULT_DEVICE:3002,KICKED_OUT_MULT_ACCOUNT:3003,KICKED_OUT_USERSIG_EXPIRED:3004,LOGGED_OUT:3005,KICKED_OUT_REST_API:3006,NO_USE:3122,OPTIONS_IS_EMPTY:3153,MSG_A2KEY_EXPIRED:20002,ACCOUNT_A2KEY_EXPIRED:70001,HELLO_ANSWER_KICKED_OUT:1002,OPEN_SERVICE_OVERLOAD_ERROR:60022},Rs={BASIC:"1",STANDARD:"2",PROFESSIONAL:"3"},Ds={SYNC_SERVER_INFO_AFTER_RE_ONLINE:"sync-server-info-after-re-online",SYNC_SERVER_INFO_AFTER_LOGIN:"sync-server-info-after-login",RECEIVE_C2C_NEW_MESSAGE:"receive-c2c-new-message",RECEIVE_GROUP_NEW_MESSAGE:"receive-group-new-message",RECEIVE_GROUP_TIPS_NOTIFICATION:"receive-group-tips-notification"},bs={USER_STATUS_UPDATE:"user-status-update",CONVERSATION_RECOVER:"conversation-recover",HISTORY_MESSAGE_RECOVER:"history-message-recover",BLACKLIST_RECOVER:"blacklist-recover",FRIEND_RECOVER:"friend-recover",GROUP_ATTRIBUTE_CACHE_CLEAR:"group-attribute-cache-clear",UNREAD_MESSAGE_RECOVER:"unread-message-recover",HANDLE_NEW_MESSAGE:"handle-new-message",HANDLE_CONVERSATION_PROFILE_UPDATED:"handle-conversation-profile-updated",COMMERCIAL_CONFIG_UPDATE:"commercial-config-update",UNREAD_MESSAGE_SYNC:"unread-message-sync",FRIEND_AND_BLACKLIST_SYNC:"friend-and-blacklist-sync",SIGNALING_MESSAGE_RECOVER:"signaling-message-recover",GROUP_LIST_SYNC:"group-list-sync",CONVERSATION_LIST_SYNC:"conversation-list-sync",USER_PROFILE_SYNC:"user-profile-sync",CONVERSATION_UPDATE_AFTER_UNREAD_SYNC_FINISHED:"conversation-update-after-unread-sync-finished",CONVERSATION_UPDATE_AFTER_GROUP_LIST_SYNC_FINISHED:"conversation-update-after-group-list-sync-finished",HANDLE_C2C_NEW_MESSAGE:"handle-c2c-new-message",HANDLE_GROUP_NEW_MESSAGE:"handle-group-new-message",CREATE_OR_UPDATE_CONVERSATION_BY_RECEIVE_NEW_MESSAGE:"create-or-update-conversation-by-receive-new-message",HANDLE_GROUP_TIPS_FROM_SYNC_UNREAD:"handle-group-tips-from-sync-unread",HANDLE_C2C_REVOKED_MESSAGE_FROM_SYNC_UNREAD:"handle-c2c-revoked-message-from-sync-unread",GROUP_REVOKED_NOTICE_RECOVER:"group-revoked-notice-recover",CLOUD_CONFIG_SYNC:"cloud-config-sync",UPDATE_GROUP_NEXT_SEQUENCE:"update-group-next-sequence",EMIT_C2C_MESSAGE_EVENT:"emit-c2c-message-event",EMIT_GROUP_MESSAGE_EVENT:"emit-group-message-event",CONVERSATION_GROUP_LIST_SYNC:"conversation-group-list-sync",CONVERSATION_GROUP_UPDATE:"conversation-group-update",UPDATE_TOPIC_AFTER_UNREAD_SYNC_FINISHED:"update-topic-after-unread-sync-finished",UPDATE_TOPIC_BY_RECEIVE_NEW_MESSAGE:"update-topic-by-received-new-message",TOPIC_REQUEST_INFO_RESET:"topic-request-info-reset",QUALITY_REPORT:"quality-report",GROUP_TIPS_RECOVER:"group-tips-recover",HANDLE_GROUP_TIPS_NOTIFICATION:"handle-group-tips-notification"},Ns={[Ds.SYNC_SERVER_INFO_AFTER_RE_ONLINE]:[{stepId:bs.USER_STATUS_UPDATE},{stepId:bs.GROUP_ATTRIBUTE_CACHE_CLEAR},{stepId:bs.UNREAD_MESSAGE_SYNC},{stepId:bs.CONVERSATION_RECOVER},{stepId:bs.HISTORY_MESSAGE_RECOVER,dependency:bs.CONVERSATION_RECOVER},{stepId:bs.BLACKLIST_RECOVER},{stepId:bs.FRIEND_RECOVER},{stepId:bs.GROUP_REVOKED_NOTICE_RECOVER,dependency:bs.HISTORY_MESSAGE_RECOVER},{stepId:bs.GROUP_TIPS_RECOVER,dependency:bs.HISTORY_MESSAGE_RECOVER},{stepId:bs.TOPIC_REQUEST_INFO_RESET},{stepId:bs.HANDLE_C2C_REVOKED_MESSAGE_FROM_SYNC_UNREAD,dependency:bs.UNREAD_MESSAGE_SYNC},{stepId:bs.HANDLE_GROUP_TIPS_FROM_SYNC_UNREAD,dependency:bs.UNREAD_MESSAGE_SYNC},{stepId:bs.CONVERSATION_UPDATE_AFTER_UNREAD_SYNC_FINISHED,dependency:[bs.UNREAD_MESSAGE_SYNC,bs.CONVERSATION_RECOVER]},{stepId:bs.EMIT_C2C_MESSAGE_EVENT,dependency:[bs.UNREAD_MESSAGE_SYNC,bs.CONVERSATION_UPDATE_AFTER_UNREAD_SYNC_FINISHED],skipIfDependencyMissing:!1}],[Ds.SYNC_SERVER_INFO_AFTER_LOGIN]:[{stepId:bs.COMMERCIAL_CONFIG_UPDATE},{stepId:bs.CLOUD_CONFIG_SYNC},{stepId:bs.USER_PROFILE_SYNC},{stepId:bs.UNREAD_MESSAGE_SYNC},{stepId:bs.FRIEND_AND_BLACKLIST_SYNC},{stepId:bs.GROUP_LIST_SYNC},{stepId:bs.CONVERSATION_LIST_SYNC},{stepId:bs.SIGNALING_MESSAGE_RECOVER,dependency:bs.UNREAD_MESSAGE_SYNC},{stepId:bs.UPDATE_TOPIC_AFTER_UNREAD_SYNC_FINISHED,dependency:[bs.UNREAD_MESSAGE_SYNC]},{stepId:bs.CONVERSATION_UPDATE_AFTER_UNREAD_SYNC_FINISHED,dependency:[bs.UNREAD_MESSAGE_SYNC,bs.CONVERSATION_LIST_SYNC]},{stepId:bs.CONVERSATION_UPDATE_AFTER_GROUP_LIST_SYNC_FINISHED,dependency:[bs.GROUP_LIST_SYNC,bs.CONVERSATION_LIST_SYNC]},{stepId:bs.CONVERSATION_GROUP_LIST_SYNC},{stepId:bs.CONVERSATION_GROUP_UPDATE,dependency:[bs.CONVERSATION_LIST_SYNC,bs.CONVERSATION_GROUP_LIST_SYNC]},{stepId:bs.QUALITY_REPORT}],[Ds.RECEIVE_C2C_NEW_MESSAGE]:[{stepId:bs.HANDLE_C2C_NEW_MESSAGE},{stepId:bs.UNREAD_MESSAGE_SYNC},{stepId:bs.CREATE_OR_UPDATE_CONVERSATION_BY_RECEIVE_NEW_MESSAGE,dependency:bs.HANDLE_C2C_NEW_MESSAGE},{stepId:bs.EMIT_C2C_MESSAGE_EVENT,dependency:[bs.HANDLE_C2C_NEW_MESSAGE,bs.CREATE_OR_UPDATE_CONVERSATION_BY_RECEIVE_NEW_MESSAGE],skipIfDependencyMissing:!1},{stepId:bs.CONVERSATION_UPDATE_AFTER_UNREAD_SYNC_FINISHED,dependency:[bs.UNREAD_MESSAGE_SYNC]}],[Ds.RECEIVE_GROUP_NEW_MESSAGE]:[{stepId:bs.HANDLE_GROUP_NEW_MESSAGE},{stepId:bs.CREATE_OR_UPDATE_CONVERSATION_BY_RECEIVE_NEW_MESSAGE,dependency:bs.HANDLE_GROUP_NEW_MESSAGE},{stepId:bs.UPDATE_GROUP_NEXT_SEQUENCE,dependency:bs.HANDLE_GROUP_NEW_MESSAGE},{stepId:bs.UPDATE_TOPIC_BY_RECEIVE_NEW_MESSAGE,dependency:bs.HANDLE_GROUP_NEW_MESSAGE},{stepId:bs.EMIT_GROUP_MESSAGE_EVENT,dependency:[bs.HANDLE_GROUP_NEW_MESSAGE,bs.CREATE_OR_UPDATE_CONVERSATION_BY_RECEIVE_NEW_MESSAGE],skipIfDependencyMissing:!1}],[Ds.RECEIVE_GROUP_TIPS_NOTIFICATION]:[{stepId:bs.HANDLE_GROUP_TIPS_NOTIFICATION},{stepId:bs.CREATE_OR_UPDATE_CONVERSATION_BY_RECEIVE_NEW_MESSAGE,dependency:bs.HANDLE_GROUP_TIPS_NOTIFICATION}]},Ls={MESSAGE_SEND_SUCCESS_RATE:"messageSendSuccessRate"},Ps={TOTAL_COUNT:"sendMessageTotalCount",SUCCESS_COUNT:"sendMessageSuccessCount",FAILED_COUNT:"sendMessageFailedCount",SEND_COST:"sendMessageCost"},ws=["login","getMyProfile","getUserProfile","updateMyProfile","setSelfStatus","getUserStatus","subscribeUserStatus","unsubscribeUserStatus","modifyMessage","deleteGroupMember","dismissGroup","getGroupMemberList","getGroupOnlineMemberCount","joinGroup","markGroupMemberList","quitGroup","searchCloudMessages","searchCloudGroups","searchCloudGroupMembers","searchCloudUsers","getMyFollowingList","getMyFollowersList","getMutualFollowersList","followUser","unfollowUser","getUserFollowInfo","checkFollowType","getFriendProfile","addFriend","deleteFriend","updateFriend","checkFriend","setFriendApplicationRead","createFriendGroup","deleteFriendGroup","addToFriendGroup","removeFromFriendGroup","renameFriendGroup","changeGroupOwner","createGroup","dismissGroup","getGroupList","getGroupOnlineMemberCount","getGroupProfile","searchGroupByID","updateGroupProfile","handleGroupApplication","deleteGroupAttributes","getGroupAttributes","initGroupAttributes","setGroupAttributes","addGroupMember","deleteGroupMember","getGroupMemberList","getGroupMemberProfile","setGroupMemberMuteTime","setGroupMemberNameCard","setGroupMemberRole","deleteMessage","revokeMessage","setMessageExtensions","getMessageExtensions","deleteMessageExtensions","getMessageList","addMessageReaction","removeMessageReaction","clearHistoryMessage","invite","accept","cancel","reject","modifyInvitation","deleteConversation","pinConversation","setMessageRead","setAllMessageRead","getConversationList","getTotalUnreadMessageCount","renameConversationGroup","deleteConversationGroup","markConversation","setConversationCustomData","deleteConversationsFromGroup","addConversationsToGroup","createConversationGroup"];var Gs=Object.freeze({__proto__:null,ERROR_CODE:Ts,InnerEvent:cs,NEED_LOG_API:ws,OuterConstant:As,OuterEvent:rs,QUALITY_METRICS:Ls,SDK_EDITION:Rs,SDK_INFO:{VERSION:"1.7.3",APPID:537048168},SEND_MESSAGE_STAT:Ps,SignalingEvent:us,WORKFLOW_DEFINITIONS:Ns,WORKFLOW_NAME:Ds,WORKFLOW_STEP:bs});var Us,ks,Fs;!function(e){e[e.USER_INITIATED=0]="USER_INITIATED",e[e.KICKED_OUT=1]="KICKED_OUT"}(Us||(Us={})),function(e){e[e.multipleAccount=1]="multipleAccount",e[e.multipleDevice=2]="multipleDevice",e[e.restApi=3]="restApi"}(ks||(ks={})),function(e){e[e.multipleDevice=3002]="multipleDevice",e[e.multipleAccount=3003]="multipleAccount",e[e.usersigExpired=70001]="usersigExpired",e[e.restApi=20002]="restApi"}(Fs||(Fs={}));const $s={[ks.multipleAccount]:"multipleAccount",[ks.multipleDevice]:"multipleDevice",[ks.restApi]:"REST_API_Kick",[Fs.multipleAccount]:"multipleAccount",[Fs.multipleDevice]:"multipleDevice",[Fs.restApi]:"REST_API_Kick",[Fs.usersigExpired]:"userSigExpired"},qs="login_online_presence_task",{ERROR:xs,DESTROY:Vs,FORCE_OFFLINE:Bs}=cs,{KICKED_OUT_MULT_ACCOUNT:js,KICKED_OUT_MULT_DEVICE:Ks,KICKED_OUT_REST_API:Hs,ACCOUNT_A2KEY_EXPIRED:Ws,MSG_A2KEY_EXPIRED:Ys}=Ts;class zs{init(){const{notificationCenter:e}=ts;e.subscribeInnerEvent(Bs,this._handleForceOfflineFromServerPush,this),e.subscribeInnerEvent(xs,Ys,this._handleForceOfflineFromResponse,this),e.subscribeInnerEvent(xs,Ws,this._handleForceOfflineFromResponse,this),e.subscribeInnerEvent(xs,js,this._handleForceOfflineFromResponse,this),e.subscribeInnerEvent(xs,Ks,this._handleForceOfflineFromResponse,this),e.subscribeInnerEvent(xs,Hs,this._handleForceOfflineFromResponse,this),e.subscribeInnerEvent(Vs,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 de(this,void 0,void 0,function*(){const{kickedOutReasonCode:t}=e,{ssoLog:s,utils:{safeStringify:n}}=ts;try{this._logKickedOutEvent(e),yield ts.login.loginAction.logout(Us.KICKED_OUT)}catch(e){s.debug("_processKickedOutReasonInfo",` fail ${n(e)}`)}finally{ts.notificationCenter.emitOuterEvent(rs.KICKED_OUT,{data:{type:$s[t]},name:rs.KICKED_OUT}),[ks.restApi,Ws,Ys].includes(t)&&ts.channel.reconnect()}})}_logKickedOutEvent(e){const{kickedOutReasonCode:t,newInstanceInfo:s={}}=e,n=`type:${$s[t]} newInstanceInfo: ${JSON.stringify(s)}`;ts.ssoLog.warn("kickedOut",n)}_isKickedOut(e){return[ks.multipleAccount,ks.multipleDevice,ks.restApi].includes(e)}_dispose(){const{notificationCenter:e}=ts;e.unSubscribeInnerEvent(Bs,this._handleForceOfflineFromServerPush,this),e.unSubscribeInnerEvent(xs,Ws,this._handleForceOfflineFromResponse,this),e.unSubscribeInnerEvent(xs,Ys,this._handleForceOfflineFromResponse,this),e.unSubscribeInnerEvent(xs,js,this._handleForceOfflineFromResponse,this),e.unSubscribeInnerEvent(xs,Ks,this._handleForceOfflineFromResponse,this),e.unSubscribeInnerEvent(xs,Hs,this._handleForceOfflineFromResponse,this),e.unSubscribeInnerEvent(Vs,this._dispose,this)}}function Js(e){return de(this,void 0,void 0,function*(){const t="im_open_status.wslogin",s=ts.common.generateProtocolData({servcmd:t,data:{State:"Online",is_web_uniapp:0,InstType:0,CustomInfo:e}}),n=`${s.head.seq}${t}`,o=yield ts.channel.sendPacket(s,{timeout:9e4,requestId:n});if(o){const{HelloInterval:e,InstId:t,TinyId:s,TimeStamp:n,CustomStatus:i,PurchaseBits:r,A2Key:a,RichMsgAuthKey:c,ErrorCode:u,ErrorInfo:l,ActionStatus:d}=o;return{helloInterval:e,instanceID:t,tinyID:s,timeStamp:n,customStatus:i,purchaseBits:r,a2Key:a,authKey:c,errorCode:u,errorInfo:l,actionStatus:d}}})}function Qs(e){var t;try{const s=Be.getStorage("errorMessage");if(!e||!s)return"";const n=(null===(t=JSON.parse(s))||void 0===t?void 0:t.errorMessage)||{},{isIntl:o=!1,code:i,replacement1:r="",replacement2:a=""}=e;if(!i)return"";const c=o?`${i}_en`:`${i}_cn`;let u=n[n[c]?c:i]||"";return u&&(r&&(u=u.replace("$replacement1",r)),a&&(u=u.replace("$replacement2",a))),u}catch(e){return console.warn("Error parsing stored error messages:",e),""}}class Xs extends Error{constructor(e){const{functionName:t="Unknown",code:s,message:n="",data:o="",moreMessage:i=""}=e;let r=n;s&&!n&&(r=Qs(e));let a=s?`${t} failed. error: {"message": ${r}, "code": ${s}}`:`${t} failed. error: {"message": ${r}}`;a=`${a} ${i}`,super(),this.code=s,this.errorCode=s,this.errorMessage=a,this.message=r,this.data=o}}function Zs(e,t){var s;if(!e)return;if(!(!0===(null===(s=ts.store.get("login"))||void 0===s?void 0:s.isLoggedIn)))throw new Xs({code:Ts.USER_NOT_LOGGED_IN,functionName:t})}function en(e,t,s){if(Array.isArray(e))for(let n=0;n<e.length;n++)tn.call(this,Object.assign(Object.assign({},e[n]),{value:t[n],name:s}));else for(const n in e)tn.call(this,Object.assign(Object.assign({},e[n]),{value:t[0][n],name:s,key:n}))}function tn({required:e,rules:t,range:s,value:n,allowEmpty:o,name:i,key:r,customValidator:a}){if(void 0===n){if(e){throw new Xs({functionName:i,message:`[${i}] Missing required params: "${r}"`})}return}let c="";if(!t.some(e=>{return e===(t=n,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()}(n)}.`;throw new Xs({functionName:i,message:e})}if(!1===o){if(Array.isArray(n)&&(0===n.length||"string"==typeof n[0]&&""===n[0].trim())){throw new Xs({functionName:i,message:`${r} can not be empty.`})}if("string"==typeof n&&""===n.trim()){throw new Xs({functionName:i,message:`${r} can not be empty.`})}}if(a&&"function"==typeof a){const e=a(n);if(!0!==e){throw new Xs({functionName:i,message:`[${r}] custom validation failed: ${e||"Invalid value"}`})}}}const sn=[],nn={},on={};function rn(e,t){Zs(nn[e],e),en(on[e],t,e),function(e){sn.forEach(t=>{const{interceptor:s,context:n}=t;s.apply(n,[e])})}(e)}function an(e,t){sn.push({interceptor:e,context:t})}function cn(e){const{params:t,auth:s}=e;t&&"object"==typeof t&&Object.assign(on,t),s&&"object"==typeof s&&Object.assign(nn,s)}function un(e){return ts.store.get("commercialConfig").get(e)}class ln{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),ts.ssoLog.debug("_executeWorkflowStep",`[Workflow ${e}] Step ${t} started at ${new Date(s).toISOString()}`)):(this._workflowStartTimes.set(e,s),ts.ssoLog.debug("_executeWorkflowStep",`[Workflow ${e}] started at ${new Date(s).toISOString()}`))},success:(e,t)=>{const s=Date.now();if(t){const n=this._stepStartTimes.get(`${e}-${t}`),o=n?s-n:0;this._stepStartTimes.delete(`${e}-${t}`),ts.ssoLog.debug("_executeWorkflowStep",`[Workflow ${e}] Step ${t} completed successfully at ${new Date(s).toISOString()} (${o}ms)`)}else{const t=this._workflowStartTimes.get(e),n=t?s-t:0;this._workflowStartTimes.delete(e),ts.ssoLog.debug("_executeWorkflowStep",`[Workflow ${e}] completed successfully at ${new Date(s).toISOString()} (${n}ms)`)}},error:(e,t,s)=>{const{ssoLog:n,utils:{safeStringify:o}}=ts,i=Date.now();if(t){const r=this._stepStartTimes.get(`${e}-${t}`),a=r?i-r:0;this._stepStartTimes.delete(`${e}-${t}`),n.error("_executeWorkflowStep",`[Workflow ${e}] Step ${t} failed at ${new Date(i).toISOString()} (${a}ms) ${o(s)}`,{error:s})}else{const t=this._workflowStartTimes.get(e),r=t?i-t:0;this._workflowStartTimes.delete(e),n.error("_executeWorkflowStep",`[Workflow ${e}] failed at ${new Date(i).toISOString()} (${r}ms) ${o(s)}`,{error:s})}}}}static getInstance(){return ln._instance||(ln._instance=new ln),ln._instance}static setInstance(e){ln._instance=e}init(){this._initializeWorkflows()}registerWorkflowStep(e,t,s,n){if(!this._handlers.has(e))return void ts.ssoLog.debug("registerWorkflowStep",`Workflow '${e}' not defined in core`);if(!Ns[e].find(e=>e.stepId===t))return void ts.ssoLog.debug("registerWorkflowStep",`Step '${t}' not defined in workflow '${e}'`);const o=this._handlers.get(e);o.has(t)||o.set(t,n?s.bind(n):s)}executeWorkflow(e,t){return de(this,void 0,void 0,function*(){if(!this._validateWorkflow(e))return;ts.ssoLog.debug("executeWorkflow",`[Workflow ${e}] Started execution at ${(new Date).toISOString()}`);const s=Ns[e],n={},o={cancelled:!1};this._activeWorkflows.set(e,{cancelToken:o});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:n,data:t,cancelToken:o};yield new Promise((t,s)=>{const n=()=>{if(o.cancelled)return void t();this._getExecutableSteps({pendingSteps:r.pendingSteps,completedSteps:r.completedSteps,stepMap:r.stepMap,workflowName:e}).filter(e=>!r.runningSteps.has(e)).forEach(o=>{r.completedSteps.has(o)||r.runningSteps.has(o)||this._executeWorkflowStep(o,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&&(ts.ssoLog.debug("executeWorkflow",`Workflow ${e} completed with some steps skipped due to dependency failures`),t())},onError:s,onStepComplete:n})})};n()}),ts.ssoLog.debug("executeWorkflow",`[Workflow ${e}] Completed execution at ${(new Date).toISOString()}`)}catch(t){ts.ssoLog.error("executeWorkflow",`[Workflow ${e}] Failed execution at ${(new Date).toISOString()}`,{error:t})}finally{this._activeWorkflows.delete(e)}})}_executeWorkflowStep(e,s,n){return de(this,void 0,void 0,function*(){const{workflowName:o,runningSteps:i,stepMap:r,stepResults:a,data:c}=s;i.add(e),this._logWorkflowExecution(o,e,"start");try{const n=r.get(e);let i=null;(null==n?void 0:n.dependency)&&(t(n.dependency)?i=a[n.dependency]:Array.isArray(n.dependency)&&(i={},n.dependency.forEach(e=>{i[e]=a[e]})));const u=this._handlers.get(o).get(e);if(u){const t=yield Promise.resolve(u({data:c,result:i}));a[e]=t,this._logWorkflowExecution(o,e,"success")}s.completedSteps.add(e)}catch(t){const s=`[Workflow].${o}.${e}`,{errorCode:i,errorInfo:r=`${s} failed`}=t||{},a=new Xs({functionName:s,code:i,message:r});ts.ssoLog.error(s,r,{error:a}),this._logWorkflowExecution(o,e,"error",t),n.onError(t)}finally{i.delete(e),s.pendingSteps.delete(e),n.onStepComplete(),n.onComplete()}})}reset(){this._cancelAllWorkflows()}destroy(){this.reset(),this._handlers.clear()}_initializeWorkflows(){Object.keys(Ns).forEach(e=>{this._handlers.has(e)||this._handlers.set(e,new Map)})}_cancelWorkFlow(e){const t=this._activeWorkflows.get(e);if(!t)return;const{cancelToken:s}=t;s.cancelled=!0,this._activeWorkflows.delete(e)}_cancelAllWorkflows(){Object.keys(Ns).forEach(e=>{this._cancelWorkFlow(e)})}_validateWorkflow(e){if(!Ns[e])return!1;return!!this._handlers.get(e)}_getExecutableSteps(e){const{pendingSteps:s,completedSteps:o,stepMap:i,workflowName:r}=e;return Array.from(s).filter(e=>{const s=i.get(e)||{},{dependency:a,skipIfDependencyMissing:c=!0}=s;if(!a)return!0;if(t(a))return this._isStepRegistered({workflowName:r,stepId:a})?o.has(a):!c;if(n(a)){if(a.filter(e=>!this._isStepRegistered({workflowName:r,stepId:e})).length>0&&c)return!1;for(const e of a)if(!o.has(e))return!1;return!0}return!1})}_isStepRegistered(e){var t;const{workflowName:s,stepId:n}=e;return null===(t=this._handlers.get(s))||void 0===t?void 0:t.has(n)}_logWorkflowExecution(e,t,s,n){this._logHandlers[s](e,t)}}const dn=new Map,hn=({type:e,groupID:t})=>e===As.GRP_COMMUNITY||`${t}`.startsWith(Ms.COMMUNITY)&&!`${t}`.includes(Ms.TOPIC),gn=(e="")=>{const t=e.startsWith("GROUP")?e.replace("GROUP",""):e;return t.startsWith(Ms.COMMUNITY)&&`${t}`.includes(Ms.TOPIC)},pn="openim",_n="million_group_open_http_svc";function mn(e){return de(this,void 0,void 0,function*(){const{servcmd:t,data:s}=function(e){const{data:t}=e;return vn(t)||fn(t)}(e)?function(e){let{servcmd:t,data:s}=e;if(fn(s))return function(e){const{servcmd:t,data:s}=e;let{GroupId:n=""}=s;const o=n;return[n]=o.split(Ms.TOPIC),{servcmd:In(t),data:Object.assign(Object.assign({},s),{GroupId:n,TopicId:o})}}(e);vn(s)&&(t=In(t));return{servcmd:t,data:s}}(e):e,n=ts.common.generateProtocolData({servcmd:t,data:s}),o=`${n.head.seq}${t}`;return ts.channel.sendPacket(n,{requestId:o})})}function vn(e){const{Type:t,GroupId:s,GroupIdList:n=[]}=e,o=s||n[0]||"";return hn({type:t,groupID:o})}function fn(e){const{GroupId:t=""}=e;return gn(t)}function In(e){if(e.includes(pn))return e;const t=e.split(".")[1];return`${_n}.${t}`}function En(){var e;return null===(e=ts.store.get("login"))||void 0===e?void 0:e.userId}const Sn=e=>n(e)||o(e),Cn=(t,s,n,o)=>{if(!Sn(t)||!Sn(s))return 0;let i=0;const r=Object.keys(s);let a;for(let c=0,u=r.length;c<u;c++)if(a=r[c],!(e(s[a])||n&&n.includes(a)))if(Sn(t[a])&&Sn(s[a]))i+=Cn(t[a],s[a],n,o);else{if(o&&o.includes(s[a]))continue;t[a]!==s[a]&&(t[a]=s[a],i+=1)}return i},Mn=(t,s)=>{if(e(s))return"";switch(t){case As.MSG_TEXT:return s.text||"";case As.MSG_IMAGE:return"[Image]";case As.MSG_LOCATION:return"[Location]";case As.MSG_AUDIO:return"[Voice]";case As.MSG_VIDEO:return"[Video]";case As.MSG_FILE:return"[File]";case As.MSG_CUSTOM:return"[Custom Messages]";case As.MSG_GRP_TIP:return"[Group Notification]";case As.MSG_GRP_SYS_NOTICE:return"[Group System Message]";case As.MSG_FACE:return"[Animated Sticker]";case As.MSG_MERGER:return"[Chat Record]";default:return""}},yn=[{cmd:"ws_get_user_status",interval:5,count:20},{cmd:"ws_status_subscribe",interval:5,count:20},{cmd:"ws_status_unsubscribe",interval:5,count:20},{cmd:"get_group_self_member_info",interval:5,count:20},{cmd:"modify_group_base_info",interval:1,count:8},{cmd:"get_pendency",interval:1,count:15},{cmd:"set_group_attr",interval:5,count:10},{cmd:"modify_group_attr",interval:5,count:10},{cmd:"delete_group_attr",interval:5,count:10},{cmd:"clear_group_attr",interval:5,count:10},{cmd:"get_group_attr",interval:5,count:20},{cmd:"update_group_counter",interval:5,count:20},{cmd:"get_group_counter",interval:5,count:20},{cmd:"get_topic",interval:1,count:10},{cmd:"read_all_unread_msg",interval:1,count:1},{cmd:"query",interval:5,count:20}],On="im_sdk_config_mgr.fetch_config",An="im_sdk_config_mgr.push_configv2",Tn="cloud-config",Rn=2996;const Dn=new class{init(e){this.core=e}};function bn(e){return de(this,void 0,void 0,function*(){const{sdkAppId:t}=Dn.core.store.get("instance")||{},s=Dn.core.helper.generateProtocolData({servcmd:On,data:{uint32_sdkappid:t,uint64_version:e}}),n=`${s.head.seq}${On}`;return Dn.core.channel.sendPacket(s,{requestId:n})})}var Nn=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:n,constants:{WORKFLOW_NAME:o,WORKFLOW_STEP:i},channel:r}=e;t.subscribeInnerEvent(An,this._handlePushedConfig,this),n.registerWorkflowStep(o.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),n.registerExperimentalAPI("getServerConfig",this),this._updateCmdFreqLimitMap(yn),r.registerBeforeSendInterceptor(this.checkMethodCallOverLimit,this)}getServerConfig(e){return de(this,void 0,void 0,function*(){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:n,methodCallCounter:o}=this._methodCallFrequencyMap.get(e);if(Date.now()-n>1e3*s)this._methodCallFrequencyMap.set(e,{startTime:Date.now(),methodCallCounter:1});else if(o+=1,this._methodCallFrequencyMap.set(e,{startTime:n,methodCallCounter:o}),o>t)throw new this._core.helper.ChatError({code:Rn,replacement1:e})}_handlePushedConfig(e){return de(this,void 0,void 0,function*(){const{ssoLog:t,utils:{safeStringify:s}}=this._core;t.info("_handlePushedConfig",s(e)),yield this._updateCloudConfig(e)})}_handleLoginSuccess(){return de(this,void 0,void 0,function*(){const{ssoLog:e,utils:{safeStringify:t}}=this._core;try{if(this._canFetch()){const s=yield bn(this._version);e.info("_fetchCloudConfigIfLogin",t(s)),yield this._updateCloudConfig(s)}this._core.helper.taskScheduler.addTask({id:Tn,intervalMs:1e3,callback:this._fetchCloudConfigIfReady,context:this})}catch(s){e.error("_fetchCloudConfigIfLogin",t(s))}})}_fetchCloudConfigIfReady(){return de(this,void 0,void 0,function*(){const{ssoLog:e,utils:{safeStringify:t}}=this._core;if(this._canFetch())try{const s=yield bn(this._version);e.info("_fetchCloudConfigIfReady",t(s)),yield this._updateCloudConfig(s)}catch(s){e.error("_fetchCloudConfigIfReady",t(s))}})}_updateCloudConfig(e){return de(this,void 0,void 0,function*(){const t=this._parseCloudConfig(e);t&&(this._core.store.set("cloudConfig",t),yield this._parseCmdFreqLimit(),this._core.notificationCenter.emitInnerEvent(this._core.InnerEvent.CLOUD_CONFIG_UPDATE,t),this._core.notificationCenter.emitOuterEvent(this._core.OuterEvent.SERVER_CONFIG_UPDATED,{name:this._core.OuterEvent.SERVER_CONFIG_UPDATED,data:{config: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:n,uint32_expired_time:o,uint32_sdkappid:i,uint64_version:r}=e;let a=null;if(0===t){if(this._version!==r)try{a=JSON.parse(n),this._version=r}catch(e){}this._expirationTime=Date.now()+1e3*o}else this._expirationTime=void 0===t?Date.now()+36e5:Date.now()+12e4;return a}_parseCmdFreqLimit(){return de(this,void 0,void 0,function*(){var e;let t=null===(e=yield 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(Tn),this._core.store.clear("cloudConfig"),this._updateCmdFreqLimitMap(yn),this._methodCallFrequencyMap.clear(),this._expirationTime=0,this._version=0,this._isFetching=!1}_dispose(){const{notificationCenter:e,InnerEvent:t}=this._core;e.unSubscribeInnerEvent(An,this._handlePushedConfig,this),e.unSubscribeInnerEvent(t.LOGOUT,this._reset,this),e.unSubscribeInnerEvent(t.DESTROY,this._dispose,this),this._reset()}};class Ln{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 Pn={SEARCH_GRP_SNS:new Ln(0,Math.pow(2,1)).toString(),AV_HISTORY_MSG:new Ln(0,Math.pow(2,2)).toString(),GRP_COMMUNITY:new Ln(0,Math.pow(2,3)).toString(),MSG_TO_SPECIFIED_GRP_MBR:new Ln(0,Math.pow(2,4)).toString(),AV_MBR_LIST:new Ln(0,Math.pow(2,6)).toString(),USER_STATUS:new Ln(0,Math.pow(2,7)).toString(),CONV_MARK:new Ln(0,Math.pow(2,9)).toString(),CONV_GROUP:new Ln(0,Math.pow(2,10)).toString(),AV_BAN_MBR:new Ln(0,Math.pow(2,11)).toString(),MSG_EXT:new Ln(0,Math.pow(2,13)).toString(),GRP_COUNTER:new Ln(0,Math.pow(2,15)).toString(),PLUGIN_TRANSLATE:new Ln(Math.pow(2,6)).toString(),PLUGIN_VOICE_TO_TEXT:new Ln(Math.pow(2,7)).toString(),PLUGIN_CS:new Ln(Math.pow(2,8)).toString(),PLUGIN_PUSH:new Ln(Math.pow(2,9)).toString(),PLUGIN_BOT:new Ln(Math.pow(2,10)).toString(),MSG_REACTION:new Ln(Math.pow(2,16)).toString(),FOLLOW:new Ln(Math.pow(2,20)).toString()},wn="CommercialConfig",Gn="commercial-config";var Un=new class{constructor(){this._core=null,this._expirationTime=0,this._isFetching=!1,this._featureMap=new Map,this._methodKeyMap=new Map,this._purchaseBits="0"}install(e){this._core=e;const{helper:t,notificationCenter:s,constants:{WORKFLOW_NAME:n,WORKFLOW_STEP:o,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(n.SYNC_SERVER_INFO_AFTER_LOGIN,o.COMMERCIAL_CONFIG_UPDATE,this._syncCommercialConfig,this),e.helper.registerExperimentalAPI("isCommercialAbilityEnabled",this),e.helper.registerExperimentalAPI("queryCommercialAbility",this)}isCommercialAbilityEnabled(e){return de(this,void 0,void 0,function*(){const t=parseInt(e,10).toString(2),{length:s}=t;let n,o=!0;for(let e=s-1,i=0;e>=0;e--,i++)if("1"===t.charAt(e)&&(n=i<32?new Ln(0,2**i).toString():new Ln(2**(i-32),0).toString(),!this._featureMap.get(n))){o=!1;break}return this._core.ssoLog.debug("isFeatureEnabled",`${wn}.isFeatureEnabled decimalNumber:${e} key:${n} ret:${o}`),{code:0,data:{enabled:o}}})}queryCommercialAbility(){return this._purchaseBits}_fetchAndParseCommercialConfig(){return de(this,void 0,void 0,function*(){var e;const{ssoLog:t,helper:s,utils:{safeStringify:n}}=this._core;try{this._isFetching=!0;const t=s.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}}),n=yield this._core.channel.sendPacket(t);(null==n?void 0:n.body)&&(this._parseCommercialConfig(n.body),this._core.store.set("commercialConfig",this._methodKeyMap))}catch(e){t.error("_fetchAndParseCommercialConfig",n(e))}finally{this._isFetching=!1}})}_syncCommercialConfig(e){return de(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:Gn,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 de(this,void 0,void 0,function*(){this._canFetch()&&(yield this._fetchAndParseCommercialConfig())})}_parseCommercialConfig(e){const{ssoLog:t}=this._core;if("object"!=typeof e)return;const{int32_error_code:s,str_error_message:n,str_purchase_bits:o,uint32_expired_time:i}=e;0===s?(this._parsePurchaseBits(o),this._expirationTime=Date.now()+1e3*i):void 0===s?(t.warn("_parseCommercialConfig",`${wn}._parseCommercialConfig failed. Invalid message format:`,e),this._expirationTime=Date.now()+36e5):(t.warn("_parseCommercialConfig",`${wn}._parseCommercialConfig errorCode:${s} errorMessage:${n}`),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){const{ssoLog:t,utils:{safeStringify:s}}=this._core;if(this._isValidPurchaseBits(e)){this._purchaseBits=e,this._featureMap.clear(),this._methodKeyMap.clear();let t=null;for(let s=e.length-1,n=0;s>=0;s--,n++)if(t=n<32?new Ln(0,2**n).toString():new Ln(2**(n-32),0).toString(),"1"===e[s]){this._featureMap.set(t,!0);const e=this._getKeyByValue(Pn,t);e&&this._methodKeyMap.set(e,!0)}else{this._featureMap.set(t,!1);const e=this._getKeyByValue(Pn,t);e&&this._methodKeyMap.set(e,!1)}}else t.warn("_parsePurchaseBits",`${wn}.parsePurchaseBits invalid purchases:${s(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(Gn),this._core.store.set("commercialConfig",{}),this._expirationTime=0,this._isFetching=!1,this._featureMap.clear(),this._purchaseBits="0"}};var kn=new class{constructor(){this._core=null,this._serverOverloadInfoMap=new Map}install(e){this._core=e;const{notificationCenter:t,InnerEvent:s,channel:n}=this._core;t.subscribeInnerEvent(s.OVERLOAD_PUSH,this._handleOverLoadPush,this),t.subscribeInnerEvent(s.LOGOUT,this._reset,this),t.subscribeInnerEvent(s.DESTROY,this._dispose,this),n.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 Fn=new class{constructor(){this.name="ConfigCenter"}install(e){Dn.init(e),Nn.install(e),Un.install(e),kn.install(e)}};var $n=new class{constructor(){this.name="ErrorMessage",this._core=null}install(e){return de(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 de(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={},n=new RegExp(/'/g);for(let e=0;e<t.length;e++){const o=t[e].indexOf(":"),i=t[e].slice(0,o);let r=t[e].slice(o+1);if(!i.startsWith("//")){if(""===r)continue;r=r.replace(n,""),s[i]=r}}return s}}};function qn(e,t){return de(this,void 0,void 0,function*(){const{cookie:s,syncFlag:n,syncTriggerEvent:o}=e,i="openim.getmsg",r=t.helper.generateProtocolData({servcmd:i,data:{Cookie:s,SyncFlag:n,IsOnlineSync:o,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:n,EventArray:o}=e,{unreadMessageList:i,revokedMessageList:c}=function(e,t){const s=[],n=[];return null==e||e.forEach(e=>{var o,i,r;const a=function(e,t){const{From_Account:s,From_AccountHeadurl:n,From_AccountNick:o,IsNeedReadReceipt:i,MsgBody:r,MsgClientTime:a,MsgRandom:c,MsgSeq:u,MsgTimeStamp:l,SendMsgControl:d,SupportMessageExtension:h,To_Account:g,TinyId:p,MsgCheckResult:_,CloudCustomData:m,IsPeerRead:v,MsgFlagBits:f,MsgVersion:I,EventArray:E}=e;return{from:s,avatar:n,nick:o,needReadReceipt:1===i,readReceiptSentByPeer:v,clientTime:a,messageFlagBits:f,random:c,sequence:u,time:l,messageControlInfo:d,isSupportExtension:h,to:g,tinyID:p,checkResult:_,cloudCustomData:m,messageVersion:I,eventArray:E,elements:t.message.messageHelper.parseServerPushMessageElement(r)}}(e,t);if(null===(r=null===(i=null===(o=null==e?void 0:e.EventArray)||void 0===o?void 0:o[0])||void 0===i?void 0:i.hasOwnProperty)||void 0===r?void 0:r.call(i,"C2cNotifyMsgArray"))n.push(...function(e){var t;const s=[];return null===(t=e.EventArray)||void 0===t||t.forEach(e=>{var t,n;const{C2cNotifyMsgArray:o}=e,i=null===(n=null===(t=null==o?void 0:o[0])||void 0===t?void 0:t.WithdrawC2cMsgNotify)||void 0===n?void 0:n.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:n}=a;e.setElement(n),s.push(e)}}),{unreadMessageList:s,revokedMessageList:n}}(e.MsgList,t);return{syncFlag:null==e?void 0:e.SyncFlag,unreadMessageList:i,revokedMessageList:c,unreadCountList:s,overflowUnreadCountList:n,cookie:null==e?void 0:e.Cookie,groupTipList:o}}catch(e){console.warn(e)}})}var xn,Vn;!function(e){e[e.START_SYNC=0]="START_SYNC",e[e.SYNCING=1]="SYNCING",e[e.SYNC_COMPLETE=2]="SYNC_COMPLETE"}(xn||(xn={})),function(e){e[e.LOGIN_SUCCESS=0]="LOGIN_SUCCESS",e[e.NEW_MESSAGE_RECEIVED=1]="NEW_MESSAGE_RECEIVED"}(Vn||(Vn={}));var Bn=new class{constructor(){this.name="UnreadMessageSynchronizer",this._unreadDBMessageMap=new Map,this._cookie=""}install(e){this._core=e;const{constants:t}=e;e.helper.registerWorkflowStep(t.WORKFLOW_NAME.SYNC_SERVER_INFO_AFTER_RE_ONLINE,t.WORKFLOW_STEP.UNREAD_MESSAGE_SYNC,this._syncUnreadDBMessageAfterReOnline,this),e.helper.registerWorkflowStep(t.WORKFLOW_NAME.RECEIVE_C2C_NEW_MESSAGE,t.WORKFLOW_STEP.UNREAD_MESSAGE_SYNC,this._syncUnreadDBMessageAfterNewMessageReceived,this),e.helper.registerWorkflowStep(t.WORKFLOW_NAME.SYNC_SERVER_INFO_AFTER_LOGIN,t.WORKFLOW_STEP.UNREAD_MESSAGE_SYNC,this._syncUnreadDBMessageAfterLogin,this),e.notificationCenter.subscribeInnerEvent(e.InnerEvent.LOGOUT,this._reset,this),e.notificationCenter.subscribeInnerEvent(e.InnerEvent.DESTROY,this._dispose,this)}_syncUnreadMessage(e){return de(this,void 0,void 0,function*(){const{isAfterReOnline:t=!1,isAfterNewMessageReceived:s=!1,isAfterLogin:n=!1}=e||{};let o=xn.START_SYNC;const i=[],r=[],a=[],c=[];for(;this._canContinueSync({cookie:this._cookie,syncFlag:o});){const e=yield this._fetchUnreadDBMessage({cookie:this._cookie,syncFlag:o,syncTriggerEvent:s?Vn.NEW_MESSAGE_RECEIVED:Vn.LOGIN_SUCCESS});if(!e)break;const{unreadMessageList:n=[],revokedMessageList:u=[],overflowUnreadCountList:l,unreadCountList:d,groupTipList:h}=e;if(this._cookie=(null==e?void 0:e.cookie)||"",o=null==e?void 0:e.syncFlag,this._parseAndSaveUnreadMessageList(n),a.push(...u),this._updateConversationUnreadOptions({unreadCountList:d,overflowUnreadCountList:l,conversationUpdateFieldList:i}),Array.isArray(h)&&r.push(...h),t){const{messages:e}=this._handleNewMessageList(n);c.push(...e)}}return t?{conversationUpdateFieldList:i,revokedMessageList:a,unreadMessageMap:this._unreadDBMessageMap,groupTipList:r,messages:c}:{conversationUpdateFieldList:i,isInstantMessage:!n,isUnreadC2CMessage:!0,revokedMessageList:a,unreadMessageMap:this._unreadDBMessageMap,groupTipList:r}})}_syncUnreadDBMessageAfterLogin(){return de(this,void 0,void 0,function*(){return this._cookie="",this._syncUnreadMessage({isAfterLogin:!0})})}_syncUnreadDBMessageAfterNewMessageReceived(e){return de(this,void 0,void 0,function*(){if(1===e.data.Flag)return this._syncUnreadMessage({isAfterNewMessageReceived:!0})})}_updateConversationUnreadOptions(e){const{unreadCountList:t,overflowUnreadCountList:s,conversationUpdateFieldList:n}=e,{constants:{OuterConstant:{CONV_C2C:o,CONV_SYSTEM:i}}}=this._core;null==t||t.forEach(e=>{const{From_Account:t,UnreadCount:s}=e;if(t!==i){const e=n.find(({conversationID:e})=>e===`${o}${t}`);e?e.unreadCount=s:n.push({conversationID:`${o}${t}`,unreadCount:s,type:o})}}),null==s||s.forEach(e=>{const{From_Account:t,LastMsgTime:s}=e;if(t!==i){n.find(({conversationID:e})=>e===`${o}${t}`)||n.push({conversationID:`${o}${t}`,type:o,lastMsgTime:s})}})}_syncUnreadDBMessageAfterReOnline(){return de(this,void 0,void 0,function*(){return this._syncUnreadMessage({isAfterReOnline:!0})})}_updateMessageProfile(e){var t;const{messageDataHandler:s}=this._core.message||{},n=null===(t=this._core.store.get("login"))||void 0===t?void 0:t.userId,{from:o,nick:i,avatar:r,conversationID:a=""}=e;if(o!==n){const t=s.getLatestMsgSentByPeer(a);if(t){const{nick:n,avatar:o}=t;i&&r?i===n&&r===o||s.updateNickAndAvatarOfSentMessage({conversationID:a,latestNick:i,latestAvatar:r,isSentByMe:!1}):(e.nick=n,e.avatar=o)}}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,n=[];return e.forEach(e=>{this._updateMessageProfile(e);let o=1===e.isModified;if(t.isMessageSentByCurrentInstance(e)?e.isModified=o:o=!1,e.isOnlineMessage())e._onlineOnlyFlag=!0,t.isMessageSentByCurrentInstance(e)||n.push(e);else if(!t.isInMessageList(e)){if(t.storeConversationMessage(e)){const{conversationID:t,conversationType:n,conversationSubType:o,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:n,subType:o,unreadCount:r||"in"!==i?0:1,lastMessage:c})}t.isMessageSentByCurrentInstance(e)&&!o||n.push(e)}}),{messages:n,conversationOptions:s}}_fetchUnreadDBMessage(e){return de(this,void 0,void 0,function*(){const{ssoLog:t,utils:{safeStringify:s}}=this._core;try{const n="unread-message-synchronizer._fetchUnreadDBMessage";t.debug("_fetchUnreadDBMessage",`${n} options:${s(e)}`);const o=yield qn(e,this._core);if(!o)return null;const{syncFlag:i,unreadMessageList:r,revokedMessageList:a,cookie:c,unreadCountList:u,overflowUnreadCountList:l,groupTipList:d}=o;return this._parseAndSaveUnreadMessageList(r),{syncFlag:i,cookie:c,unreadMessageList:r,revokedMessageList:a,unreadCountList:u,overflowUnreadCountList:l,groupTipList:d}}catch(e){console.log(e)}})}_canContinueSync({cookie:e,syncFlag:t}){var s;return t===xn.START_SYNC||t===xn.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 jn=new class{init(e){var t;this._core=e,this._visibilityChangeHandler=this._handleVisibilityChange.bind(this),e.notificationCenter.subscribeInnerEvent(e.InnerEvent.DESTROY,this._dispose,this),null===document||void 0===document||document.addEventListener("visibilitychange",this._visibilityChangeHandler),null===(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 Kn=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,t,s,n,o;const{MINI_APP_NAMESPACE:i,IN_TT_MINI_GAME:r,IN_WX_MINI_GAME:a}=(null===(e=this._core)||void 0===e?void 0:e.utils)||{};r||a?(null===(t=null==i?void 0:i.onShow)||void 0===t||t.call(i,()=>{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})}),null===(s=null==i?void 0:i.onHide)||void 0===s||s.call(i,()=>{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})})):(null===(n=null==i?void 0:i.onAppShow)||void 0===n||n.call(i,()=>{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})}),null===(o=null==i?void 0:i.onAppHide)||void 0===o||o.call(i,()=>{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 Hn=new class{init(e){const{IN_MINI_APP:t,IN_WX_MINI_PLUGIN:s}=e.helper;s||(t?Kn.init(e):jn.init(e))}};const Wn="none",Yn="online";var zn=new class{init(e){this._core=e,this._activateNetworkMonitoring(),e.notificationCenter.subscribeInnerEvent(e.InnerEvent.DESTROY,this._dispose,this)}_activateNetworkMonitoring(){return de(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:n,networkType:o}=e;null===(t=this._core)||void 0===t||t.store.set("netWorkMonitor",{isNetworkOnline:n,networkType:o}),null===(s=this._core)||void 0===s||s.notificationCenter.emitInnerEvent("networkStatusChange",{isNetworkOnline:n,networkType:o})}_onOnline(){this._onNetworkStatusChange({isConnected:!0,networkType:Yn})}_onOffline(){this._onNetworkStatusChange({isConnected:!1,networkType:Wn})}_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 Jn=new class{init(e){this._core=e,this._activateNetworkMonitoring(),e.notificationCenter.subscribeInnerEvent(e.InnerEvent.DESTROY,this._dispose,this)}_activateNetworkMonitoring(){return de(this,void 0,void 0,function*(){try{const{utils:{MINI_APP_NAMESPACE:e}}=this._core;this._mpNetworkStatusCallback=this._onNetworkStatusChange.bind(this),e.onNetworkStatusChange(this._onNetworkStatusChange.bind(this))}catch(e){console.error(e)}})}_deactivateNetworkMonitoring(){if(null!==this._mpNetworkStatusCallback){const{utils:{MINI_APP_NAMESPACE:e}}=this._core;e.offNetworkStatusChange&&e.offNetworkStatusChange(this._mpNetworkStatusCallback),this._mpNetworkStatusCallback=null}}_onNetworkStatusChange(e){var t,s;const{isConnected:n,networkType:o}=e;null===(t=this._core)||void 0===t||t.store.set("netWorkMonitor",{isNetworkOnline:n,networkType:o}),null===(s=this._core)||void 0===s||s.notificationCenter.emitInnerEvent("networkStatusChange",{isNetworkOnline:n,networkType:o})}_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 Qn=new class{init(e){const{IN_MINI_APP:t}=e.utils;t?Jn.init(e):zn.init(e)}};var Xn=new class{constructor(){this.name="SystemStateMonitor"}install(e){Hn.init(e),Qn.init(e)}};const Zn=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.*"]),eo="tui_room_svr.*";var to=new class{constructor(){this.name="BusinessCommandTransfer",this._transferredCommands=Zn}install(e){this._core=e;const{notificationCenter:t,InnerEvent:s,helper:n}=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),n.registerExperimentalAPI("sendTRTCCustomData",this,"transferBusinessCommand"),n.registerExperimentalAPI("sendRoomCustomData",this,"transferBusinessCommand")}transferBusinessCommand(e){return de(this,void 0,void 0,function*(){const t="transferBusinessCommand";try{const{serviceCommand:s=eo}=e||{};if(!this._isValidTransferredCommand(s))throw new this._core.helper.ChatError({code:2995,functionName:t});const n=yield function(e,t){return de(this,void 0,void 0,function*(){const{helper:s,channel:n}=t,{serviceCommand:o=eo,data:i}=e||{};let r={};try{r="string"==typeof i?JSON.parse(i):i}catch(e){console.warn(e)}const a=s.generateProtocolData({servcmd:o,data:r}),c=`${a.head.seq}${o}`;return n.sendPacket(a,{requestId:c})})}(e,this._core);return{code:0,data:n||{}}}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:n}=e||{},{ROOM_CUSTOM_DATA_RECEIVED:o}=t;s.emitOuterEvent(o,{name:o,data:n})}_reset(){this._transferredCommands=Zn}_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 so=1,no=2,oo=3,io=4,ro=5,ao="TIMCustomElem",co="C2C",uo="GROUP",lo="invite",ho="accept",go="cancel",po="reject",_o="modifyInvitation",mo="signaling",vo=8010,fo="signaling-timeout";function Io(e){return e.filter(e=>{if(e.type===ao){const{cloudCustomData:t="",payload:{data:s=""}={}}=e,n=t.match(/"type":"tsignaling"/),o=s.match(/inviteID/),i=s.match(/actionType/);return n||o&&i}return!1})}function Eo(e){const{data:t}=e.payload;try{return JSON.parse(t)}catch(e){return console.error(e),null}}function So(e,t){return e.toString(16).padStart(t,"0")}function Co(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 Mo=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=`${mo}.isInvitationValid`,{inviteID:s,groupID:n,inviter:o}=e,i=o===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:${n}`),n){if(i)return r.length>0;const e=this._core.common.getCurrentUserID();return r.includes(e)}return!0}updateSignaling(e){const t=`${mo}.updateSignaling`,{inviteID:s,inviter:n,inviteeList:o,groupID:i}=e;if(console.log(`${t} inviteID:${s} inviter:${n} groupID:${i}`),i&&this.hasSignaling(s)){const e=o[0],{inviteeList:n}=this._onlineSignalingMap.get(s);n.includes(e)&&(n.splice(n.indexOf(e),1),console.log(`${t} remove ${e}. localInviteeList.length:${n.length}`)),0===n.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 yo=new class{init(e){this._core=e}createInviteSignaling(e){const t=this._generateInviteID(),s=this._createInviteSignalingData(Object.assign(Object.assign({},e),{inviteID:t})),{groupID:n,inviteeList:o}=s,i=n||o[0];return{signaling:this._createSignaling(s,i),signalingData:s,signalingExtensionOptions:this._createSignalingExtensionOptions(e)}}createAcceptSignaling(e){const t=this._createAcceptSignalingData(e),{groupID:s,inviter:n}=t,o=s||n;return{signaling:this._createSignaling(t,o),signalingData:t,signalingExtensionOptions:this._createSignalingExtensionOptions(e)}}createCancelSignaling(e){const t=this._createCancelSignalingData(e),{groupID:s,inviteeList:n}=t,o=s||n[0];return{signaling:this._createSignaling(t,o),signalingData:t,signalingExtensionOptions:this._createSignalingExtensionOptions(e)}}createRejectSignaling(e){const t=this._createRejectSignalingData(e),{groupID:s,inviter:n}=t,o=s||n;return{signaling:this._createSignaling(t,o),signalingData:t,signalingExtensionOptions:this._createSignalingExtensionOptions(e)}}createTimeoutSignaling(e){const{isInviter:t=!1}=e,s=this._createTimeoutSignalingData(e),{groupID:n,inviteeList:o,inviter:i}=s,r=n||(t?o[0]:i);return{signaling:this._createSignaling(s,r),signalingData:s,signalingExtensionOptions:this._createSignalingExtensionOptions(s)}}_createSignalingExtensionOptions(e){var t,s;const{data:n="",onlineUserOnly:o,inviteID:i="",offlinePushInfo:r,actionType:a}=e,c=(null===(s=null===(t=Mo.getSignaling(i))||void 0===t?void 0:t.signaling)||void 0===s?void 0:s._onlineOnlyFlag)||!1;return{onlineUserOnly:o||c,offlinePushInfo:r,messageControlInfo:this._createMessageControlInfo(n,a)}}_createMessageControlInfo(e,t){const s=t===ro&&!!e.match(/excludeTimeoutSignalingFromHistoryMessage/),n=!!e.match(/excludeFromHistoryMessage/)||!!e.match(/excludeOriginalSignalingFromHistoryMessage/);return{excludedFromContentModeration:!0,excludedFromUnreadCount:s||n,excludedFromLastMessage:s||n}}_createInviteSignalingData(e){const t=`${mo}._createInviteSignalingData`,{userID:s,timeout:n=0,groupID:o="",inviteeList:i=[]}=e,r=this._core.common.getCurrentUserID(),a=Object.assign(Object.assign({},this._generateBaseSignalData(e)),{actionType:so,inviter:r,inviteeList:o?i:[s],timeout:n});return console.log(`${t} signalingData:`,a),a}_createAcceptSignalingData(e){const t=`${mo}._createAcceptSignalingData`,{inviteID:s}=e,n=this._core.common.getCurrentUserID(),{inviter:o,groupID:i}=Mo.getSignaling(s),r=Object.assign(Object.assign({},this._generateBaseSignalData(e)),{actionType:oo,groupID:i,inviter:o,inviteeList:[n]});return console.log(`${t} signalingData:`,r),r}_createCancelSignalingData(e){const t=`${mo}._createCancelSignalingData`,{inviteID:s}=e,n=this._core.common.getCurrentUserID(),{inviteeList:o,groupID:i}=Mo.getSignaling(s),r=Object.assign(Object.assign({},this._generateBaseSignalData(e)),{actionType:no,groupID:i,inviter:n,inviteeList:o});return console.log(`${t} signalingData:`,r),r}_createRejectSignalingData(e){const t=`${mo}._createRejectSignalingData`,{inviteID:s}=e,n=this._core.common.getCurrentUserID(),{inviter:o,groupID:i}=Mo.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}_createTimeoutSignalingData(e){const t=`${mo}._createTimeoutSignalingData`,{isInviter:s=!1,inviteID:n}=e,{inviteeList:o,inviter:i}=Mo.getSignaling(n),r=this._core.common.getCurrentUserID(),a=Object.assign(Object.assign({},this._generateBaseSignalData(e)),{actionType:ro,inviter:i,inviteeList:s?o:[r]});return console.log(`${t} signalingData:`,a),a}_createSignaling(e,t){var s,n,o;const{groupID:i=""}=e,r={to:t,conversationType:i?uo:co,priority:"High",payload:{data:JSON.stringify(e)}};return null===(o=null===(n=null===(s=this._core)||void 0===s?void 0:s.message)||void 0===n?void 0:n.messageFactory)||void 0===o?void 0:o.createCustomMessage(r)}_generateInviteID(){return[So(Co(32),8),So(Co(16),4),So(16384|Co(12),4),So(32768|Co(14),4),So(Co(48),12)].join("-")}_generateBaseSignalData(e){const{data:t="",inviteID:s="",groupID:n=""}=e;return{businessID:1,timeout:0,data:t,inviteID:s,groupID:n}}};var Oo=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 de(this,void 0,void 0,function*(){var t;try{this._validateBeforeInvite(e);const{signaling:s,signalingData:n,signalingExtensionOptions:o}=yo.createInviteSignaling(e),i=yield this._sendSignaling(s,o);if(0===(null==i?void 0:i.code)){const{inviteID:e,timeout:o}=n;return Mo.saveSignaling(e,Object.assign(Object.assign({},n),{signaling:s})),o>0&&(null===(t=this._core)||void 0===t||t.helper.taskScheduler.addOnceTask({id:`${fo}-${e}`,intervalMs:1e3*(o+5),callback:this.handleInvitationExpiryTimer.bind(this,e)})),Object.assign(Object.assign({},i),{inviteID:e})}return i}catch(e){throw e}})}accept(e){return de(this,void 0,void 0,function*(){try{const{inviteID:t}=e;this._validateBeforeAccept(t),this._isProcessingSignaling=!0;const{signaling:s,signalingData:n,signalingExtensionOptions:o}=yo.createAcceptSignaling(e),i=yield this._sendSignaling(s,o);return 0===(null==i?void 0:i.code)?(Mo.updateSignaling(n),Object.assign(Object.assign({},i),{inviteID:t})):i}catch(e){throw e}finally{this._isProcessingSignaling=!1}})}cancel(e){return de(this,void 0,void 0,function*(){try{const{inviteID:t}=e;this._validateBeforeCancel(t),this._isProcessingSignaling=!0;const{signaling:s,signalingExtensionOptions:n}=yo.createCancelSignaling(e),o=yield this._sendSignaling(s,n);return 0===(null==o?void 0:o.code)?(Mo.removeSignaling(t),Object.assign(Object.assign({},o),{inviteID:t})):o}catch(e){throw e}finally{this._isProcessingSignaling=!1}})}reject(e){return de(this,void 0,void 0,function*(){try{const{inviteID:t}=e;this._validateBeforeReject(t),this._isProcessingSignaling=!0;const{signaling:s,signalingExtensionOptions:n}=yo.createRejectSignaling(e),o=yield this._sendSignaling(s,n);return 0===(null==o?void 0:o.code)?(Mo.removeSignaling(t),Object.assign(Object.assign({},o),{inviteID:t})):o}catch(e){throw e}finally{this._isProcessingSignaling=!1}})}modifyInvitation(e){return de(this,void 0,void 0,function*(){var t,s;const{inviteID:n,data:o}=e;let i="";try{this._validateBeforeModifyInvitation(n);const e=Mo.getSignaling(n),{signaling:r}=e,a=le(e,["signaling"]);i=r.payload.data,a.data=o,r.payload.data=JSON.stringify(a);const c=yield null===(s=null===(t=this._core)||void 0===t?void 0:t.message.messageAction)||void 0===s?void 0:s.modifyMessage(r);return Mo.hasSignaling(n)&&Mo.saveSignaling(n,Object.assign(Object.assign({},a),{signaling:r})),c}catch(e){if(i){const{signaling:e}=Mo.getSignaling(n);e.payload.data=i}throw e}})}getSignalingInfo(e){const{ssoLog:t,utils:{safeStringify:s}}=this._core;if(0===Io([e]).length)return;const n=Eo(e),o={businessID:n.businessID||1,inviteID:n.inviteID,groupID:n.groupID||"",inviter:n.inviter||"",inviteeList:n.inviteeList||[],data:n.data||"",actionType:n.actionType||so,timeout:n.timeout||0};return t.debug(`${mo} getSignalingInfo ${s(o)}`),o}addSignalingListener(e,t,s){var n,o;e===(null===(n=this._core)||void 0===n?void 0:n.SignalingEvent.NEW_INVITATION_RECEIVED)&&Mo.setSignalingListenStatus(!0),null===(o=this._core)||void 0===o||o.notificationCenter.subscribeOuterEvent(e,t,s)}removeSignalingListener(e,t,s){var n,o;e===(null===(n=this._core)||void 0===n?void 0:n.SignalingEvent.NEW_INVITATION_RECEIVED)&&Mo.setSignalingListenStatus(!1),null===(o=this._core)||void 0===o||o.notificationCenter.unSubscribeOuterEvent(e,t,s)}handleInvitationExpiryTimer(e){const t=Mo.getOnlineSignalingMap(),s=this._core.common.getCurrentUserID();if(!t.has(e))return;const n=t.get(e).inviter===s;this._sendTimeoutNotice({inviteID:e,isInviter:n})}_sendSignaling(e,t){return de(this,void 0,void 0,function*(){var s,n,o;return null===(o=null===(n=null===(s=this._core)||void 0===s?void 0:s.message)||void 0===n?void 0:n.messageSender)||void 0===o?void 0:o.sendMessage(e,t)})}_sendTimeoutNotice(e){return de(this,void 0,void 0,function*(){var t,s,n;this._core.ssoLog.debug("_sendTimeoutNotice",`${mo}._sendTimeoutNotice params:${JSON.stringify(e)}`);const{isInviter:o,inviteID:i}=e,{signaling:r,signalingData:a,signalingExtensionOptions:c}=yo.createTimeoutSignaling(e),u=yield this._sendSignaling(r,c);if(0===(null==u?void 0:u.code)){const{data:e,groupID:c,inviteeList:u,inviter:l}=a;null===(t=this._core)||void 0===t||t.notificationCenter.emitOuterEvent(null===(s=this._core)||void 0===s?void 0:s.SignalingEvent.INVITATION_TIMEOUT,{name:null===(n=this._core)||void 0===n?void 0:n.SignalingEvent.INVITATION_TIMEOUT,data:{data:e,groupID:c,inviteID:i,inviteeList:u,inviter:l,isSelfTimeout:!0,message:r}}),o?Mo.removeSignaling(i):Mo.updateSignaling(a)}})}_validateInviteId(e,t){if(!Mo.hasSignaling(t))throw new this._core.helper.ChatError({functionName:e,code:vo})}_validateProcessStatus(e){if(this._isProcessingSignaling)throw new this._core.helper.ChatError({functionName:e,message:"processing other signaling operations"})}_validateBeforeInvite(e){const t=lo,{userID:s}=e,n=this._core.common.getCurrentUserID();if(s===n)throw new this._core.helper.ChatError({functionName:t,message:`cannot invite yourself, currentUserId:${n}, inviteeId:${s}`})}_validateBeforeAccept(e){const t=ho;this._validateInviteId(t,e),this._validateProcessStatus(t);const s=this._core.common.getCurrentUserID(),{inviteeList:n}=Mo.getSignaling(e);if(!n.includes(s)){const n=`userID:${s} not in inviteeList. inviteID:${e}`;throw new this._core.helper.ChatError({functionName:t,message:n})}}_validateBeforeCancel(e){const t=go;this._validateInviteId(t,e),this._validateProcessStatus(t);const s=this._core.common.getCurrentUserID(),{inviter:n}=Mo.getSignaling(e);if(n!==s){const e=`unmatched inviter:${n} and my userID:${s}`;throw new this._core.helper.ChatError({functionName:t,message:e})}}_validateBeforeReject(e){const t=po;this._validateInviteId(t,e),this._validateProcessStatus(t);const s=this._core.common.getCurrentUserID(),{inviteeList:n}=Mo.getSignaling(e);if(!n.includes(s)){const n=`userID:${s} not in inviteeList. inviteID:${e}`;throw new this._core.helper.ChatError({functionName:t,message:n})}}_validateBeforeModifyInvitation(e){const t=_o;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 Ao=new class{constructor(){this._actionProcessor=new Map([[so,this._onNewInvitationReceived.bind(this)],[io,this._onInviteeRejected.bind(this)],[oo,this._onInviteeAccepted.bind(this)],[no,this._onInvitationCancelled.bind(this)],[ro,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=Eo(e);if(t){const s=this._actionProcessor.get(t.actionType);null==s||s(t,e)}})}_handleMessageReceived(e){if(!Mo.getSignalingListenStatus())return;const t=Io(e.data);0!==t.length&&this.handleActionSignaling(t)}_handleMessageModified(e){if(!Mo.getSignalingListenStatus())return;const t=Io(e.data);t.length>0&&t.forEach(e=>{const t=Eo(e);t&&this._onInvitationModified(t,e)})}_onNewInvitationReceived(e,t){var s,n;const o=`${mo}._onNewInvitationReceived`,{inviteID:i,inviteeList:r,groupID:a}=e,c=this._core.common.getCurrentUserID();this._core.ssoLog.debug("_onNewInvitationReceived",`${o} signalingData:${JSON.stringify(e)}}`);if(a&&!r.includes(c))return;let{timeout:u}=e;const l=Date.now()/1e3-t.time;u>0&&l>0&&u>l&&(u-=l);const d=Mo.getSignaling(i);d!==e&&(d||Mo.saveSignaling(i,Object.assign(Object.assign({},e),{signaling:t})),u>0&&(null===(s=this._core)||void 0===s||s.helper.taskScheduler.addOnceTask({id:`${fo}-${i}`,intervalMs:1e3*u,callback:Oo.handleInvitationExpiryTimer.bind(Oo,i)})),this._emitEvent({name:null===(n=this._core)||void 0===n?void 0:n.SignalingEvent.NEW_INVITATION_RECEIVED,data:Object.assign(Object.assign({},this._generateBaseEmitData(e)),{inviteeList:r})}))}_onInviteeRejected(e){var t;const s=`${mo}._onInviteeRejected`,{inviteID:n,inviter:o,groupID:i,inviteeList:r}=e,a=Mo.hasSignaling(n);this._core.ssoLog.debug("_onInviteeRejected",`${s} inviteID:${n} hasInviteID:${a} inviter:${o} groupID:${i}`),a&&(Mo.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=`${mo}._onInviteeAccepted`,{inviteID:n,inviter:o,groupID:i,inviteeList:r}=e,a=Mo.hasSignaling(n);this._core.ssoLog.debug("_onInviteeAccepted",`${s} inviteID:${n} hasInviteID:${a} inviter:${o} groupID:${i}`),a&&(Mo.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=`${mo}._onInvitationCancelled`,{inviteID:n,inviter:o,groupID:i}=e,r=Mo.hasSignaling(n);this._core.ssoLog.debug("_onInvitationCancelled",`${s} inviteID:${n} hasInviteID:${r} inviter:${o} groupID:${i}`),r&&(Mo.removeSignaling(n),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=`${mo}._onInvitationTimeout`,{inviteID:n,inviteeList:o}=e,i=Mo.hasSignaling(n);this._core.ssoLog.debug("_onInvitationTimeout",`${s} inviteID:${n} hasInviteID:${i} data:${e.data}`),i&&(Mo.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:o,isSelfTimeout:!1})}))}_onInvitationModified(e,t){var s;const n=`${mo}._onInvitationModified`,{inviteID:o,data:i}=e,r=Mo.hasSignaling(o);this._core.ssoLog.debug("_onInvitationModified",`${n} inviteID:${o} data:${i}`),r&&(Mo.saveSignaling(o,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:o,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:n,data:o}=e;return{inviteID:t,inviter:s,groupID:n,data:o||""}}_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 To=new class{constructor(){this._offlineSignalingMap=new Map}init(e){this._core=e;const{notificationCenter:t,helper:s,constants:{InnerEvent:n,WORKFLOW_STEP:o,WORKFLOW_NAME:i}}=e;t.subscribeInnerEvent(n.DESTROY,this._dispose,this),t.subscribeInnerEvent(n.LOGOUT,this._reset,this),s.registerWorkflowStep(i.SYNC_SERVER_INFO_AFTER_LOGIN,o.SIGNALING_MESSAGE_RECOVER,this._handleC2COfflineMessage,this)}_handleC2COfflineMessage(e){const{result:{unreadMessageMap:t}={}}=e||{};if(!(0!==(null==t?void 0:t.size)&&Mo.getSignalingListenStatus()))return;const s=Io([...t.values()]);if(0!==s.length&&(s.forEach(e=>{this._handleC2CActionType(e)}),this._offlineSignalingMap.size>0)){const e=this._sortOfflineSignalingByTime();Ao.handleActionSignaling(e)}}_handleC2CActionType(e){const t=Eo(e);if(!t)return;const{actionType:s}=t;s===so?this._saveValidOfflineInvite(t,e):this._removeOfflineInvite(t)}_saveValidOfflineInvite(e,t){const{inviteID:s,inviteeList:n=[],timeout:o=0}=e,i=this._core.common.getCurrentUserID();if(!n.includes(i))return;const r=Date.now()/1e3-t.time;o>0&&r>o&&0!==o||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 Ro={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}}},Do={invite:!0,cancel:!0,accept:!0,reject:!0,modifyInvitation:!0};var bo=new class{constructor(){this.name="Signaling"}install(e){Oo.init(e),Ao.init(e),yo.init(e),Mo.init(e),To.init(e),e.helper.registerValidateConfig({auth:Do,params:Ro})}};const No=new class{init(e){this.core=e}};var Lo,Po;!function(e){e.MSG_TEXT="TIMTextElem",e.MSG_CUSTOM="TIMCustomElem",e.MSG_LOCATION="TIMLocationElem",e.MSG_FACE="TIMFaceElem"}(Lo||(Lo={})),function(e){e[e.FORWARD=0]="FORWARD",e[e.BACKWARD=1]="BACKWARD"}(Po||(Po={}));const wo="MSG_REACTION",Go="MSG_EXT",Uo=0,ko=1,Fo={ZH_CN:"zh (cmn-Hans-CN)",EN_US:"en-US",YUE_HK:"yue-Hant-HK",JA_JP:"ja-JP",ZH_PY:"zh-PY"},$o="16k_zh",qo="16k_en",xo="16k_yue",Vo="16k_ja",Bo="16k_zh-PY",jo={[Fo.ZH_CN]:$o,[Fo.EN_US]:qo,[Fo.YUE_HK]:xo,[Fo.JA_JP]:Vo,[Fo.ZH_PY]:Bo},Ko=/\.(wav|pcm|ogg-opus|speex|silk|mp3|m4a|aac|amr)/,Ho={READ:0,UNREAD:1},Wo=1,Yo=2,zo=3,Jo=1,Qo=2;var Xo;!function(e){e.IN="in",e.OUT="out"}(Xo||(Xo={}));const Zo=16,ei=17;const ti=2116,si=2500,ni="C2C",oi="GROUP",ii=20;function ri(e){return de(this,void 0,void 0,function*(){var t,s;const{appStore:n,utils:{isEmpty:o},common:{getCurrentUserID:i},notificationCenter:r,OuterEvent:a}=No.core,{messageList:c,conversationID:u}=e,l=n.conversationStore.getConversationMap();let d=null===(t=l.get(u))||void 0===t?void 0:t.peerReadTime;if(!d){const e=u.replace(ni,""),t=yield function(e){return de(this,void 0,void 0,function*(){const t={To_Account:e};return No.core.common.buildAndSendPacket({servcmd:"openim.get_peer_read_time",data:t})})}([e]);if(t){const{ReadTime:e}=t;d=null==e?void 0:e[0],l.has(u)&&(l.get(u).peerReadTime=d)}}if(l.has(u)){const e=null===(s=l.get(u))||void 0===s?void 0:s.lastMessage;o(e)||e.fromAccount===i()&&e.lastTime<=d&&!e.isPeerRead&&(e.isPeerRead=!0,n.conversationStore.updateConversation(u,{lastMessage:e}))}const h=[];c.forEach(e=>{e.time<=d&&!e.isPeerRead&&"out"===e.flow&&(e.isPeerRead=!0,h.push(e))}),r.emitOuterEvent(a.MESSAGE_READ_BY_PEER,{name:a.MESSAGE_READ_BY_PEER,data:h})})}function ai(e){return de(this,void 0,void 0,function*(){var t;const{message:s,user:n,appStore:o,constants:{OuterConstant:i}}=No.core,r=o.conversationStore.getConversationMap();if(r.has(e)){const s=null===(t=r.get(e))||void 0===t?void 0:t.userProfile;if(s&&e.startsWith(i.CONV_C2C)){const{avatar:t,nick:n}=s;No.core.message.messageDataHandler.updateNickAndAvatarOfSentMessage({conversationID:e,latestAvatar:t,latestNick:n,isSentByMe:!1})}}const{data:a}=(yield n.userProfile.getMyProfile())||{};if(a){const{avatar:t,nick:n}=a;s.messageDataHandler.updateNickAndAvatarOfSentMessage({conversationID:e,latestAvatar:t,latestNick:n,isSentByMe:!0})}})}function ci(e){let t;const{message:s}=No.core,{conversationID:n,messageID:o}=e;if(t=s.messageDataHandler.getLocalMessageList(n).find(e=>e.ID===o),!t){t=s.messageDataHandler.getSparseMessageList(n).find(e=>e.ID===o)}return t}function ui(e){return e.map(e=>{const{from:t,to:s,cloudCustomData:n,avatar:o,nick:i,ID:r,clientSequence:a,clientTime:c,messageRandom:u,messageSequence:l,time:d}=e;return{ClientSeq:a,CloudCustomData:n,From_Account:t,From_AccountHeadurl:o,From_AccountNick:i,Id:r,MsgBody:JSON.parse(JSON.stringify(e.transformElementsToServerFormat())),MsgClientTime:c,MsgRandom:u,Random:u,MsgSeq:l,MsgTimeStamp:d,ReceiverId:s,SenderId:t,To_Account:s}})}function li(e){var t;const{From_Account:s,From_AccountHeadurl:n,From_AccountNick:o,GroupId:i,MsgClientTime:r,ClientSeq:a,To_Account:c,MsgTimeStamp:u,TinyId:l,MsgRandom:d,MsgSeq:h}=e;return{from:s,avatar:n,nick:o,clientTime:r,time:u,tinyID:l,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 No.core.message.messageFactory.getElementClass(t).parseServerPushElement(e)})}}var di=new class{constructor(){this._reactionsMap=new Map}init(e){this._core=e;const{helper:t,notificationCenter:s,InnerEvent:{MESSAGE_PUSH:n},InnerEventSubType:{MESSAGE_REACTION_UPDATED:o,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(n,o,this._handleReactionUpdated,this),s.subscribeInnerEvent(n,i,this._handleReactionSync,this)}addMessageReaction(e,t){return de(this,void 0,void 0,function*(){const{OuterConstant:s,ssoLog:n,helper:o}=this._core;this._validateMessageReactionBusinessCapability();const{conversationID:i,ID:r,conversationType:a,from:c,to:u,clientSequence:l,random:d,time:h,sequence:g}=e,p=`conversationID:${i} messageID:${r} reactionID:${t}`;try{return this._recordMessageReactedByMe(r,t),a===s.CONV_C2C?yield function(e,t){return de(this,void 0,void 0,function*(){var s;const{from:n,to:o,clientSequence:i,random:r,time:a,reactionID:c}=e,u={From_Account:n,To_Account:o,MsgKey:`${i}_${r}_${a}`,Reaction:c,Add_Account:[null===(s=t.store.get("login"))||void 0===s?void 0:s.userId]};return No.core.common.buildAndSendPacket({servcmd:"openim_msg_ext_http_svc.reaction_add",data:u})})}({from:c,to:u,clientSequence:l,random:d,time:h,reactionID:t},this._core):a===s.CONV_GROUP&&(yield function(e,t){return de(this,void 0,void 0,function*(){var s;const{to:n,reactionID:o,sequence:i}=e,r={GroupId:n,MsgSeq:i,Reaction:o,Add_Account:[null===(s=t.store.get("login"))||void 0===s?void 0:s.userId]};return No.core.common.buildAndSendPacket({servcmd:"openim_msg_ext_http_svc.group_reaction_add",data:r})})}({to:u,reactionID:t,sequence:g},this._core)),{code:0,successLog:{message:p}}}catch(e){this._removeMyReactionRecord(r,t);const{errorCode:s}=e||{};throw new o.ChatError({functionName:"addMessageReaction",code:s,moreMessage:p})}})}removeMessageReaction(e,t){return de(this,void 0,void 0,function*(){const{OuterConstant:s,helper:n}=this._core;this._validateMessageReactionBusinessCapability();const{conversationID:o,ID:i,conversationType:r,from:a,to:c,clientSequence:u,random:l,time:d,sequence:h}=e,g=`conversationID:${o} messageID:${i} reactionID:${t}`;try{return this._removeMyReactionRecord(i,t),r===s.CONV_C2C?yield function(e,t){return de(this,void 0,void 0,function*(){var s;const{from:n,to:o,clientSequence:i,random:r,time:a,reactionID:c}=e,u={From_Account:n,To_Account:o,MsgKey:`${i}_${r}_${a}`,Reaction:c,Del_Account:[null===(s=t.store.get("login"))||void 0===s?void 0:s.userId]};return No.core.common.buildAndSendPacket({servcmd:"openim_msg_ext_http_svc.reaction_del",data:u})})}({from:a,to:c,clientSequence:u,random:l,time:d,reactionID:t},this._core):r===s.CONV_GROUP&&(yield function(e,t){return de(this,void 0,void 0,function*(){var s;const{to:n,reactionID:o,sequence:i}=e,r={GroupId:n,MsgSeq:i,Reaction:o,Del_Account:[null===(s=t.store.get("login"))||void 0===s?void 0:s.userId]};return No.core.common.buildAndSendPacket({servcmd:"openim_msg_ext_http_svc.group_reaction_del",data:r},t)})}({to:c,reactionID:t,sequence:h},this._core)),{code:0,successLog:{message:g}}}catch(e){const{errorCode:t}=e||{};throw new n.ChatError({functionName:"removeMessageReaction",code:t,moreMessage:g})}})}getAllUserListOfMessageReaction(e){return de(this,void 0,void 0,function*(){this._validateMessageReactionBusinessCapability();const{message:t,reactionID:s,nextSeq:n=0}=e,o=e.count>100?100:e.count,{conversationID:i}=t,{ssoLog:r,helper:a,constants:c}=this._core;try{let e=null;if(e=i.startsWith(c.OuterConstant.CONV_C2C)?yield function(e){return de(this,void 0,void 0,function*(){const{message:t,nextSeq:s,reactionID:n,count:o}=e,{from:i,to:r,clientSequence:a,random:c,time:u}=t,l={Reaction:n,NextSeq:s,Count:o,From_Account:i,To_Account:r,MsgKey:`${a}_${c}_${u}`};return No.core.common.buildAndSendPacket({servcmd:"openim_msg_ext_http_svc.reaction_iterate",data:l})})}({message:t,reactionID:s,nextSeq:n,count:o}):yield function(e){return de(this,void 0,void 0,function*(){const{message:t,nextSeq:s,reactionID:n,count:o}=e,{sequence:i,to:r}=t,a={Reaction:n,NextSeq:s,GroupId:r,Count:o,MsgSeq:i};return No.core.common.buildAndSendPacket({servcmd:"openim_msg_ext_http_svc.group_reaction_iterate",data:a})})}({message:t,reactionID:s,nextSeq:n,count:o}),e){const{Reaction_Account:t,NextSeq:s}=e,o=yield this._getUserProfileList(t);return{code:0,data:{nextSeq:s,isCompleted:0===n,userList:o}}}}catch(e){const{errorCode:t}=e||{};throw new a.ChatError({functionName:"getAllUserListOfMessageReaction",code:t})}})}getMessageReactions(e){return de(this,void 0,void 0,function*(){const{constants:t}=this._core;this._validateMessageReactionBusinessCapability();const{messageList:s,maxUserCountPerReaction:n=10}=e,o=s[0];let i=null;const r=new Map,{from:a,to:c,conversationType:u}=o,l=this._generateMessageKeyList(s,r);u===t.OuterConstant.CONV_C2C?i=yield function(e){return de(this,void 0,void 0,function*(){const{from:t,to:s,messageKeyList:n,maxUserCountPerReaction:o}=e,i={From_Account:t,To_Account:s,MsgKeyList:n,Count:o};return No.core.common.buildAndSendPacket({servcmd:"openim_msg_ext_http_svc.reaction_multi_stat",data:i})})}({from:a,to:c,messageKeyList:l,maxUserCountPerReaction:n}):u===t.OuterConstant.CONV_GROUP&&(i=yield function(e){return de(this,void 0,void 0,function*(){const{groupId:t,messageSequenceList:s,maxUserCountPerReaction:n}=e,o={GroupId:t,MsgSeqList:s,Count:n};return No.core.common.buildAndSendPacket({servcmd:"openim_msg_ext_http_svc.group_reaction_multi_stat",data:o})})}({groupId:c,messageSequenceList:l,maxUserCountPerReaction:n}));const{Results:d=[]}=i||{},h=this._extractUserIDsFromReactionResults(d),g=yield this._getUserProfileMap(h);return{code:0,data:{resultList:d.map(e=>{const{ReactionList:t,MsgSeq:s,MsgKey:n}=e;return{messageID:this._generateMessageID({messageSequence:s,messageKey:n,messageIDMap:r}),reactionList:t.map(e=>{const{Reaction:t,Count:s,Reaction_Account:n,ReactedByMe:o}=e;return{reactionID:t,totalUserCount:s,partialUserList:this._generatePartialUserInfo({userIDList:n,userProfileMap:g}),reactedByMyself:1===o}})}})}}})}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 de(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 de(this,void 0,void 0,function*(){const t=new Map;return(yield this._getUserProfileList(e)).forEach(e=>{const{nick:s,avatar:n,userID:o}=e;t.set(o,{nick:s,avatar:n,userID:o})}),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:n}=e,o=`${t}-${s}`,i=this._reactionsMap.get(o)||{};this._reactionsMap.set(o,Object.assign(Object.assign({},i),n))}_validateMessageReactionBusinessCapability(){const{helper:e,constants:t}=this._core;if(!e.checkBusinessCapabilityBits(wo))throw new e.ChatError({functionName:"addMessageReaction",code:t.ERROR_CODE.NO_USE,replacement1:"addMessageReaction"})}_handleReactionUpdated(e){const{MsgReactionNotifyList:t}=e,{notificationCenter:s,constants:n}=this._core;t.forEach(e=>de(this,void 0,void 0,function*(){const{C2CMsgInfo:t,GroupMsgInfo:o,MsgReactionSummary:i}=e,{TinyId:r,MsgClientTime:a,MsgRandom:c}=Object.assign(Object.assign({},t),o),u=`${r}-${a}-${c}`,l=this._extractUserIDsFromReactionResults([{ReactionList:i}]),d=yield this._getUserProfileMap(l),h=i.map(e=>{var t;const{Reaction:s,Reaction_Account:n}=e,o=this._generatePartialUserInfo({userIDList:n,userProfileMap:d}),i=n?e.Count:0,r=(null===(t=this._reactionsMap.get(`${u}-${s}`))||void 0===t?void 0:t.reactedByMe)||!1;return this._recordMessageReactionInfo({messageID:u,reactionID:s,reactionInfo:{reactionID:s,totalUserCount:i,partialUserList:o}}),{reactionID:s,totalUserCount:i,partialUserList:o,reactedByMyself:r}});s.emitOuterEvent(n.OuterEvent.MESSAGE_REACTIONS_UPDATED,{name:n.OuterEvent.MESSAGE_REACTIONS_UPDATED,data:{messageID:u,reactionList:h}})}))}_handleReactionSync(e){var t;const{notificationCenter:s,constants:n}=this._core,{C2CMsgInfo:o={},GroupMsgInfo:i={},Reaction:r,OperateType:a}=e.MsgReactionNotify,{TinyId:c="",MsgClientTime:u=0,MsgRandom:l=0}=Object.assign(Object.assign({},o),i),d=`${c}-${u}-${l}`,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(n.OuterEvent.MESSAGE_REACTIONS_UPDATED,{name:n.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:n}=e;return s?n.get(s):n.get(t)}_generateMessageKeyList(e,t){const{constants:s}=this._core,n=e[0],{conversationType:o}=n;let i=[];return o===s.OuterConstant.CONV_C2C?i=e.map(e=>{const{clientSequence:s,random:n,time:o,ID:i}=e,r=`${s}_${n}_${o}`;return t.set(r,i),r}):o===s.OuterConstant.CONV_GROUP&&(i=e.map(e=>{const{ID:s,sequence:n}=e;return t.set(n,s),n})),i}};var hi=new class{init(e){this._core=e;const{helper:t,InnerEvent:{MESSAGE_PUSH:s},InnerEventSubType:{C2C_MESSAGE_READ_RECEIPT:n,GROUP_MESSAGE_READ_RECEIPT:o},notificationCenter:i}=e;t.registerApi({apiName:"sendMessageReadReceipt",context:this}),t.registerApi({apiName:"getMessageReadReceiptList",context:this}),t.registerApi({apiName:"getGroupMessageReadMemberList",context:this}),i.subscribeInnerEvent(s,n,this._handleC2CMessageReadReceipt,this),i.subscribeInnerEvent(s,o,this._handleGroupMessageReadReceipt,this)}sendMessageReadReceipt(e){return de(this,void 0,void 0,function*(){const{common:t,constants:s}=this._core,n=this._filterValidMessageSendByOther(e);if(0===n.length)throw new t.ChatError({code:s.ERROR_CODE.READ_RECEIPT_MSG_LIST_EMPTY});try{const{conversationType:e}=n[0];return e===s.OuterConstant.CONV_C2C?yield function(e){return de(this,void 0,void 0,function*(){const{common:t,constants:s}=No.core,n=e[0].conversationID.replace(s.OuterConstant.CONV_C2C,""),o=e.map(e=>{const{from:t,to:s,sequence:n,random:o,time:i,clientTime:r}=e;return{From_Account:t,To_Account:s,MsgSeq:n,MsgRandom:o,MsgTime:i,MsgClientTime:r}}),i={Peer_Account:n,C2CMsgInfo:o};return t.buildAndSendPacket({servcmd:"openim.c2c_msg_read_receipt",data:i})})}(n):yield function(e){return de(this,void 0,void 0,function*(){const{common:t,constants:s}=No.core,n={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:n})})}(n),{code:0,data:{}}}catch(e){const{errorCode:s,errorInfo:n}=e;throw new t.ChatError({code:s,message:n})}})}getMessageReadReceiptList(e){return de(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 de(this,void 0,void 0,function*(){const{common:t,constants:s}=No.core,n={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:n})})}(t),{GroupMsgReceiptList:n}=s||{};this._updateGroupMessagesReadReceiptInfo({messageList:e,readReceiptList:n})}}return{code:0,data:{messageList:e}}}catch(e){const{errorCode:s,errorInfo:n}=e;throw new t.ChatError({code:s,message:n})}})}getGroupMessageReadMemberList(e){return de(this,void 0,void 0,function*(){const{constants:t,common:s}=this._core,{message:n,filter:o=Ho.READ,cursor:i=""}=e,{conversationID:r,sequence:a,ID:c}=n,u=r.replace(t.OuterConstant.CONV_GROUP,""),l=e.count>=100?100:e.count;try{const e=yield function(e){return de(this,void 0,void 0,function*(){const{sequence:t,groupID:s,filter:n,cursor:o,count:i}=e,r={MsgSeq:t,GroupId:s,Filter:n,Cursor:o,Num:i};return No.core.common.buildAndSendPacket({servcmd:"group_open_http_svc.get_group_msg_receipt_detail",data:r})})}({groupID:u,sequence:a,filter:o,cursor:i,count:l});if(e){const{Cursor:t,IsFinish:s,UnreadList:n,ReadList:i}=e,r={cursor:t,isCompleted:1===s,messageID:c,unreadUserIDList:[],readUserIDList:[]};return o===Ho.READ?r.readUserIDList=i.map(e=>e.Read_Account):o===Ho.UNREAD&&(r.unreadUserIDList=n.map(e=>e.Unread_Account)),{code:0,data:r}}}catch(e){const{errorCode:t,errorInfo:n}=e;throw new s.ChatError({code:t,message:n})}})}_handleC2CMessageReadReceipt(e){const t=[],{constants:s,helper:n}=this._core,{C2cMsgInfo:o,PeerReadTime:i,Peer_Account:r}=e;if(n.isEmpty(o))return;const a=`${s.OuterConstant.CONV_C2C}${r}`;null==o||o.forEach(e=>{const{TinyId:s,MsgClientTime:n,MsgRandom:o}=e,c=`${s}-${n}-${o}`,u=ci({conversationID:a,messageID:c});u&&!u.readReceiptInfo.isPeerRead&&(u.readReceiptInfo.isPeerRead=!0,u.readReceiptInfo.timestamp=i,t.push({userID:r,messageID:c,isPeerRead:!0,timestamp:i}))}),this._emitReadReceiptEventIfNeed(t)}_updateGroupMessagesReadReceiptInfo(e){const{messageList:t,readReceiptList:s}=e,n=new Map;t.forEach(e=>{n.set(e.sequence,e)}),null==s||s.forEach(e=>{if(0===e.Code){const{MsgSeq:t,ReadNum:s,UnreadNum:o}=e,i=n.get(t);i&&(i.readReceiptInfo.readCount=s,i.readReceiptInfo.unreadCount=o)}})}_handleGroupMessageReadReceipt(e){const t=[],{constants:s}=this._core,{GroupTips:n}=e;n.forEach(e=>{const{MsgBody:{GroupMsgReceiptList:n},GroupInfo:{GroupId:o}}=e,i=`${s.OuterConstant.CONV_GROUP}${o}`;null==n||n.forEach(e=>{const{TinyId:s,MsgClientTime:n,MsgRandom:r,ReadNum:a,UnreadNum:c}=e,u=`${s}-${n}-${r}`,l=ci({conversationID:i,messageID:u}),d={groupID:o,messageID:u,readCount:0,unreadCount:0};l&&("number"==typeof a&&(l.readReceiptInfo.readCount=a,d.readCount=a),"number"==typeof c&&(l.readReceiptInfo.unreadCount=c,d.unreadCount=c),t.push(d))})}),this._emitReadReceiptEventIfNeed(t)}_emitReadReceiptEventIfNeed(e){const{notificationCenter:t,OuterEvent:s}=this._core;e.length>0&&t.emitOuterEvent(s.MESSAGE_READ_RECEIPT_RECEIVED,{name:s.MESSAGE_READ_RECEIPT_RECEIVED,data:e})}_filterValidMessageSendByOther(e){return this._filterNeedReadReceiptMessages(e).filter(e=>{const{from:t}=e;return t!==this._core.common.getCurrentUserID()})}_filterValidMessageSendByMe(e){const{OuterConstant:t}=this._core.constants;return this._filterNeedReadReceiptMessages(e).filter(e=>{const{from:s,status:n}=e;return s===this._core.common.getCurrentUserID()&&n===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:n}=this._core;n.unSubscribeInnerEvent(e,t,this._handleC2CMessageReadReceipt,this),n.unSubscribeInnerEvent(e,s,this._handleGroupMessageReadReceipt,this)}};function gi(e,t,s){return de(this,void 0,void 0,function*(){const{common:{buildAndSendPacket:n}}=No.core,{from:o,to:i,clientSequence:r,random:a,time:c}=e;return n({servcmd:"openim_msg_ext_http_svc.set_key_values",data:{From_Account:o,To_Account:i,MsgKey:`${r}_${a}_${c}`,OperateType:s,ExtensionList:t}})})}function pi(e,t,s){return de(this,void 0,void 0,function*(){const{common:{buildAndSendPacket:n}}=No.core,{to:o,sequence:i}=e;return n({servcmd:"openim_msg_ext_http_svc.group_set_key_values",data:{GroupId:o,MsgSeq:i,OperateType:s,ExtensionList:t}})})}var _i=new class{constructor(){this._messageExtensionsMap=new Map,this._extensionsLatestSequenceMap=new Map,this._completedFetchExtensions=new Set}init(e){this._core=e;const{notificationCenter:t,helper:{registerApi:s},InnerEvent:{MESSAGE_PUSH:n,LOGOUT:o},InnerEventSubType:{MESSAGE_EXTENSIONS_UPDATED:i}}=e;s({apiName:"setMessageExtensions",context:this}),s({apiName:"getMessageExtensions",context:this}),s({apiName:"deleteMessageExtensions",context:this}),t.subscribeInnerEvent(n,i,this._handleMessageExtensionsNotify,this),t.subscribeInnerEvent(o,this.reset,this)}setMessageExtensions(e,t){return de(this,void 0,void 0,function*(){this._validateMessageExtensionBusinessCapability("setMessageExtensions");const{constants:{OuterConstant:s},ssoLog:n}=this._core,{ID:o,conversationID:i,sequence:r,time:a,conversationType:c}=e;let u=t;t.length>20&&(u=t.slice(0,20),n.warn("setMessageExtensions","the length of extensions cannot exceed 20"));const l=this._generateServerExtensions(e,u),d=`convID:${i} messageID:${o} sequence:${r} time:${a} count:${u.length}`;try{let t;if(c===s.CONV_C2C?t=yield gi(e,l,Wo):c===s.CONV_GROUP&&(t=yield pi(e,l,Wo)),t){const{resultList:s,successCount:n,failureCount:o}=this._handleModifyMessageExtensions(e,t);return{code:0,data:{extensions:s},successLog:{message:`${d} successCount:${n} failCount:${o}`}}}return{code:0,data:{extensions:[]}}}catch(e){const{errorCode:t}=e;throw new this._core.helper.ChatError({functionName:"setMessageExtensions",code:t,moreMessage:d})}})}getMessageExtensions(e){return de(this,void 0,void 0,function*(){const{utils:{isUndefined:t}}=this._core;this._validateMessageExtensionBusinessCapability("getMessageExtensions");const{conversationID:s,ID:n,sequence:o,time:i}=e,r=`convID:${s} messageID:${n} sequence:${o} time:${i}`;try{let s;this._completedFetchExtensions.has(n)&&(s=this._extensionsLatestSequenceMap.get(n));const o=yield this._fetchMessageExtensions(e,s);return t(s)&&o.length>1&&this._completedFetchExtensions.add(n),{code:0,data:{extensions:o},successLog:{message:r}}}catch(e){const{errorCode:t,errorInfo:s=""}=e||{};throw new this._core.common.ChatError({code:t,message:s,moreMessage:r})}})}deleteMessageExtensions(e,t){return de(this,void 0,void 0,function*(){this._validateMessageExtensionBusinessCapability("deleteMessageExtensions");const{utils:{isEmpty:s},constants:{OuterConstant:n}}=this._core,{conversationType:o,conversationID:i,sequence:r,ID:a,time:c}=e;let u=zo;const l=[];s(t)||(u=Yo,null==t||t.forEach(e=>{l.push({key:e,value:"",seq:0})}));const d=`convID:${i} messageID:${a} sequence:${r} time:${c} operateType:${u}`,h=this._generateServerExtensions(e,l);try{let t;if(o===n.CONV_C2C?t=yield gi(e,h,u):o===n.CONV_GROUP&&(t=yield pi(e,h,u)),t){const{resultList:s,successCount:n,failureCount:o}=this._handleModifyMessageExtensions(e,t);return{code:0,data:{extensions:s},successLog:{message:`${d}successCount:${n} failCount:${o}`}}}return{code:0,data:{extensions:[]}}}catch(e){const{errorCode:t}=e;throw new this._core.helper.ChatError({functionName:"deleteMessageExtensions",code:t,moreMessage:d})}})}reset(){this._messageExtensionsMap.clear(),this._extensionsLatestSequenceMap.clear(),this._completedFetchExtensions.clear()}dispose(){this.reset();const{notificationCenter:e,InnerEvent:{MESSAGE_PUSH:t,LOGOUT:s},InnerEventSubType:{MESSAGE_EXTENSIONS_UPDATED:n}}=this._core;e.unSubscribeInnerEvent(t,n,this._handleMessageExtensionsNotify,this),e.subscribeInnerEvent(s,this.reset,this)}_handleModifyMessageExtensions(e,t){const{ID:s}=e,{Seq:n}=t,o=t.ExtensionList||[],i=[];let r=0,a=0,c=[];return o.forEach(e=>{const{ErrorCode:t,Extension:s}=e,{Key:n,Value:o,Seq:u}=s;i.push({code:t,key:n,value:o}),0===t?r++:a++,c.push({key:n,value:o,seq:u})}),this._extensionsLatestSequenceMap.set(s,n),c.length>0&&this._updateLocalExtensions(e.ID,c),{resultList:i,successCount:r,failureCount:a}}_updateLocalExtensions(e,t){this._messageExtensionsMap.has(e)||this._messageExtensionsMap.set(e,new Map);const s=this._messageExtensionsMap.get(e);null==t||t.forEach(e=>{const{key:t,seq:n,value:o=""}=e;null==s||s.set(t,{value:o,seq:n})})}_fetchMessageExtensions(e,t){return de(this,void 0,void 0,function*(){const{constants:{OuterConstant:s},utils:{isEmpty:n}}=this._core;try{let o;const{conversationType:i,ID:r}=e;if(i===s.CONV_C2C?o=yield function(e,t){const{common:{buildAndSendPacket:s}}=No.core,{from:n,to:o,clientSequence:i,random:r,time:a}=e;return s({servcmd:"openim_msg_ext_http_svc.get_key_values",data:{From_Account:n,To_Account:o,MsgKey:`${i}_${r}_${a}`,StartSeq:t}})}(e,t):i===s.CONV_GROUP&&(o=yield function(e,t){const{common:{buildAndSendPacket:s}}=No.core,{to:n,sequence:o}=e;return s({servcmd:"openim_msg_ext_http_svc.group_get_key_values",data:{GroupId:n,MsgSeq:o,StartSeq:t}})}(e,t)),o){const{LatestSeq:t,ClearSeq:s,CompleteFlag:i}=o,a=(o.ExtensionList||[]).map(e=>({key:e.Key,value:e.Value,seq:e.Seq}));if(this._updateLocalExtensions(r,a),this._clearLocationExtensions(r,s),this._extensionsLatestSequenceMap.set(r,t),1!==i){const t=a[a.length-1].seq+1;return this._fetchMessageExtensions(e,t)}const c=[];if(this._messageExtensionsMap.has(r)){const e=this._messageExtensionsMap.get(r);null==e||e.forEach((e,t)=>{const{value:s}=e;n(s)||c.push({key:t,value:s})})}return c}}catch(e){throw e}})}_clearLocationExtensions(e,t){if(!(t<=0)&&this._messageExtensionsMap.has(e)){const s=this._messageExtensionsMap.get(e);null==s||s.forEach((e,n)=>{e.seq<=t&&s.delete(n)})}}_generateServerExtensions(e,t){const{ID:s}=e;if(this._messageExtensionsMap.has(s)){const e=this._messageExtensionsMap.get(s);return t.map(t=>{var s;const{key:n,value:o}=t;let i=0;return(null==e?void 0:e.has(n))&&(i=null===(s=e.get(n))||void 0===s?void 0:s.seq),{Key:n,Value:o,Seq:i}})}return t.map(e=>({Key:e.key,Value:e.value,Seq:0}))}_validateMessageExtensionBusinessCapability(e){const{helper:t,constants:s}=this._core;if(!t.checkBusinessCapabilityBits(Go))throw new t.ChatError({functionName:e,code:s.ERROR_CODE.NO_USE,replacement1:e})}_handleMessageExtensionsNotify(e){const{SetKVInfo:t,DeleteKVInfo:s,ClearKVInfo:n,MsgOptType:o,TinyId:i,MsgLastSeq:r,ExtensionC2cMsgInfo:a,ExtensionGroupMsgInfo:c}=(null==e?void 0:e.MsgExtensionNotify)||{},u=a||c||{},{MsgClientTime:l,MsgRandom:d}=u,h=`${i}-${l}-${d}`;this._extensionsLatestSequenceMap.set(h,r),o===Wo?this._handleMessageExtensionsUpdated({messageID:h,updateMessageExtensionsInfo:t}):o===Yo?this._handleMessageExtensionsDeleted({messageID:h,deleteMessageExtensionsInfo:s}):o===zo&&this._handleMessageExtensionsCleared({messageID:h,clearMessageExtensionsInfo:n})}_handleMessageExtensionsUpdated(e){const{notificationCenter:t,OuterEvent:s}=this._core,{messageID:n,updateMessageExtensionsInfo:o=[]}=e,i=[];o.forEach(e=>{const{MsgKeyValue:t=[]}=e,s=t.map(e=>(i.push({key:e.Key,value:e.Value}),{key:e.Key,value:e.Value,seq:e.Seq}));this._updateLocalExtensions(n,s)}),t.emitOuterEvent(s.MESSAGE_EXTENSIONS_UPDATED,{name:s.MESSAGE_EXTENSIONS_UPDATED,data:{messageID:n,extensions:i}})}_handleMessageExtensionsDeleted(e){const{notificationCenter:t,OuterEvent:s}=this._core,{messageID:n,deleteMessageExtensionsInfo:o=[]}=e,i=[];o.forEach(e=>{const{MsgKeyValue:t=[]}=e,s=t.map(e=>(i.push(e.Key),{key:e.Key,seq:e.Seq}));this._updateLocalExtensions(n,s)}),t.emitOuterEvent(s.MESSAGE_EXTENSIONS_DELETED,{name:s.MESSAGE_EXTENSIONS_DELETED,data:{messageID:n,keyList:i}})}_handleMessageExtensionsCleared(e){const{notificationCenter:t,OuterEvent:{MESSAGE_EXTENSIONS_DELETED:s},utils:{isEmpty:n}}=this._core,{messageID:o,clearMessageExtensionsInfo:i=[]}=e,r=[];i.forEach(e=>{const{ClearMsgSeq:t}=e;if(this._messageExtensionsMap.has(o)){(this._messageExtensionsMap.get(o)||[]).forEach((e,s)=>{e.seq<=t&&!n(e.value)&&r.push(s)})}this._clearLocationExtensions(o,t)}),t.emitOuterEvent(s,{name:s,data:{messageID:o,keyList:r}})}};const mi={key:"message",required:!0,rules:["object"],allowEmpty:!1,customValidator:e=>{const{constants:{OuterConstant:t}}=No.core;return e.status!==t.MessageStatus.SUCCESS?"message is not success":!0===e.isSupportExtension||"message is not support extension"}},vi={setMessageExtensions:[mi,{key:"extensions",required:!0,rules:["array"],allowEmpty:!1}],getMessageExtensions:[mi],deleteMessageExtensions:[mi]},fi=Object.assign(Object.assign(Object.assign(Object.assign({deleteMessage:[{required:!0,rules:["array"],allowEmpty:!1}],revokeMessage:[{required:!0,rules:["object"],allowEmpty:!1}],resendMessage:[{key:"message",required:!0,rules:["object"],allowEmpty:!1},{key:"options",required:!1,rules:["object"],allowEmpty:!1}],getMessageList:{conversationID:{required:!0,rules:["string"],allowEmpty:!1},nextReqMessageID:{required:!1,rules:["string"],allowEmpty:!0},count:{required:!1,rules:["number"],allowEmpty:!0}},getMessageListHopping:{conversationID:{required:!0,rules:["string"],allowEmpty:!1},sequence:{required:!1,rules:["number"],allowEmpty:!0},direction:{required:!1,rules:["number"],allowEmpty:!0},count:{required:!1,rules:["number"],allowEmpty:!0}},createTextAtMessage:{to:{required:!0,rules:["string"],allowEmpty:!1},conversationType:{required:!0,rules:["string"],allowEmpty:!1,customValidator:e=>"GROUP"===e||"conversationType should be GROUP."},payload:{required:!0,rules:["object"],allowEmpty:!1,customValidator:e=>{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}}=No.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}}}),vi),{pinGroupMessage:{groupID:{required:!0,rules:["string"],allowEmpty:!1},message:{required:!0,rules:["object"],allowEmpty:!1},isPinned:{required:!0,rules:["boolean"],allowEmpty:!1}},getPinnedGroupMessageList:[{key:"groupID",required:!0,rules:["string"],allowEmpty:!1}]}),Ii=Object.assign(Object.assign(Object.assign(Object.assign({deleteMessage:!0,revokeMessage:!0,resendMessage:!0,getMessageList:!0,getMessageListHopping:!0,createTextAtMessage:!0,findMessage:!0,translateText:!0,createForwardMessage:!0,createLocationMessage:!0},{addMessageReaction:!0,removeMessageReaction:!0,getMessageReactions:!0,getAllUserListOfMessageReaction:!0}),{sendMessageReadReceipt:!0,getMessageReadReceiptList:!0,getGroupMessageReadMemberList:!0}),{setMessageExtensions:!0,getMessageExtensions:!0,deleteMessageExtensions:!0}),{pinGroupMessage:!0,getPinnedGroupMessageList:!0});class Ei{constructor(e){this._core=e}deleteMessage(e){return de(this,void 0,void 0,function*(){const{to:t,messageIdentifiers:s}=e,n={From_Account:this._core.common.getCurrentUserID(),To_Account:t,MsgKeyList:s};return this._core.common.buildAndSendPacket({servcmd:"openim.delete_c2c_msg_ramble",data:n})})}revokeMessage(e){return de(this,void 0,void 0,function*(){const{to:t,from:s,sequence:n,time:o,random:i}=e,r={MsgInfo:{From_Account:s,To_Account:t,MsgSeq:n,MsgRandom:i,MsgTimeStamp:o}};return this._core.common.buildAndSendPacket({servcmd:"openim.msgwithdraw",data:r})})}}class Si{constructor(e){this._core=e}deleteMessage(e){return de(this,void 0,void 0,function*(){const{to:t,messageIdentifiers:s}=e,n={GroupId:t,Deleter_Account:this._core.common.getCurrentUserID(),Seqs:s};return this._core.common.buildAndSendPacket({servcmd:"group_open_http_svc.delete_group_ramble_msg_by_seq",data:n})})}revokeMessage(e){return de(this,void 0,void 0,function*(){const{to:t,sequence:s}=e,n={GroupId:t,MsgSeqList:[{MsgSeq:s}]};return this._core.common.buildAndSendPacket({servcmd:"group_open_http_svc.group_msg_recall",data:n})})}}class Ci{constructor(e){this._core=e}generateRevokeMessage(e){const{conversationID:t,sequence:s,random:n,tinyID:o,clientTime:i,revokeReason:r,revoker:a}=e;let c={};const{messageDataHandler:u}=this._core.message;return c=u.revokeMessage({conversationID:t,sequence:s,random:n,revoker:a}),c||(c={conversationID:t,sequence:s},o&&i&&n&&(c.ID=`${o}-${i}-${n}`)),c.revoker=a,c.revokeReason=r,c.revokerInfo={userID:a,nick:"",avatar:""},c}updateRevokerInfo(e){return de(this,void 0,void 0,function*(){const t=e.map(e=>e.revoker);try{const s=yield this._fetchUserInfos(t);s&&e.forEach(e=>{const{revoker:t}=e;s[t]&&(e.revokerInfo.nick=s[t].nick||"",e.revokerInfo.avatar=s[t].avatar||"",e.revokerInfo.userID=t)})}catch(e){console.debug(e)}})}_fetchUserInfos(e){return de(this,void 0,void 0,function*(){var t,s;const n=yield null===(t=this._core.user.userProfile)||void 0===t?void 0:t.getUserProfile({userIDList:e});return(null==n?void 0:n.data)?null===(s=n.data)||void 0===s?void 0:s.reduce((e,{userID:t,nick:s,avatar:n})=>(e[t]={nick:s||"",avatar:n||""},e),{}):null})}}var Mi=new class{constructor(){this._core=null,this._c2cMessageAction=null,this._groupMessageAction=null}init(e){this._core=e,this._groupMessageAction=new Si(e),this._c2cMessageAction=new Ei(e),this._messageHelper=new Ci(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 de(this,void 0,void 0,function*(){let t=[],s=[];const{conversationID:n,conversationType:o}=e[0],i=n.replace(o,"");if("@TIM#SYSTEM"===o)throw new this._core.helper.ChatError({code:ti});if(e.forEach(e=>{const{conversationID:i,conversationType:r,status:a,_onlineOnlyFlag:c,sequence:u,random:l,time:d}=e||{};if("success"===a&&i===n&&r===o){if(!c){const e="C2C"===r?`${u}_${l}_${d}`:String(u);t.push(e)}s.push(e)}}),0===t.length)return this._handleDeleteMessageSuccess(s),{code:0,data:{messageList:s}};t.length>30&&(t=t.slice(0,30),s=s.slice(0,30));try{return"C2C"===o?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 de(this,void 0,void 0,function*(){var t;const{conversationType:s,isRevoked:n,ID:o,type:i,from:r,to:a}=e;let c=null;const u=`type:${i} from:${r} to:${a} ID:${o}`;if("@TIM#SYSTEM"===s)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",moreMessage:u});try{if(c="C2C"===s?yield this._c2cMessageAction.revokeMessage(e):yield this._groupMessageAction.revokeMessage(e),c){const{RecallRetList:s}=c,n=(null===(t=null==s?void 0:s[0])||void 0===t?void 0:t.RetCode)||0;if(0!==n)throw new this._core.helper.ChatError({code:n,moreMessage:u});return e.isRevoked=!0,yield this._handleRevokeMessageSuccess(e),{code:0,data:{message:e},successLog:{message:u}}}}catch(e){const{errorCode:t}=e;throw new this._core.helper.ChatError({functionName:"revokeMessage",code:t,moreMessage:u})}})}resendMessage(e,t){return de(this,void 0,void 0,function*(){var s,n;return e.isResend=!0,e.status="unSend",null===(n=null===(s=this._core)||void 0===s?void 0:s.apiMap)||void 0===n?void 0:n.sendMessage(e,t)})}findMessage(e){return this._core.message.messageDataHandler.findMessage(e)}_handleDeleteMessageSuccess(e){if(0===e.length)return;const{message:{messageDataHandler:t},common:{isTopic:s},notificationCenter:n,InnerEvent:o}=this._core;e.forEach(e=>{e.isDeleted=!0;const s=t.getLocalMessageList(e.conversationID);null==s||s.forEach(t=>{t.ID===e.ID&&(t.isDeleted=!0)})});const{conversationID:i=""}=e[0];s(i)?n.emitInnerEvent(o.TOPIC_MESSAGE_DELETED,i):n.emitInnerEvent(o.MESSAGE_DELETED,i)}_handleRevokeMessageSuccess(e){return de(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:n,sequence:o,random:i}=e;this._core.message.messageDataHandler.revokeMessage({conversationID:n,sequence:o,random:i,revoker:s}),yield this._messageHelper.updateRevokerInfo([e])})}};class yi{static parseServerPushElement(e){const{MsgContent:t={}}=e,{Index:s,Data:n}=t;return new yi({index:s,data:n})}constructor(e){this.type=Lo.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:n,data:o}=s;return{MsgType:this.type,MsgContent:{Index:n,Data:o}}}}class Oi{static parseServerPushElement(e){const{MsgContent:t={}}=e,{Desc:s,Longitude:n,Latitude:o}=t;return new Oi({description:s,longitude:n,latitude:o})}constructor(e){this.type=Lo.MSG_LOCATION;const{description:t,longitude:s,latitude:n}=e;this.content={description:t,longitude:s,latitude:n}}validateBeforeSend(){return{isValid:!0}}transformToServerFormat(e){const{isMergerMessage:t=!1}=e||{},s=t?this.payload:this.content,{description:n,longitude:o,latitude:i}=s;return{MsgType:this.type,MsgContent:{Desc:n,Longitude:o,Latitude:i}}}}var Ai=new class{init(e){this._core=e,e.message.messageFactory.registerElementClass(Lo.MSG_FACE,yi),e.message.messageFactory.registerElementClass(Lo.MSG_LOCATION,Oi),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)||{},n=new yi({index:t,data:s}),o=this._core.common.getCurrentUserID(),i=this._core.message.messageFactory.createMessage(Object.assign(Object.assign({},e),{from:o}));return i.setElement(n),i}createTextAtMessage(e){const{atUserList:t}=(null==e?void 0:e.payload)||{},s=this._core.apiMap.createTextMessage(e),{OuterConstant:n}=this._core;if(!s)return null;if(Array.isArray(t)){const e=[],o=[];t.forEach(t=>{t!==n.MSG_AT_ALL?(e.push({GroupAtAllFlag:Uo,GroupAt_Account:t}),o.push(t)):(e.push({GroupAtAllFlag:ko}),o.push(n.MSG_AT_ALL))}),s._groupAtInfoList=e,s.atUserList=o}return s}createForwardMessage(e){const{helper:t,OuterConstant:s}=this._core,{to:n,conversationType:o,priority:i,payload:r,needReadReceipt:a,receiverList:c,cloudCustomData:u="",isSupportExtension:l=!1}=e;if(!Array.isArray(r._elements))throw new t.ChatError({functionName:"createForwardMessage",code:2454});if(r.type===s.MSG_GRP_TIP)throw new t.ChatError({functionName:"createForwardMessage",code:2453});const d=this._core.common.getCurrentUserID(),h=this._core.message.messageFactory.createMessage({to:n,from:d,conversationType:o,isPlaceMessage:0,priority:i,payload:r,needReadReceipt:a,isSupportExtension:l,cloudCustomData:u,receiverList:c});return h.setRelayFlag(!0),h.setElement(r._elements[0]),h}createLocationMessage(e){if(!e)return null;const{description:t,longitude:s,latitude:n}=(null==e?void 0:e.payload)||{},o=new Oi({description:t,longitude:s,latitude:n}),i=this._core.common.getCurrentUserID(),r=this._core.message.messageFactory.createMessage(Object.assign(Object.assign({},e),{from:i}));return r.setElement(o),r}};let Ti=class{init(e){this._messageHelper=new Ci(e),this._core=e;const{notificationCenter:t,InnerEvent:{MESSAGE_PUSH:s},InnerEventSubType:{C2C_REVOKED_MESSAGE:n},helper:{registerWorkflowStep:o},constants:{WORKFLOW_NAME:i,WORKFLOW_STEP:r}}=e;t.subscribeInnerEvent(s,n,this._handleC2CNotifyMessage,this),o(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 de(this,void 0,void 0,function*(){try{const{WithdrawC2cMsgNotify:{C2cWithdrawInfoArray:t}}=e;yield this._parseAndEmitC2CRevokedMessages(t)}catch(e){console.debug(e)}})}_parseAndEmitC2CRevokedMessages(e){return de(this,void 0,void 0,function*(){const t=[],{notificationCenter:s,OuterEvent:n,common:{getCurrentUserID:o}}=this._core;e.forEach(e=>{var s;const{MsgRand:n,MsgSeq:i,To_Account:r,From_Account:a,RevokerInfo:{Revoker_Account:c,Revoke_Reason:u}}=e,l=o()===a?`C2C${r}`:`C2C${a}`,d=(null===(s=null==e?void 0:e.RevokerInfo)||void 0===s?void 0:s.Reason)||u,h=this._messageHelper.generateRevokeMessage({conversationID:l,sequence:i,random:n,revoker:c,revokeReason:d});t.push(h)}),t.length>0&&(yield this._messageHelper.updateRevokerInfo(t),s.emitOuterEvent(n.MESSAGE_REVOKED,{name:n.MESSAGE_REVOKED,data:t}))})}_handleC2CRevokeMessagesFromUnreadMessageSync(e){return de(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)}},Ri=class{init(e){this._messageHelper=new Ci(e),this._core=e;const{notificationCenter:t,InnerEvent:{MESSAGE_PUSH:s},InnerEventSubType:{GROUP_MESSAGE_REVOKED:n}}=e;t.subscribeInnerEvent(s,n,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 de(this,void 0,void 0,function*(){try{const{RevokerInfo:t,MsgBody:{GroupWithdrawInfoArray:s},GroupInfo:n}=e,o=[],i=[],{notificationCenter:r,OuterEvent:a,utils:{isEmpty:c},common:{isCommunity:u}}=this._core;let l=!1;n&&(l=u({groupID:n.GroupId})||!c(n.TopicId)),s.forEach(e=>{const{Random:s,MsgSeq:r,GroupId:a,MsgClientTime:c,TinyId:u,TopicId:d,RevokerInfo:{Revoker_Account:h=(null==t?void 0:t.Revoker_Account)||"",Reason:g=(null==t?void 0:t.Reason)||""}}=e,p=d?`GROUP${d}`:`GROUP${a}`,_=this._messageHelper.generateRevokeMessage({conversationID:p,sequence:r,random:s,tinyID:u,clientTime:c,revoker:h,revokeReason:g});l?(_.revokerInfo.nick=n.From_AccountNick,_.revokerInfo.avatar=n.From_AccountHeadurl,o.push(_)):i.push(_)}),i.length>0&&(yield this._messageHelper.updateRevokerInfo(i),o.push(...i)),0!==o.length&&r.emitOuterEvent(a.MESSAGE_REVOKED,{name:a.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 Di=new class{constructor(){this._c2cMessageReceiver=new Ti,this._groupMessageReceiver=new Ri}init(e){this._c2cMessageReceiver.init(e),this._groupMessageReceiver.init(e)}dispose(){this._c2cMessageReceiver.dispose(),this._groupMessageReceiver.dispose()}};class bi{constructor(e){this._core=e;const{constants:t}=e;this._messageHelper=new Ci(e),e.helper.registerWorkflowStep(t.WORKFLOW_NAME.SYNC_SERVER_INFO_AFTER_RE_ONLINE,t.WORKFLOW_STEP.GROUP_REVOKED_NOTICE_RECOVER,this._recoverGroupRevokeNotice,this)}getRoamingMessagesByAnchor(e){return this._core.message.messageHistory.getGroupRoamingMessagesByAnchor(e)}_recoverGroupRevokeNotice(e){const{recoverRevokeNoticeGroupIDList:t=[]}=e.result,s=this._filterValidGroupIDList(t);if(0===s.length)return;const n=Math.min(Math.ceil(s.length/10),5);Promise.all(Array.from({length:n},(e,t)=>{const n=10*t,o=Math.min(n+10,s.length);return this._fetchGroupRevokeNotice(s.slice(n,o))})).catch(e=>console.error(e))}_fetchGroupRevokeNotice(e){return de(this,void 0,void 0,function*(){var t;try{const s=yield function(e){return de(this,void 0,void 0,function*(){const{appStore:t,constants:{OuterConstant:s},common:n}=No.core,o=t.groupStore.getGroupMap(),i={NotifyReqList:e.map(e=>{const t=o.get(e);return{NotifyType:1,Limit:20,Type:n.isCommunity({type:t.type,groupID:e})?s.GRP_COMMUNITY:void 0,GroupId:e,BeginTime:(null==t?void 0:t._lastRevokedTime)||0,EndTime:1e3*No.core.common.timeManager.getServerTimeMs()}})||[]};return n.buildAndSendPacket({servcmd:"group_open_http_svc.batch_get_group_notify",data:i})})}(e);if(s){const e=[];null===(t=null==s?void 0:s.NotifyRspList)||void 0===t||t.forEach(t=>{const{GroupId:s,NotifyMsgList:n}=t,o=this._parseServerRevokeMessageList({groupID:s,serverRevokeMessageList:n});e.push(...o)}),0!==e.length&&(yield this._emitMessageRevokedEvent(e))}}catch(e){console.error(e)}})}_parseServerRevokeMessageList(e){const{serverRevokeMessageList:t,groupID:s}=e,n=[];return null==t||t.forEach(e=>{const{ClientTime:t,MsgSeq:o,Random:i,RevokerInfo:{Revoker_Account:r="",Reason:a=""}}=e,c=`GROUP${s}`,u=this._messageHelper.generateRevokeMessage({conversationID:c,sequence:o,random:i,clientTime:t,revoker:r,revokeReason:a});n.push(u)}),n}_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 n=s.get(e);return(null==n?void 0:n.type)!==t.GRP_AVCHATROOM&&!(null==n?void 0:n.isSupportTopic)}))||[]}_emitMessageRevokedEvent(e){return de(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 Ni{constructor(e){this._historyMessageListFetchAnchors=new Map,this._core=e,this._messageHelper=new Ci(e)}getRoamingMessagesByAnchor(e){return de(this,void 0,void 0,function*(){var t;try{const{conversationID:s,count:n,messageID:o,time:i,direction:r}=e;let a=i,c="";if(!i){const e=o?this._core.message.messageDataHandler.findMessage(o):null;if(a=(null==e?void 0:e.time)||0,o&&this._historyMessageListFetchAnchors.has(s)){const e=this._historyMessageListFetchAnchors.get(s);a=e.lastMessageTime,c=e.messageKey}}const u=s.replace(ni,""),l=yield function(e){return de(this,void 0,void 0,function*(){const{peerAccount:t,count:s,lastMessageTime:n,messageKey:o,direction:i}=e,r={Peer_Account:t,MaxCnt:s,WithRecalledMsg:1,LastMsgTime:n,MsgKey:o,GetDirection:i};return No.core.common.buildAndSendPacket({servcmd:"openim.getroammsg",data:r})})}({count:n,lastMessageTime:a,messageKey:c,peerAccount:u,direction:r});if(l){const{MsgList:e=[],Complete:n,MsgKey:o,LastMsgTime:i}=l;this._historyMessageListFetchAnchors.set(s,{messageKey:o,lastMessageTime:i});const r=[];for(let t=0;t<e.length;t++){const s=e[t],n=this._parseMessage(s);r.push(n)}const a=this._core.message.messageHelper.filterValidMessages(r);return{messageList:a,nextReqMessageIDFromServer:null===(t=a[0])||void 0===t?void 0:t.ID,lastMessageTime:i,hasNoMoreHistoryMessage:1===n}}}catch(e){throw new this._core.helper.ChatError({code:null==e?void 0:e.code})}})}clearHistoryMessageListFetchAnchors(e){this._historyMessageListFetchAnchors.delete(e)}reset(){this._historyMessageListFetchAnchors.clear()}_parseMessage(e){const t=ni,s=this._core.message.messageHelper.parseServerPushMessage(e),n=this._core.message.messageFactory.createMessage(Object.assign(Object.assign({},s),{conversationType:t,flow:"in"}));return n.setElement(s.elements),n}}var Li=new class{constructor(){this._clearedConversations=new Set,this._fetchedCompleteConversations=new Set}init(e){this._core=e,this._groupMessageHistory=new bi(e),this._c2cMessageHistory=new Ni(e),this._messageHelper=new Ci(e),e.helper.registerApi({apiName:"getMessageList",context:this}),e.helper.registerApi({apiName:"getMessageListHopping",context:this}),e.helper.registerApi({apiName:"clearHistoryMessage",context:this})}getMessageList(e){return de(this,void 0,void 0,function*(){try{let{conversationID:t,nextReqMessageID:s}=e;const n=ii;if("@TIM#SYSTEM"===t)return{code:0,data:{messageList:[],isCompleted:!1,nextMessageSeq:""}};const o=this._getAvailableLocalMessagesCount({conversationID:t,nextReqMessageID:s});if(this._needFetchHistoryMessageList({conversationID:t,availableLocalMessagesCount:o,targetCount:n})){let e=null;if(t.startsWith(oi)?e=yield this._groupMessageHistory.getRoamingMessagesByAnchor({conversationID:t,sequence:Number(s),count:n,direction:Po.FORWARD}):t.startsWith(ni)&&(e=yield this._c2cMessageHistory.getRoamingMessagesByAnchor({conversationID:t,messageID:s,count:n,direction:Po.FORWARD})),e){const{nextReqMessageIDFromServer:n,hasNoMoreHistoryMessage:i,messageList:r}=e,a=this._core.message.messageDataHandler.prependLocalMessageList({messageList:r,conversationID:t});!function(e){const{appStore:t,message:s,OuterConstant:n}=No.core,o=t.conversationStore.getConversation(e),i=s.messageDataHandler.getLocalMessageList(e);if(!o||0===i.length||e===n.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(o.type===n.CONV_C2C){const e=r.slice(-o.unreadCount).filter(e=>e.isRevoked).length;a=r.length-o.unreadCount-e}else a=r.length-o.unreadCount;for(let e=0;e<a&&!r[e].isRead;e++)r[e].setIsRead(!0)}(t),yield ai(t),t.startsWith(ni)&&(yield ri({messageList:r,conversationID:t}));const c=this._core.message.messageDataHandler.getLocalMessageList(t).slice(0,a.length+o),u=c.filter(e=>e.isRevoked);yield this._messageHelper.updateRevokerInfo(u),i&&this._fetchedCompleteConversations.add(t);const l={nextReqMessageID:i?"":String(n),messageList:c,isCompleted:i},d=c.map(e=>e.sequence);return{code:0,data:l,successLog:{message:`conversationID: ${t} nextReqMessageID: ${s} availableLocalMessagesCount: ${o} sequenceList: ${JSON.stringify(d)}`}}}return{code:0,data:{messageList:[],isCompleted:!1,nextReqMessageID:""}}}return{code:0,data:yield this._getMessageListFromMemory({conversationID:t,nextReqMessageID:s,count:n}),successLog:{message:`conversationID: ${t} nextReqMessageID: ${s} availableLocalMessagesCount: ${o}}`}}}catch(e){throw new this._core.helper.ChatError({code:null==e?void 0:e.code})}})}getMessageListHopping(e){return de(this,void 0,void 0,function*(){var t,s;const{conversationID:n,sequence:o,time:i,direction:r=Po.FORWARD}=e,{isEmpty:a}=this._core.helper;if(![Po.BACKWARD,Po.FORWARD].includes(r))throw new this._core.helper.ChatError({message:"direction must be 0 or 1"});let{count:c=ii}=e;c=c>ii?ii:c;let u=null;if(n.startsWith(oi)){if(u=yield this._groupMessageHistory.getRoamingMessagesByAnchor({conversationID:n,sequence:o,count:c,direction:r}),u){const{nextReqMessageIDFromServer:e,hasNoMoreHistoryMessage:n,messageList:i,invisibleSequenceList:c}=u;if(this._core.message.messageDataHandler.storeSparseMessageList(i),r===Po.FORWARD){const t=n&&e<1;return{code:0,data:{messageList:i,isCompleted:t,nextMessageSeq:t?"":e}}}if(r===Po.BACKWARD){if(a(i)&&a(c))return{code:0,data:{messageList:[],isCompleted:!0,nextMessageSeq:""}};const e=(null===(t=null==i?void 0:i[i.length-1])||void 0===t?void 0:t.sequence)||0,r=(null===(s=null==c?void 0:c[c.length-1])||void 0===s?void 0:s.sequence)||0;return{code:0,data:{messageList:i.filter(e=>e.sequence>=o),isCompleted:!n,nextMessageSeq:n?Math.max(e,r)+1:""}}}return{code:0,data:u}}}else if(n.startsWith(ni)&&(u=yield this._c2cMessageHistory.getRoamingMessagesByAnchor({conversationID:n,count:c+1,time:i,direction:r}),u)){const{messageList:e,lastMessageTime:t,hasNoMoreHistoryMessage:s}=u;return s||(r===Po.FORWARD?e.shift():e.pop()),this._core.message.messageDataHandler.storeSparseMessageList(e),{code:0,data:{messageList:e,isCompleted:s,nextMessageTime:s?"":t}}}})}clearHistoryMessage(e){return de(this,void 0,void 0,function*(){var t;const{appStore:s,common:{ChatError:n,getCurrentUserID:o},OuterConstant:{CONV_C2C:i,CONV_GROUP:r},message:a,apiMap:c}=this._core,u=s.conversationStore.getConversation(e);if(!u)throw new n({code:si});const l={fromAccount:o()},{type:d}=u;d===i?(l.type=Jo,l.toAccount=e.replace(i,"")):d===r&&(l.type=Qo,l.toGroupID=e.replace(r,""));try{yield null===(t=null==c?void 0:c.setMessageRead)||void 0===t?void 0:t.call(c,{conversationID:e});const s=yield function(e){return de(this,void 0,void 0,function*(){const{fromAccount:t,type:s,toAccount:n,toGroupID:o}=e,i={From_Account:t,Type:s,To_Account:n,ToGroupid:o};return No.core.common.buildAndSendPacket({servcmd:"recentcontact.clear_msg",data:i})})}(l);return s&&(a.messageDataHandler.deleteConversationMessageList(e),this._clearedConversations.add(e),this._fetchedCompleteConversations.delete(e),this._c2cMessageHistory.clearHistoryMessageListFetchAnchors(e),this._updateConversationLastMessage(e)),{code:0,data:{conversationID:e},successLog:{message:`convID:${e}`}}}catch(t){const{errorCode:s}=t;throw new this._core.helper.ChatError({functionName:"clearHistoryMessage",code:s,moreMessage:`convID:${e}`})}})}_updateConversationLastMessage(e){const{appStore:t}=this._core;t.conversationStore.updateConversation(e,{lastMessage:this._generateLastMessage()},{needSort:!0})}_getAvailableLocalMessagesCount({conversationID:e,nextReqMessageID:t}){const s=this._core.message.messageDataHandler.getLocalMessageList(e),{length:n}=s;if(!t)return n;let o=-1;return(null==e?void 0:e.startsWith(ni))?o=s.findIndex(e=>e.ID===t):(null==e?void 0:e.startsWith(oi))&&(o=s.findIndex(e=>t.includes("-")?e.ID===t:String(e.sequence)===t)),-1===o?0:o}_needFetchHistoryMessageList({conversationID:e,availableLocalMessagesCount:t,targetCount:s}){return!!this._clearedConversations.has(e)||t<s&&!this._fetchedCompleteConversations.has(e)}_getMessageListFromMemory(e){return de(this,arguments,void 0,function*({conversationID:e,nextReqMessageID:t,count:s}){const n=this._core.message.messageDataHandler.getLocalMessageList(e),o=n.length;let i=o,r={isCompleted:!1,nextReqMessageID:"",messageList:[]},a=0,c=o;return t?t&&(c=n.findIndex(s=>e.startsWith(ni)?s.ID===t:String(s.sequence)===t),a=c>s?c-s:0,i=c):a=o>s?o-s:0,r.nextReqMessageID=0===a?"":this._generateNextReqMessageID({conversationID:e,targetIndex:a}),r.messageList=n.slice(a,c),r.isCompleted=i<=s,e.startsWith(ni)&&(yield ai(e),yield ri({messageList:r.messageList,conversationID:e})),r})}_generateNextReqMessageID({conversationID:e,targetIndex:t}){const s=this._core.message.messageDataHandler.getLocalMessageList(e);return e.startsWith("C2C")?s[t].ID:String(s[t].sequence)}_generateLastMessage(){return{lastTime:0,lastSequence:0,fromAccount:"",messageForShow:"",payload:null,type:"",isRevoked:!1,cloudCustomData:"",onlineOnlyFlag:!1,nick:"",nameCard:"",version:0,isPeerRead:!1,revoker:null}}reset(){this._clearedConversations.clear(),this._fetchedCompleteConversations.clear(),this._c2cMessageHistory.reset()}dispose(){this.reset()}};var Pi=new class{constructor(){this._core=null}init(e){this._core=e;const{helper:t}=e;t.registerApi({apiName:"translateText",context:this})}translateText(e){return de(this,void 0,void 0,function*(){try{const{sourceLanguage:t,sourceTextList:s,targetLanguage:n}=e,o=yield function(e,t){return de(this,void 0,void 0,function*(){var s,n;const{sourceTextList:o,sourceLanguage:i,targetLanguage:r}=e,{store:a,common:c}=t,u={SourceText:o,Source:i,Target:r,FromAccount:null===(s=a.get("login"))||void 0===s?void 0:s.tinyID,SDKAppID:null===(n=a.get("instance"))||void 0===n?void 0:n.sdkAppId},l=yield c.buildAndSendPacket({servcmd:"im_open_translate.ws_batch_trans_text",data:u});if(l){const{CmdErrorCode:e,TargetText:t}=l;return{cmdErrorCode:e,translatedTextList:t}}})}({sourceLanguage:t,sourceTextList:s,targetLanguage:n},this._core);if(o){const{cmdErrorCode:{ErrorCode:e,ErrorInfo:t},translatedTextList:s}=o;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 wi=new class{init(e){this._core=e,e.helper.registerApi({apiName:"convertVoiceToText",context:this})}convertVoiceToText(e){return de(this,void 0,void 0,function*(){var t;const{message:s,language:n=Fo.ZH_PY}=e;let{url:o}=s.payload||{};const i=this._core.common.getCurrentUserID();s.from===i&&"out"===s.flow&&(o=s.payload.remoteAudioUrl),this._validateVoiceFormat(o);const r=(null===(t=Ko.exec(o))||void 0===t?void 0:t[1])||"mp3",a=jo[n]||Bo;try{const e=yield function(e){var t;const{store:s,common:n}=No.core,{url:o,format:i,serverLanguageType:r}=e,a={BytesUrl:o,BytesEngServiceType:r,BytesVoiceFormat:i,Uint32Sdkappid:null===(t=s.get("instance"))||void 0===t?void 0:t.sdkAppId,Uint64SourceType:0};return n.buildAndSendPacket({servcmd:"im_open_speech.ws_sentence_recognition",data:a})}({url:o,format:r,serverLanguageType:a});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||{};throw new this._core.common.ChatError({functionName:"convertVoiceToText",code:t,message:s})}})}_validateVoiceFormat(e){if(!Ko.test(e))throw new this._core.common.ChatError({code:2119})}};class Gi{constructor(e){const{constants:t,common:s,utils:n}=No.core,{CONV_C2C:o,CONV_GROUP:i}=t.OuterConstant,{ID:r,tinyID:a,from:c,to:u,clientTime:l=s.timeManager.getServerTimeSeconds()||0,random:d,sequence:h,cloudCustomData:g="",nick:p="",avatar:_="",clientSequence:m,conversationType:v,groupID:f,_elements:I,time:E}=e;this.ID=r||`${a}-${l}-${d}`,this.messageRandom=d,this.from=c,this.messageSender=c,this.time=E,this.messageSequence=h,this.clientSequence=m||h,this.clientTime=l,this.cloudCustomData=g,this.messageReceiver=u,this.avatar=_,this.nick=p;const S=n.deepCopyWithMethods(I);S.forEach(e=>{e.payload=e.content,delete e.content}),this.messageBody=S,r?v.startsWith(o)?this.receiverUserID=u:v.startsWith(i)&&(this.receiverGroupID=u):f?(this.receiverGroupID=f,this.messageReceiver=f):u&&(this.receiverUserID=u,this.messageReceiver=u)}transformElementsToServerFormat(){return this.messageBody?Array.isArray(this.messageBody)?this.messageBody.map(e=>e.transformToServerFormat({isMergerMessage:!0})):this.messageBody.transformToServerFormat({isMergerMessage:!0}):null}}class Ui{static parseServerPushElement(e){const{MsgContent:t}=e,{MsgList:s=[],CompatibleText:n,AbstractList:o,Title:i,PbMsgKey:r,JsonMsgKey:a}=t||{},c=s.map(e=>li(e));return new Ui({messageList:c,title:i,abstractList:o,compatibleText:n,pbDownloadKey:r,downloadKey:a})}constructor(e){this.type=No.core.constants.OuterConstant.MSG_MERGER;const{messageList:t,title:s,abstractList:n,compatibleText:o,pbDownloadKey:i="",downloadKey:r="",version:a=0,layersOverLimit:c=!1}=e,u=[];t.forEach(e=>{if(e){const t=new Gi(e);u.push(t)}}),this.content={messageList:u,title:s,abstractList:n,compatibleText:o,version:a,downloadKey:r,pbDownloadKey:i,layersOverLimit:c}}validateBeforeSend(){const{isEmpty:e}=No.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:n,compatibleText:o,downloadKey:i,layersOverLimit:r,pbDownloadKey:a,title:c,version:u,messageList:l}=s;return{MsgType:this.type,MsgContent:{AbstractList:n,CompatibleText:o,JsonMsgKey:i,LayersOverLimit:r,PbMsgKey:a,Title:c,Version:u,MsgList:ui(l)}}}}var ki=new class{init(e){this._core=e;const{message:t,helper:s,constants:{OuterConstant:n}}=e;t.messageFactory.registerElementClass(n.MSG_MERGER,Ui),s.registerApi({apiName:"createMergerMessage",context:this}),s.registerApi({apiName:"sendMessage",context:this,matcher:e=>e[0].type===n.MSG_MERGER}),s.registerApi({apiName:"downloadMergerMessage",context:this})}createMergerMessage(e){const{common:t}=this._core;if(!e)return null;const s=new Ui(e.payload),n=t.getCurrentUserID(),o=this._core.message.messageFactory.createMessage(Object.assign(Object.assign({},e),{from:n}));return o.setRelayFlag(!0),o.setElement(s),o}sendMessage(e,t){return de(this,void 0,void 0,function*(){var s,n,o;try{const i=function(e){let t="utf-8";No.core.helper.IN_BROWSER&&document&&(t=document.charset.toLowerCase());let s,n=0,o=0;if(o=e.length,"utf-8"===t||"utf8"===t)for(let t=0;t<o;t++)s=e.codePointAt(t),s<=127?n+=1:s<=2047?n+=2:s<=65535?n+=3:(n+=4,t++);else if("utf-16"===t||"utf16"===t)for(let t=0;t<o;t++)s=e.codePointAt(t),s<=65535?n+=2:(n+=4,t++);else n=e.replace(/[^\x00-\xff]/g,"aa").length;return n}(JSON.stringify(e));let r=e,a=null;if(i>11264){r=this._core.utils.deepCopyWithMethods(e);try{const{JsonMsgKey:e,PbMsgKey:t}=yield function(e){return de(this,void 0,void 0,function*(){const{payload:{messageList:t}}=e,s={MsgList:ui(t)};return No.core.common.buildAndSendPacket({servcmd:"im_long_msg.save_relay_json_msg",data:s})})}(r),{payload:s}=r;a=new Ui(Object.assign(Object.assign({},s),{messageList:[],downloadKey:e,pbDownloadKey:t})),r.setElement(a)}catch(e){console.error(e)}}const{data:{message:c}}=yield null===(o=null===(n=null===(s=this._core)||void 0===s?void 0:s.message)||void 0===n?void 0:n.messageSender)||void 0===o?void 0:o.sendMessage(r,t);return a&&c.setElement(e._elements),{code:0,data:{message:c}}}catch(e){const{errorCode:t}=e;throw new this._core.helper.ChatError({code:t})}})}downloadMergerMessage(e){return de(this,void 0,void 0,function*(){const{ssoLog:t}=this._core,s=e.payload,{downloadKey:n,pbDownload:o,type:i,messageList:r}=s,a=le(s,["downloadKey","pbDownload","type","messageList"]);try{const s=yield function(e){return de(this,void 0,void 0,function*(){return No.core.common.buildAndSendPacket({servcmd:"im_long_msg.get_relay_json_msg",data:{JsonMsgKey:e}})})}(n),{MsgList:o}=s||{},i=null==o?void 0:o.map(e=>{const t=li(e);return new Gi(t)});return"function"==typeof e.isOnlineMessage?e.setElement({type:e.type,content:Object.assign({messageList:i},a)}):(e.payload.messageList=i,e.payload.downloadKey="",e.payload.pbDownloadKey=""),t.info("downloadMergerMessage",` success downloadKey:${n}`),e}catch(e){const{errorCode:t}=e;throw new this._core.helper.ChatError({functionName:"downloadMergerMessage",code:t,moreMessage:n})}})}};var Fi=new class{init(e){this._core=e,this._core.helper.registerExperimentalAPI("sendComboMessage",this)}sendComboMessage(e){return de(this,void 0,void 0,function*(){const{appStore:t,message:s,common:{getCurrentUserID:n},utils:{isArray:o}}=this._core,{GroupId:i,To_Account:r}=e;e.From_Account=e.From_Account||n();let a=null;if(i){a=this._generateGroupMessage(Object.assign(Object.assign({},e),{ToGroupId:i}));const s=t.userStore.getUserProfile(n());a.level=(null==s?void 0:s.level)||0,o(r)&&r.length>0&&(a._receiverList=r)}else r&&(a=this._generateC2CMessage(e));return s.messageSender.sendMessage(a,e)})}_generateC2CMessage(e){const{message:t,OuterConstant:{CONV_C2C:s}}=this._core,n=s,o=t.messageHelper.parseServerPushMessage(e),i=t.messageFactory.createMessage(Object.assign(Object.assign({},o),{conversationType:n,flow:Xo.OUT})),{elements:r}=o;return i.setElement(r),i}_generateGroupMessage(e){const{message:t,OuterConstant:{CONV_GROUP:s}}=this._core,n=s,o=t.messageHelper.parseServerGroupMessage(e),i=t.messageFactory.createMessage(Object.assign(Object.assign({},o),{conversationType:n,flow:Xo.OUT})),{elements:r}=o;return i.setElement(r),i}};var $i=new class{init(e){this._core=e;const{helper:t,notificationCenter:s,InnerEvent:{MESSAGE_PUSH:n},InnerEventSubType:{GROUP_MESSAGE_PINNED:o}}=e;s.subscribeInnerEvent(n,o,this._handleGroupMessagePinned,this),t.registerApi({apiName:"pinGroupMessage",context:this}),t.registerApi({apiName:"getPinnedGroupMessageList",context:this})}pinGroupMessage(e){return de(this,void 0,void 0,function*(){const{ssoLog:t,common:{isTopic:s},OuterConstant:{GROUP_ID_PREFIX:n},helper:{ChatError:o}}=this._core;let{groupID:i,message:r,isPinned:a}=e;const{sequence:c}=r;try{return yield function(e){return de(this,void 0,void 0,function*(){const{common:{buildAndSendPacket:t,getCurrentUserID:s}}=No.core,{groupID:n,sequence:o,isPinned:i}=e,r=s(),a=i?"group_open_http_svc.pin_message":"group_open_http_svc.unpin_message",c={GroupId:n,MsgSeq:o};return i?c.Pinner_Account=r:c.UnPinner_Account=r,t({servcmd:a,data:c})})}({groupID:i,sequence:c,isPinned:a}),{code:0,data:{}}}catch(e){const{errorCode:t,errorInfo:s}=e||{};throw new o({code:t,message:s})}})}getPinnedGroupMessageList(e){return de(this,void 0,void 0,function*(){let t=[];try{const s=yield function(e){return de(this,void 0,void 0,function*(){const{groupID:t}=e,{common:{buildAndSendPacket:s}}=No.core;return s({servcmd:"group_open_http_svc.get_pinned_messages",data:{GroupId:t}})})}({groupID:e});if(s){const{PinnedMsgList:n=[]}=s;t=yield this._updatePinnedMessageInfo({serverPinnedMessageList:n,groupID:e})}return{code:0,data:{messageList:t}}}catch(e){throw e}})}_handleGroupMessagePinned(e){const{message:{messageHelper:t,messageFactory:s},notificationCenter:n,OuterEvent:o,OuterConstant:i}=this._core;e.GroupTips.forEach(e=>{const{ToGroupId:r,MsgBody:{PinnedMsg:a,OpType:c,MsgOperatorMemberExtraInfo:u,SdkGroupMessageId:l}}=e,{UserId:d,NickName:h="",ImageUrl:g=""}=u;let p=null,_=!1;if(c===Zo){_=!0;const e=t.parseServerGroupMessage(a);p=s.createMessage(Object.assign(Object.assign({},e),{conversationType:i.CONV_GROUP,flow:"in"})),p.setElement(e.elements),p.pinnerInfo={userID:d,nick:h,avatar:g}}else if(c===ei){const{ClientTime:e,Random:t,SenderTinyId:s,ServerTime:n,MsgSeq:o}=l;p={ID:`${s}-${e}-${t}`,sequence:o,random:t,time:n,clientTime:e}}p&&n.emitOuterEvent(o.PINNED_GROUP_MESSAGE_UPDATED,{name:o.PINNED_GROUP_MESSAGE_UPDATED,data:{groupID:r,message:p,isPinned:_,operatorInfo:{userID:d,nick:h,avatar:g}}})})}_findMessageBySequence(e,t){const{message:{messageDataHandler:s}}=this._core;return[...s.getLocalMessageList(e),...s.getSparseMessageList(e)].find(e=>e.sequence===t)}_updatePinnedMessageInfo(e){return de(this,arguments,void 0,function*({serverPinnedMessageList:e,groupID:t}){const{OuterConstant:{CONV_GROUP:s},utils:{isEmpty:n}}=this._core,o=[],i=[],r=[],a=new Map,c=`${s}${t}`;for(let t=0;t<e.length;t++){const s=e[t],{Pinner_Account:n,MsgSeq:u}=s,l=this._findMessageBySequence(c,u);i.push(n),a.set(u,n),l?o.push(l):r.push(u)}const u=yield this._fetchPinnedMessageInfo({conversationID:c,messageSequenceList:r,pinnerIDList:i});if(u){const{pinnerInfoMap:e,messageList:t}=u;return o.push(...t),o.forEach(t=>{const{sequence:s}=t,n=a.get(s),o=e[n]||{userID:n,nick:"",avatar:""};t.pinnerInfo=o}),o.sort((e,t)=>e.sequence-t.sequence),o}return[]})}_fetchPinnedMessageInfo(e){return de(this,void 0,void 0,function*(){var t,s;const{message:{messageHistory:n},user:{userProfile:o},utils:{isArray:i}}=this._core,{conversationID:r,messageSequenceList:a,pinnerIDList:c}=e,u=yield Promise.all([this._fetchMessageBySequence({conversationID:r,messageSequenceList:a}),null==o?void 0:o.getUserProfile({userIDList:c})]);if(i(u)){const e={};return((null===(t=u[1])||void 0===t?void 0:t.data)||[]).forEach(t=>{const{userID:s,nick:n="",avatar:o=""}=t;e[s]={userID:s,nick:n,avatar:o}}),{messageList:(null===(s=u[0])||void 0===s?void 0:s.messageList)||[],pinnerInfoMap:e}}})}_fetchMessageBySequence(e){return de(this,void 0,void 0,function*(){const{utils:{isEmpty:t},message:{messageHistory:s}}=this._core,{conversationID:n,messageSequenceList:o}=e;return t(o)?[]:s.getGroupRoamingMessagesByAnchor({conversationID:n,messageSequenceList:o,getType:3})})}};var qi=new class{constructor(){this.name="MessageEnhancer"}install(e){this._core=e,No.init(e),Mi.init(e),Ai.init(e),Di.init(e),Li.init(e),di.init(e),Pi.init(e),wi.init(e),hi.init(e),ki.init(e),_i.init(e),Fi.init(e),$i.init(e),e.helper.registerValidateConfig({auth:Ii,params:fi}),e.notificationCenter.subscribeInnerEvent(e.InnerEvent.LOGOUT,this._reset,this),e.notificationCenter.subscribeInnerEvent(e.InnerEvent.DESTROY,this.dispose,this)}dispose(){const{notificationCenter:e,InnerEvent:t}=this._core;e.unSubscribeInnerEvent(t.LOGOUT,this._reset,this),e.unSubscribeInnerEvent(t.DESTROY,this.dispose,this),Di.dispose(),Li.dispose(),hi.dispose(),_i.dispose()}_reset(){Li.reset()}};var xi=new class{constructor(){this._name="WebRequest"}init(e){this._core=e}request(e,t){return de(this,void 0,void 0,function*(){var s;const{isEmpty:n}=null===(s=this._core)||void 0===s?void 0:s.utils,{downloadUrl:o="",method:i="PUT",url:r,qs:a,headers:c={},resources:u,dataType:l="text",uploadByIP:d,uploadIP:h}=e;let g=r;if(a){const e=this._queryString(a);e&&(g+=`${g.includes("?")?"&":"?"}${e}`)}const p=new XMLHttpRequest;p.open(i.toUpperCase(),g,!0),p.responseType=l;const _=Object.assign({},c);if(d&&h&&(_.host=h),!n(_))for(const e in _)_.hasOwnProperty(e)&&!["content-length","user-agent","origin","host"].includes(e.toLowerCase())&&p.setRequestHeader(e,_[e]);return p.onload=()=>{const s=this._getResponseBody(p,o,d&&h),n=this._buildResponse(p,s);if(200===p.status)t(null,n);else{if(h&&!g.includes(h))return e.url=this._domainName2IP(g,h),e.uploadByIP=!0,this.request(e,t);t({code:p.status,message:JSON.stringify(p.responseText)},n)}},p.onerror=()=>{const e=this._getResponseBody(p,o,d&&h),s=this._buildResponse(p,e),n={code:p.status,message:0===p.status?"CORS blocked or network error":JSON.stringify(p.responseText)};t(n,s)},e.onProgress&&p.upload&&(p.upload.onprogress=t=>{const{total:s,loaded:n}=t,o=Math.min(Math.floor(100*n/s),100);e.onProgress({total:s,loaded:n,percent:o/100})}),p.send(u),p})}_buildResponse(e,t){const s={};return e.getAllResponseHeaders().trim().split("\n").forEach(e=>{if(e){const[t,n]=e.split(":").map(e=>e.trim());s[t.toLowerCase()]=n}}),{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 n;const{isEmpty:o,isPlainObject:i}=null===(n=this._core)||void 0===n?void 0:n.utils;return o(e)?"":i(e)?Object.keys(e).map(n=>{const o=encodeURIComponent(n)+s;return Array.isArray(e[n])?e[n].map(e=>o+encodeURIComponent(e)).join(t):o+encodeURIComponent(e[n])}).filter(Boolean).join(t):void 0}_domainName2IP(e,t){return e.replace(/^http(s)?:\/\/(.*?)\//,`https://${t}/`)}};const Vi=["unknown","image","video","audio","log"];var Bi=new class{init(e){this._core=e}request(e,t){var s;const{MINI_APP_NAMESPACE:n,IN_ALIPAY_MINI_APP:o,isUniIOSApp:i}=null===(s=this._core)||void 0===s?void 0:s.utils,{resources:r="",headers:a={},url:c,downloadUrl:u=""}=e;let l=c,d=null;const h=u?u.match(/^(https?:\/\/[^/]+\/)([^/]*\/?)(.*)$/):null;if(!h)return void console.warn("message Invalid download URL format");const g=decodeURIComponent(h[3]),p=g.includes("?")?g.split("?")[0]:g||"",_={key:e.fileKey||p,success_action_status:200,"Content-Type":""},m={};if(i()){const[e,t]=c.split("?sign=");t&&(l=`${e}?sign=${encodeURIComponent(t)}`,m.sign=decodeURIComponent(t),m.signature=decodeURIComponent(t))}let v={url:l,header:a,name:"file",filePath:r,formData:Object.assign(Object.assign({},_),m),timeout:e.timeout||3e5};if(o){const{name:t}=v,s=le(v,["name"]);v=Object.assign(Object.assign({},s),{fileName:"file",fileType:e.fileType?Vi[e.fileType]:"image"})}return d=n.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})}})),d.onProgressUpdate&&d.onProgressUpdate(t=>{e.onProgress&&e.onProgress({total:t.totalBytesExpectedToSend||0,loaded:t.totalBytesSent||0,percent:t.progress?Math.floor(t.progress)/100:0})}),d}_handleResponse(e){const{downloadUrl:t,response:s,callback:n}=e,o={};if(s.header)for(const e in s.header)s.header.hasOwnProperty(e)&&(o[e.toLowerCase()]=s.header[e]);const i=+s.statusCode;200===i?n(null,{statusCode:i,headers:o,data:Object.assign(Object.assign({},s.data),{location:t})}):n({code:i,message:JSON.stringify(s.data)},{statusCode:i,headers:o,data:void 0})}};function ji(e){return"file"===function(e){return Object.prototype.toString.call(e).match(/^\[object (.*)\]$/)[1].toLowerCase()}(e)}function Ki(e){const t=e||99999999;return Math.round(Math.random()*t)}function Hi(e,t=!0,s=!0){const n=Date.now();return t?s?n-e+" ms":`${Math.round((n-e)/1e3)} s`:s?n-e:Math.round((n-e)/1e3)}function Wi(e){return`${Array.from({length:8},()=>Math.floor(65536*(1+Math.random())).toString(16).substring(1)).join("")}-${e}`}function Yi(e,t){return Math.round(Number(e)*10**t)/10**t}function zi(e){const t=1024,s=1048576;return e<t?`${e}B`:e<s?`${Math.floor(e/t)}KB`:`${Math.floor(e/s)}MB`}function Ji(e){if(e<=1048576){return`${Yi(e/1024,1)}KB/s`}return`${Yi(e/1048576,1)}MB/s`}const Qi="TIMImageElem",Xi="TIMSoundElem",Zi="TIMFileElem",er="TIMVideoFileElem",tr="RichMediaMessagePlugin",sr=["rich.my-imcloud.com","imrich.qcloud.com"],nr=1,or=2,ir=3,rr=255;var ar;!function(e){e.UNSENT="unSend",e.SUCCESS="success",e.FAIL="fail"}(ar||(ar={}));const cr={wechat:/^(wxfile:\/\/tmp_|http:\/\/temp\/|cloud:\/\/temp-)/,alipay:/^(https:\/\/resource\/|alipayfile:\/\/tmp\/)/,baidu:/^(http:\/\/tmp\/|swanfile:\/\/tmp_)/,bytedance:/^(ttfile:\/\/tmp_|\/(var|tmp)\/|tttemp:\/\/)/,qq:/^(qqfile:\/\/tmp_|http:\/\/qtemp\/)/},ur=Symbol("isCustomUpload");var lr,dr=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,n]=e.split("?");if(!n)return s;const o=n.split("&").reduce((e,s)=>{const[n,o]=s.split("=");return n&&n!==t&&(e[n]=o||""),e},{}),i=Object.keys(o).map(e=>`${e}${o[e]?`=${o[e]}`:""}`).join("&");return i?`${s}?${i}`:s}(e,"authKey")}_isMiniProgramTempFile(e){return!!this.getPlatformFlags().IN_MINI_APP&&Object.values(cr).some(t=>t.test(e))}extractFileFromInput(e){const{utils:{isArray:t}}=this._core;return ji(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?t(e.tempFiles)&&e.tempFiles.length>0?e.tempFiles[0]:t(e.files)?e.files[0]:e.tempFile?e.tempFile:null:e instanceof HTMLInputElement&&e.files&&e.files.length>0?e.files[0]:null}probeImageWidthHeight(e){return de(this,void 0,void 0,function*(){var t;const{IN_MINI_APP:s,IN_BROWSER:n}=(null===(t=this._core)||void 0===t?void 0:t.utils)||{};return this._shouldSkipProbing()?{width:0,height:0}:n?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=sr;const s=(null===(e=this._core)||void 0===e?void 0:e.store.get("cloudConfig"))||{},{file_dn_list:n}=s;if(void 0===n)return t;try{JSON.parse(n).forEach(e=>{t.includes(e)||t.push(e)})}catch(e){console.warn(e),t=sr}return t}getPlatform(){var e;return null===(e=this._core)||void 0===e?void 0:e.utils.platform}generateUUID(e,t){var s;let n=`${this.getSDKAppID()}-${this.getCurrentUserID()}-${null===(s=this._core)||void 0===s?void 0:s.utils.randomString()}`;if(t)return`${n}.${t}`;const o=e.name||e.value||e.url||e.tempFilePath,i=o&&o.slice(o.lastIndexOf(".")+1);return i&&(n=`${n}.${i}`),n}processResourceUrl(e){if(!e)return"";let t=e;const s=this.getFileDownloadProxy(),n=this.getAuthKey(),o=this.getFileDNList();s&&(e.startsWith("http://")?t=e.replace(/^http:\/\/[^/]+/,s):e.startsWith("https://")&&(t=e.replace(/^https:\/\/[^/]+/,s)));const i=n&&-1===t.indexOf("authKey=")&&function(e,t){let s=!1;if(e){const n=e.match(/:\/\/([0-9]?\.)?(.[^/:]+)/),o=n&&n[2]||"";if(o.includes("rich-dev"))return!0;for(let e=0;e<t.length;e++)if(o.endsWith(t[e])){s=!0;break}}return s}(t,o);return i&&(t=t.indexOf("?")>-1?`${t}&authKey=${n}`:`${t}?authKey=${n}`),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:n,IN_UNI_NATIVE_APP:o}=null===(e=this._core)||void 0===e?void 0:e.utils;return{IN_BROWSER:t,IN_MINI_APP:s,IN_RN_APP:n,IN_UNI_NATIVE_APP:o}}isEmpty(e){var t;const{isEmpty:s}=null===(t=this._core)||void 0===t?void 0:t.utils;return s(e)}generateURL(e,t){const{needAddAuthToUrl:s=!0}=t||{};return s?this.addAuthToUrl(e):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:n,IN_WX_MINI_GAME:o}=(null===(e=this._core)||void 0===e?void 0:e.utils)||{};return t||s&&9===n||o}_probeImageDimensionsWeb(e){return new Promise(t=>{const s=new Image,n=()=>{s.onload=null,s.onerror=null,s.src=""};s.onload=()=>{t({width:s.width,height:s.height}),n()},s.onerror=()=>{t({width:0,height:0}),n()},s.src=e})}},hr={exports:{}};var gr=(lr||(lr=1,function(e){e.exports=function(e){var t=["0","1","2","3","4","5","6","7","8","9","a","b","c","d","e","f"];function s(e,t){var s=e[0],n=e[1],o=e[2],i=e[3];n=((n+=((o=((o+=((i=((i+=((s=((s+=(n&o|~n&i)+t[0]-680876936|0)<<7|s>>>25)+n|0)&n|~s&o)+t[1]-389564586|0)<<12|i>>>20)+s|0)&s|~i&n)+t[2]+606105819|0)<<17|o>>>15)+i|0)&i|~o&s)+t[3]-1044525330|0)<<22|n>>>10)+o|0,n=((n+=((o=((o+=((i=((i+=((s=((s+=(n&o|~n&i)+t[4]-176418897|0)<<7|s>>>25)+n|0)&n|~s&o)+t[5]+1200080426|0)<<12|i>>>20)+s|0)&s|~i&n)+t[6]-1473231341|0)<<17|o>>>15)+i|0)&i|~o&s)+t[7]-45705983|0)<<22|n>>>10)+o|0,n=((n+=((o=((o+=((i=((i+=((s=((s+=(n&o|~n&i)+t[8]+1770035416|0)<<7|s>>>25)+n|0)&n|~s&o)+t[9]-1958414417|0)<<12|i>>>20)+s|0)&s|~i&n)+t[10]-42063|0)<<17|o>>>15)+i|0)&i|~o&s)+t[11]-1990404162|0)<<22|n>>>10)+o|0,n=((n+=((o=((o+=((i=((i+=((s=((s+=(n&o|~n&i)+t[12]+1804603682|0)<<7|s>>>25)+n|0)&n|~s&o)+t[13]-40341101|0)<<12|i>>>20)+s|0)&s|~i&n)+t[14]-1502002290|0)<<17|o>>>15)+i|0)&i|~o&s)+t[15]+1236535329|0)<<22|n>>>10)+o|0,n=((n+=((o=((o+=((i=((i+=((s=((s+=(n&i|o&~i)+t[1]-165796510|0)<<5|s>>>27)+n|0)&o|n&~o)+t[6]-1069501632|0)<<9|i>>>23)+s|0)&n|s&~n)+t[11]+643717713|0)<<14|o>>>18)+i|0)&s|i&~s)+t[0]-373897302|0)<<20|n>>>12)+o|0,n=((n+=((o=((o+=((i=((i+=((s=((s+=(n&i|o&~i)+t[5]-701558691|0)<<5|s>>>27)+n|0)&o|n&~o)+t[10]+38016083|0)<<9|i>>>23)+s|0)&n|s&~n)+t[15]-660478335|0)<<14|o>>>18)+i|0)&s|i&~s)+t[4]-405537848|0)<<20|n>>>12)+o|0,n=((n+=((o=((o+=((i=((i+=((s=((s+=(n&i|o&~i)+t[9]+568446438|0)<<5|s>>>27)+n|0)&o|n&~o)+t[14]-1019803690|0)<<9|i>>>23)+s|0)&n|s&~n)+t[3]-187363961|0)<<14|o>>>18)+i|0)&s|i&~s)+t[8]+1163531501|0)<<20|n>>>12)+o|0,n=((n+=((o=((o+=((i=((i+=((s=((s+=(n&i|o&~i)+t[13]-1444681467|0)<<5|s>>>27)+n|0)&o|n&~o)+t[2]-51403784|0)<<9|i>>>23)+s|0)&n|s&~n)+t[7]+1735328473|0)<<14|o>>>18)+i|0)&s|i&~s)+t[12]-1926607734|0)<<20|n>>>12)+o|0,n=((n+=((o=((o+=((i=((i+=((s=((s+=(n^o^i)+t[5]-378558|0)<<4|s>>>28)+n|0)^n^o)+t[8]-2022574463|0)<<11|i>>>21)+s|0)^s^n)+t[11]+1839030562|0)<<16|o>>>16)+i|0)^i^s)+t[14]-35309556|0)<<23|n>>>9)+o|0,n=((n+=((o=((o+=((i=((i+=((s=((s+=(n^o^i)+t[1]-1530992060|0)<<4|s>>>28)+n|0)^n^o)+t[4]+1272893353|0)<<11|i>>>21)+s|0)^s^n)+t[7]-155497632|0)<<16|o>>>16)+i|0)^i^s)+t[10]-1094730640|0)<<23|n>>>9)+o|0,n=((n+=((o=((o+=((i=((i+=((s=((s+=(n^o^i)+t[13]+681279174|0)<<4|s>>>28)+n|0)^n^o)+t[0]-358537222|0)<<11|i>>>21)+s|0)^s^n)+t[3]-722521979|0)<<16|o>>>16)+i|0)^i^s)+t[6]+76029189|0)<<23|n>>>9)+o|0,n=((n+=((o=((o+=((i=((i+=((s=((s+=(n^o^i)+t[9]-640364487|0)<<4|s>>>28)+n|0)^n^o)+t[12]-421815835|0)<<11|i>>>21)+s|0)^s^n)+t[15]+530742520|0)<<16|o>>>16)+i|0)^i^s)+t[2]-995338651|0)<<23|n>>>9)+o|0,n=((n+=((i=((i+=(n^((s=((s+=(o^(n|~i))+t[0]-198630844|0)<<6|s>>>26)+n|0)|~o))+t[7]+1126891415|0)<<10|i>>>22)+s|0)^((o=((o+=(s^(i|~n))+t[14]-1416354905|0)<<15|o>>>17)+i|0)|~s))+t[5]-57434055|0)<<21|n>>>11)+o|0,n=((n+=((i=((i+=(n^((s=((s+=(o^(n|~i))+t[12]+1700485571|0)<<6|s>>>26)+n|0)|~o))+t[3]-1894986606|0)<<10|i>>>22)+s|0)^((o=((o+=(s^(i|~n))+t[10]-1051523|0)<<15|o>>>17)+i|0)|~s))+t[1]-2054922799|0)<<21|n>>>11)+o|0,n=((n+=((i=((i+=(n^((s=((s+=(o^(n|~i))+t[8]+1873313359|0)<<6|s>>>26)+n|0)|~o))+t[15]-30611744|0)<<10|i>>>22)+s|0)^((o=((o+=(s^(i|~n))+t[6]-1560198380|0)<<15|o>>>17)+i|0)|~s))+t[13]+1309151649|0)<<21|n>>>11)+o|0,n=((n+=((i=((i+=(n^((s=((s+=(o^(n|~i))+t[4]-145523070|0)<<6|s>>>26)+n|0)|~o))+t[11]-1120210379|0)<<10|i>>>22)+s|0)^((o=((o+=(s^(i|~n))+t[2]+718787259|0)<<15|o>>>17)+i|0)|~s))+t[9]-343485551|0)<<21|n>>>11)+o|0,e[0]=s+e[0]|0,e[1]=n+e[1]|0,e[2]=o+e[2]|0,e[3]=i+e[3]|0}function n(e){var t,s=[];for(t=0;t<64;t+=4)s[t>>2]=e.charCodeAt(t)+(e.charCodeAt(t+1)<<8)+(e.charCodeAt(t+2)<<16)+(e.charCodeAt(t+3)<<24);return s}function o(e){var t,s=[];for(t=0;t<64;t+=4)s[t>>2]=e[t]+(e[t+1]<<8)+(e[t+2]<<16)+(e[t+3]<<24);return s}function i(e){var t,o,i,r,a,c,u=e.length,l=[1732584193,-271733879,-1732584194,271733878];for(t=64;t<=u;t+=64)s(l,n(e.substring(t-64,t)));for(o=(e=e.substring(t-64)).length,i=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],t=0;t<o;t+=1)i[t>>2]|=e.charCodeAt(t)<<(t%4<<3);if(i[t>>2]|=128<<(t%4<<3),t>55)for(s(l,i),t=0;t<16;t+=1)i[t]=0;return r=(r=8*u).toString(16).match(/(.*?)(.{0,8})$/),a=parseInt(r[2],16),c=parseInt(r[1],16)||0,i[14]=a,i[15]=c,s(l,i),l}function r(e){var t,n,i,r,a,c,u=e.length,l=[1732584193,-271733879,-1732584194,271733878];for(t=64;t<=u;t+=64)s(l,o(e.subarray(t-64,t)));for(n=(e=t-64<u?e.subarray(t-64):new Uint8Array(0)).length,i=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],t=0;t<n;t+=1)i[t>>2]|=e[t]<<(t%4<<3);if(i[t>>2]|=128<<(t%4<<3),t>55)for(s(l,i),t=0;t<16;t+=1)i[t]=0;return r=(r=8*u).toString(16).match(/(.*?)(.{0,8})$/),a=parseInt(r[2],16),c=parseInt(r[1],16)||0,i[14]=a,i[15]=c,s(l,i),l}function a(e){var s,n="";for(s=0;s<4;s+=1)n+=t[e>>8*s+4&15]+t[e>>8*s&15];return n}function c(e){var t;for(t=0;t<e.length;t+=1)e[t]=a(e[t]);return e.join("")}function u(e){return/[\u0080-\uFFFF]/.test(e)&&(e=unescape(encodeURIComponent(e))),e}function l(e,t){var s,n=e.length,o=new ArrayBuffer(n),i=new Uint8Array(o);for(s=0;s<n;s+=1)i[s]=e.charCodeAt(s);return t?i:o}function d(e){return String.fromCharCode.apply(null,new Uint8Array(e))}function h(e,t,s){var n=new Uint8Array(e.byteLength+t.byteLength);return n.set(new Uint8Array(e)),n.set(new Uint8Array(t),e.byteLength),n}function g(e){var t,s=[],n=e.length;for(t=0;t<n-1;t+=2)s.push(parseInt(e.substr(t,2),16));return String.fromCharCode.apply(String,s)}function p(){this.reset()}return c(i("hello")),"undefined"==typeof ArrayBuffer||ArrayBuffer.prototype.slice||function(){function t(e,t){return(e=0|e||0)<0?Math.max(e+t,0):Math.min(e,t)}ArrayBuffer.prototype.slice=function(s,n){var o,i,r,a,c=this.byteLength,u=t(s,c),l=c;return n!==e&&(l=t(n,c)),u>l?new ArrayBuffer(0):(o=l-u,i=new ArrayBuffer(o),r=new Uint8Array(i),a=new Uint8Array(this,u,o),r.set(a),i)}}(),p.prototype.append=function(e){return this.appendBinary(u(e)),this},p.prototype.appendBinary=function(e){this._buff+=e,this._length+=e.length;var t,o=this._buff.length;for(t=64;t<=o;t+=64)s(this._hash,n(this._buff.substring(t-64,t)));return this._buff=this._buff.substring(t-64),this},p.prototype.end=function(e){var t,s,n=this._buff,o=n.length,i=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0];for(t=0;t<o;t+=1)i[t>>2]|=n.charCodeAt(t)<<(t%4<<3);return this._finish(i,o),s=c(this._hash),e&&(s=g(s)),this.reset(),s},p.prototype.reset=function(){return this._buff="",this._length=0,this._hash=[1732584193,-271733879,-1732584194,271733878],this},p.prototype.getState=function(){return{buff:this._buff,length:this._length,hash:this._hash.slice()}},p.prototype.setState=function(e){return this._buff=e.buff,this._length=e.length,this._hash=e.hash,this},p.prototype.destroy=function(){delete this._hash,delete this._buff,delete this._length},p.prototype._finish=function(e,t){var n,o,i,r=t;if(e[r>>2]|=128<<(r%4<<3),r>55)for(s(this._hash,e),r=0;r<16;r+=1)e[r]=0;n=(n=8*this._length).toString(16).match(/(.*?)(.{0,8})$/),o=parseInt(n[2],16),i=parseInt(n[1],16)||0,e[14]=o,e[15]=i,s(this._hash,e)},p.hash=function(e,t){return p.hashBinary(u(e),t)},p.hashBinary=function(e,t){var s=c(i(e));return t?g(s):s},p.ArrayBuffer=function(){this.reset()},p.ArrayBuffer.prototype.append=function(e){var t,n=h(this._buff.buffer,e),i=n.length;for(this._length+=e.byteLength,t=64;t<=i;t+=64)s(this._hash,o(n.subarray(t-64,t)));return this._buff=t-64<i?new Uint8Array(n.buffer.slice(t-64)):new Uint8Array(0),this},p.ArrayBuffer.prototype.end=function(e){var t,s,n=this._buff,o=n.length,i=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0];for(t=0;t<o;t+=1)i[t>>2]|=n[t]<<(t%4<<3);return this._finish(i,o),s=c(this._hash),e&&(s=g(s)),this.reset(),s},p.ArrayBuffer.prototype.reset=function(){return this._buff=new Uint8Array(0),this._length=0,this._hash=[1732584193,-271733879,-1732584194,271733878],this},p.ArrayBuffer.prototype.getState=function(){var e=p.prototype.getState.call(this);return e.buff=d(e.buff),e},p.ArrayBuffer.prototype.setState=function(e){return e.buff=l(e.buff,!0),p.prototype.setState.call(this,e)},p.ArrayBuffer.prototype.destroy=p.prototype.destroy,p.ArrayBuffer.prototype._finish=p.prototype._finish,p.ArrayBuffer.hash=function(e,t){var s=c(r(new Uint8Array(e)));return t?g(s):s},p}()}(hr)),hr.exports),pr=Yt(gr);var _r=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?Bi:xi,null===(t=this.httpRequest)||void 0===t||t.init(e)}uploadToCOS(e){return de(this,void 0,void 0,function*(){const t=`${tr} uploadToCOS`,{ssoLog:s,utils:{safeStringify:n}}=this._core,{file:o}=e;this.uploadFileType=e.uploadFileType,s.debug("uploadToCOS",`${t} options:${n(e)}`);try{const n=Date.now(),i=yield this._createCosOptions(e),r=i.fileExistsInCOS?{data:{location:i.downloadUrl}}:yield this._uploadFile(i);this._handleUploadError(r,e);const a=this._createUploadResult(o,r),c=Date.now()-n,u=zi(o.size),l=`size:${u} time:${c}ms speed:${Ji(1e3*o.size/c)}`;return s.debug("uploadToCOS",`${t} ok. name:${o.name} ${l}`),{uploadOptions:i,response:a}}catch(e){throw s.warn("uploadToCOS",`${t} failed, error:${n(e)}`),e}})}_handleUploadError(e,t){var s,n;const{ChatError:o}=null===(s=this._core)||void 0===s?void 0:s.helper;if(403===e.statusCode)throw t.url,(null===(n=null==e?void 0:e.data)||void 0===n?void 0:n.uploadIP)&&e.data.uploadIP,new o({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:Hi(Date.now(),!1),uploadSpeed:Ji(1e3*e.size/Hi(Date.now(),!1))}}_createCosOptions(e){return de(this,void 0,void 0,function*(){const{fileName:t,resources:s,uploadMethod:n}=yield this._prepareUploadParams(e),o=this._isC2CConversation(e.message.conversationID)?1:2;try{const i=yield this._fetchCosSignatureUrl({fileType:this.uploadFileType,fileName:t,uploadMethod:n,duration:this.duration,userID:e.message.from,conversationType:o}),{uploadUrl:r,downloadUrl:a,requestSnapshotUrl:c,thumbUrl:u,largeUrl:l,fileKey:d,existFlag:h}=i,g=!dr.isPrivateNetWork()&&i.uploadIP;return{url:this._getRawOrUploadProxyUrl(r),fileType:this.uploadFileType,fileName:t,resources:s,downloadUrl:a,requestSnapshotUrl:c,thumbUrl:u,largeUrl:l,fileKey:d,uploadIP:g||"",fileExistsInCOS:1===h,onProgress:t=>this._handleUploadProgress(t,e)}}catch(e){throw console.error("Failed to create COS pre-signed URL options:",e),e}})}_prepareUploadParams(e){return de(this,void 0,void 0,function*(){const{ssoLog:t,utils:{safeStringify:s,isEmpty:n}}=this._core;t.debug("_prepareUploadParams",` prepareUploadParams:${s(e)}`);const{file:o}=e,{IN_MINI_APP:i,IN_RN_APP:r}=dr.getPlatformFlags(),a=i||r,c=a&&e.message.type!==Zi,{name:u}=o,l=u.slice(u.lastIndexOf(".")),d=`${Ki(999999)}${l}`,h=c?o.name:d,g=yield this._generateHashFileName(o);return{fileName:n(g)?Wi(h):`${g}${l}`,resources:a?o.url:o,uploadMethod:a?1:0}})}_generateHashFileName(e){return de(this,void 0,void 0,function*(){const{utils:{IN_MINI_APP:t,IN_BROWSER:s,IN_UNI_NATIVE_APP:n,isArray:o},ssoLog:i}=this._core,r=Date.now();let a="";return s&&(a=yield this._generateHashFileNameInWeb(e)),t&&(o(e.tempFiles)&&(e=e.tempFiles[0]),n||(a=yield this._generateFileNameInMiniProgram(e)),n&&(a=yield this._generateFileNameInUNINativeApp(e))),i.info("_generateHashFileName",`hashFileName:${a} costTime:${Date.now()-r}`),a})}_generateHashFileNameInWeb(e){return de(this,void 0,void 0,function*(){const{ssoLog:t,utils:{safeStringify:s}}=this._core;let n="";try{n=yield new Promise((s,n)=>{const o=File.prototype.slice||File.prototype.mozSlice||File.prototype.webkitSlice;o||(t.warn("_generateHashFileNameInWeb","Browser does not support file slicing"),s(""));const i=10485760,r=Math.ceil(e.size/i);let a=0;const c=new pr.ArrayBuffer,u=new FileReader,l=setTimeout(()=>{u.abort(),t.warn("_generateHashFileNameInWeb","File hash generation timeout"),s("")},2e3);function d(){const t=a*i,s=t+i>=e.size?e.size:t+i;u.readAsArrayBuffer(o.call(e,t,s))}u.onload=e=>{t.debug("_generateHashFileNameInWeb",`read chunk nr ${a+1} of ${r}`),c.append(e.target.result),a++,a<r?d():(t.debug("_generateHashFileNameInWeb","finished loading"),clearTimeout(l),s(c.end()))},u.onerror=e=>{clearTimeout(l),n(e)},d()})}catch(e){t.warn("_generateHashFileNameInWeb",s(e))}return n})}_generateFileNameInMiniProgram(e){return de(this,void 0,void 0,function*(){const{utils:{MINI_APP_NAMESPACE:t,safeStringify:s,isEmpty:n},ssoLog:o}=this._core;let i="";if(n(e.url))return o.warn("_generateFileNameInMiniProgram","file.url is empty"),i;if("function"!=typeof(null==t?void 0:t.getFileSystemManager))return o.warn("_generateFileNameInUNINativeApp","getFileSystemManager is not a function"),i;try{i=yield new Promise((s,n)=>{t.getFileSystemManager().getFileInfo({filePath:e.url,success:e=>{s(e.digest)},fail:e=>{n(e)}})})}catch(e){o.warn("_generateFileNameInMiniProgram",s(e))}return i})}_generateFileNameInUNINativeApp(e){return de(this,void 0,void 0,function*(){var t;const{utils:{safeStringify:s,isEmpty:n},ssoLog:o}=this._core;let i="";if(n(e.url))return o.warn("_generateFileNameInUNINativeApp","file.url is empty"),i;if("function"!=typeof(null===(t=null===plus||void 0===plus?void 0:plus.io)||void 0===t?void 0:t.getFileInfo))return o.warn("_generateFileNameInUNINativeApp","plus.io.getFileInfo is not a function"),i;try{i=yield new Promise((t,s)=>{plus.io.getFileInfo({filePath:e.url,success:e=>{t(e.digest)},fail:e=>{s(e)}})})}catch(e){o.warn("_generateFileNameInMiniProgram",s(e))}return i})}_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 de(this,void 0,void 0,function*(){const{ssoLog:t,utils:{safeStringify:s}}=this._core,n=dr.isSimpleCos(),o=this._prepareCosRequestData(e),i=n?"im_cos_msg.simple_sig":"im_cos_msg.pre_sig";try{const e=yield function(e,t,s){return de(this,void 0,void 0,function*(){try{const{helper:n,channel:o}=s,i=n.generateCosSpecifiedData({servcmd:e,data:t}),r=`${i.head.seq}${e}`;return yield o.sendPacket(i,{requestId:r})}catch(e){throw console.warn("getCosSig error:",e),e}})}(i,o,this._core);this.fetchCosTryCount=0;const r=this._processResponse(e);return t.debug("_fetchCosSignatureUrl",` ok. isSimpleCos:${n} data:${s(r)}`),r||{}}catch(t){if(this.fetchCosTryCount<1)return this.fetchCosTryCount++,this._fetchCosSignatureUrl(e);throw this.fetchCosTryCount=0,t}})}_processResponse(e){var t;const s=dr.isSimpleCos(),n=s?null===(t=null==e?void 0:e.rpt_pre_sig)||void 0===t?void 0:t[0]:e;if(!n)return{};if(s){const{str_final_ip:e,rpt_pre_sig:t,uint32_file_id:s,uint32_exist_flag:o,str_download_url:i,str_upload_url:r,str_snapshot_url:a,str_file_key:c}=n;return{uploadIP:e,preSig:t,fileID:s,existFlag:o,downloadUrl:i,uploadUrl:r,requestSnapshotUrl:a,fileKey:c}}const{upload_url:o,download_url:i,snapshot_url:r,thumb_url:a,large_url:c,file_key:u}=n;return{uploadUrl:o,downloadUrl:i,requestSnapshotUrl:r,thumbUrl:a,largeUrl:c,fileKey:u}}_prepareCosRequestData(e){return dr.isSimpleCos()?{uint32_upload_method:e.uploadMethod,uint32_platform:dr.getPlatform(),uint32_sdkappid:dr.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 de(this,void 0,void 0,function*(){return new Promise((t,s)=>{this.httpRequest.request(e,(n,o)=>{n&&this.uploadFileTryCount<this.maxRetries&&this.shouldRetry(n)?(this.uploadFileTryCount++,this._uploadFile(e).then(t).catch(s)):(this.uploadFileTryCount=0,n?s(n):t(o))})})})}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 n=null===(t=e.error)||void 0===t?void 0:t.Code,o=null===(s=e.error)||void 0===s?void 0:s.Message;return"RequestTimeTooSkewed"===n||"AccessDenied"===n&&"Request has expired"===o}catch(e){return!1}}_isClockOutOfSync(e){var t,s,n;const o=(null===(t=e.headers)||void 0===t?void 0:t.date)||(null===(s=e.headers)||void 0===s?void 0:s.Date)||(null===(n=e.error)||void 0===n?void 0:n.ServerTime);if(!o)return!1;const i=Date.now(),r=Date.parse(o);return Math.abs(i+this.systemClockOffset-r)>=3e4}_syncSystemClock(e){var t,s,n;const o=(null===(t=e.headers)||void 0===t?void 0:t.date)||(null===(s=e.headers)||void 0===s?void 0:s.Date)||(null===(n=e.error)||void 0===n?void 0:n.ServerTime);if(o){const e=Date.now(),t=Date.parse(o);this.systemClockOffset=t-e}}_getRawOrUploadProxyUrl(e){const t=dr.getFileUploadProxy();let s=e;return t&&(s=e.replace(/^https:\/\/[^/]+/,t)),s}_isC2CConversation(e){return"C2C"===e.slice(0,3)}};const mr=2108,vr=2251,fr=2252,Ir=["jpg","jpeg","gif","png","bmp","image","webp"],Er=20971520,Sr={JPG:1,JPEG:1,GIF:2,PNG:3,BMP:4,UNKNOWN:255};class Cr{constructor(e,t){this.instanceID=Ki(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=dr.addAuthToUrl(e.imageUrl||e.url||""),this.url=dr.addAuthToUrl(e.url||t)}setSizeType(e){this.sizeType=e}setType(e){this.type=e}setImageUrl(e){e&&(this.imageUrl=dr.addAuthToUrl(e))}getImageUrl(){return this.imageUrl}}function Mr(e){const{originUrl:t,originWidth:s,originHeight:n,min:o=198}=e,i=parseInt(s)||0,r=parseInt(n)||0,a={url:void 0,width:0,height:0};if((i<=r?i:r)<=o)a.url=t,a.width=i,a.height=r;else{r<=i?(a.width=Math.ceil(i*o/r),a.height=o):(a.width=o,a.height=Math.ceil(r*o/i));const e=t&&t.indexOf("?")>-1?`${t}&`:`${t}?`;a.url=198===o?`${e}imageView2/3/w/198/h/198`:`${e}imageView2/3/w/720/h/720`}if(void 0===t){const{url:e}=a;return le(a,["url"])}return a}class yr{constructor(e){this._imageMemoryURL="",this._percent=0,this.type=Qi;const{uuid:t,file:s,imageFormat:n,imageInfoArray:o=[],isCustomUpload:i=!1}=e;this._imageMemoryURL=this.createImageDataAsURL(s),this.content={imageFormat:n,uuid:t,imageInfoArray:[]},this[ur]=i,this.initImageInfoArray(o),this.autoFixUrl()}static parseServerPushElement(e){const{MsgContent:t}=e,{ImageFormat:s,ImageInfoArray:n,UUID:o}=t,i=function(e){return e.map(e=>({size:e.Size,type:e.Type,width:e.Width,height:e.Height,url:e.URL}))}(n);return new yr({imageFormat:s,imageInfoArray:i,uuid:o})}createImageDataAsURL(e){let t="";const{IN_MINI_APP:s,IN_RN_APP:n,IN_BROWSER:o}=dr.getPlatformFlags();return e?((s||n)&&(t=e.url),o&&(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 n=e[s]||Object.assign({},t),o=new Cr(n,this._imageMemoryURL);o.setSizeType(s+1),o.setType(s),this.addImageInfo(o)}this.updateAccessSideImageInfoArray()}autoFixUrl(){const e=["http","https"];this.content.imageInfoArray.forEach(t=>{if(!t.url||""===t.imageUrl)return;const[s,...n]=t.imageUrl.split("://"),o=n.join("://");e.includes(s)||t.setImageUrl(`https://${o}`)})}updatePercent(e){this._percent=Math.min(e,1)}updateImageFormat(e){this.content.imageFormat=Sr[e.toUpperCase()]||Sr.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 n=0;n<t;n++)s=this.content.imageInfoArray[n],e[n].size&&(s.size=e[n].size),e[n].url&&s.setImageUrl(e[n].url),e[n].width&&(s.width=e[n].width),e[n].height&&(s.height=e[n].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],Mr({originWidth:e.width,originHeight:e.height,min:720})))}validateBeforeSend(){if(this[ur])return delete this[ur],{isValid:!0};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:n,imageFormat:o,imageInfoArray:i}=s;return{MsgType:this.type,MsgContent:{ImageFormat:o,ImageInfoArray:this.parseImageInfoArray(i),UUID:n}}}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:dr.removeAuthToUrl(e.imageUrl)}))}}var Or=new class{constructor(){this._messageOptionsMap=new Map}init(e){var t;this._core=e;const{notificationCenter:s,helper:n,InnerEvent:o,message:i}=e;n.registerApi({apiName:"createImageMessage",context:this}),n.registerExperimentalAPI("createImageMessage",this,"createCustomUploadImageMessage"),null===(t=null==i?void 0:i.messageFactory)||void 0===t||t.registerElementClass(Qi,yr),s.subscribeInnerEvent(o.DESTROY,this._dispose,this)}createImageMessage(e){var t,s,n;try{const o=null===(t=this._core.store.get("login"))||void 0===t?void 0:t.userId,i=null===(n=null===(s=this._core)||void 0===s?void 0:s.message.messageFactory)||void 0===n?void 0:n.createMessage(Object.assign(Object.assign({},e),{from:o})),r=this._processImage(e);e.payload.file=r;const a={imageFormat:Sr.UNKNOWN,uuid:dr.generateUUID(r),file:r,imageInfoArray:[]},c=new yr(a);return i.setElement(c),this._messageOptionsMap.set(i.clientSequence,e),i}catch(e){throw e}}createCustomUploadImageMessage(e){var t,s,n,o;const{store:i,utils:{isEmpty:r}}=this._core,a=null===(t=i.get("login"))||void 0===t?void 0:t.userId,c=null===(n=null===(s=this._core)||void 0===s?void 0:s.message.messageFactory)||void 0===n?void 0:n.createMessage(Object.assign(Object.assign({},e),{from:a})),{largeImageUuid:u,largeFileSize:l,largeImageWidth:d,largeImageHeight:h,largeImageUrl:g,originImageUuid:p,originFileSize:_,originImageWidth:m,originImageHeight:v,originImageUrl:f,thumbImageUuid:I,thumbFileSize:E,thumbImageWidth:S,thumbImageHeight:C,thumbImageUrl:M}=(null===(o=null==e?void 0:e.payload)||void 0===o?void 0:o.file)||{};if(r(f)||r(p))throw new Error("createImageMessageExperimental originImageUrl or originImageUuid is empty");const y=new yr({imageFormat:Sr.UNKNOWN,uuid:p,imageInfoArray:[{instanceID:p,size:_,width:m,height:v,imageUrl:f,url:f},{instanceID:u,size:l,width:d,height:h,imageUrl:g,url:g},{instanceID:I,size:E,width:S,height:C,imageUrl:M,url:M}],isCustomUpload:!0});return c.setElement(y),this._messageOptionsMap.set(c.clientSequence,e),c._skipUpload=!0,c}upload(e){return de(this,void 0,void 0,function*(){const t=e.getElements()[0],{file:s}=this._messageOptionsMap.get(e.clientSequence).payload;this._validateBeforeUploadImage(s);const n=yield this._performImageUpload(t,e,s),o=this._generateImageInfo(n);return t.updateImageFormat(null==n?void 0:n.fileType),t.updateImageInfoArray(o),e})}_performImageUpload(e,t,s){return de(this,void 0,void 0,function*(){const{to:n}=t,o={uploadFileType:nr,file:s,to:n,message:t,onProgress:s=>{var n,o;e.updatePercent(s),null===(o=null===(n=this._messageOptionsMap.get(t.clientSequence))||void 0===n?void 0:n.onProgress)||void 0===o||o.call(n,s)}},{uploadOptions:i,response:r}=yield _r.uploadToCOS(o);return this._parseResponse(i,r)})}_generateImageInfo(e){const{location:t,fileSize:s,width:n,height:o,smallImageUrl:i,smallImageWidth:r,smallImageHeight:a,largeImageUrl:c,largeImageWidth:u,largeImageHeight:l,imageInfoArray:d}=e,h=dr.addAuthToUrl(t),g={size:s,url:h,width:n,height:o};return(null==d?void 0:d.length)>0?this._processImageInfoArray(d,s):i&&c?[Object.assign({},g),{largeImageUrl:c,largeImageWidth:u,largeImageHeight:l},{smallImageUrl:i,smallImageWidth:r,smallImageHeight:a}]:[Object.assign({},g),this._generateThumbInfo(h,n,o,720),this._generateThumbInfo(h,n,o,198)]}_generateThumbInfo(e,t,s,n){return Mr({originUrl:e,originWidth:t,originHeight:s,min:n})}_processImageInfoArray(e,t){let s,n,o;for(const i of e)1===i.type?(n=i,n.size=t):2===i.type?(o=i,o.size=t):(s=i,s.size=t);return[Object.assign({},s),Object.assign({},o),Object.assign({},n)]}_parseResponse(e,t){return de(this,void 0,void 0,function*(){try{const{thumbUrl:s,largeUrl:n,downloadUrl:o}=e;s&&n&&(yield this._getImageInfoByUrl(s,t,"thumb"),yield this._getImageInfoByUrl(n,t,"large"));if(dr.isSimpleCos()&&!dr.isPrivateNetWork()&&(yield this._getImageInfoArray(o,t),null==t?void 0:t.uploadIP)){const e=this._extractDomainFromUrl(o);e&&(yield this._getDownloadIP(e,t))}return t}catch(e){throw e}})}_extractDomainFromUrl(e){var t;try{const t=e.match(/:\/\/([^\/]+)/);return t?t[1]:null}catch(e){return null===(t=this._core)||void 0===t||t.ssoLog.warn("_extractDomainFromUrl",`Failed to extract domain from URL:${e.message}`),null}}_getImageInfoByUrl(e,t,s){return de(this,void 0,void 0,function*(){var n;try{const n=dr.addAuthToUrl(e),{width:o=0,height:i=0}=yield dr.probeImageWidthHeight(n);t.width=o,t.height=i,"thumb"===s?(t.smallImageUrl=e,t.smallImageWidth=o,t.smallImageHeight=i):(t.largeImageUrl=e,t.largeImageWidth=o,t.largeImageHeight=i)}catch(e){null===(n=this._core)||void 0===n||n.ssoLog.warn("_getImageInfoByUrl",`Failed to get ${s} image info:${e.message}`)}})}_validateBeforeUploadImage(e){var t;const{ChatError:s}=null===(t=this._core)||void 0===t?void 0:t.helper;if(!e)throw new s({code:vr});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:n}=e.payload;return n=s?this._processMiniAppImageFile(n):this._processWebImageFile(n),n}catch(e){throw e}}_processMiniAppImageFile(e){ji(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,n=dr.extractFileFromInput(e);if(!n)throw new s({message:"Invalid file. Pass either `e.target` (from file input) or a File object"});return n}_getDownloadIP(e,t){return de(this,void 0,void 0,function*(){const s=`${tr} getDownloadIP domainName: ${e}`;try{const n=yield function(e,t){return de(this,void 0,void 0,function*(){try{const{helper:s,channel:n}=t,o="im_cos_msg.get_final_ip",i={str_domain:e},r=s.generateProtocolData({servcmd:o,data:i}),a=`${r.head.seq}${o}`;return yield n.sendPacket(r,{requestId:a})}catch(e){throw console.warn("getFinalIP error:",e),e}})}(e,this._core);if(!n||!n.str_final_ip)return;console.log(`${s} ok. downloadIP:${n}`);const o=t.location.split("/");o[0]=n.str_final_ip,t.location=o.join("/")}catch(e){console.warn(e)}})}_getImageInfoArray(e,t){return de(this,void 0,void 0,function*(){try{const s=yield function(e,t){return de(this,void 0,void 0,function*(){try{const{helper:s,channel:n}=t,o="im_cos_msg.get_imageinfo",i={str_image_url:e},r=s.generateProtocolData({servcmd:o,data:i}),a=`${r.head.seq}${o}`;return yield n.sendPacket(r,{requestId:a})}catch(e){throw console.warn("getImageInfo error:",e),e}})}(e,this._core);return t.imageInfoArray=this._processImageInfoResponse(s),t}catch(e){throw t.imageInfoArray=void 0,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 n="";if(t.IN_MINI_APP&&(n=e.url.slice(e.url.lastIndexOf(".")+1)),t.IN_BROWSER&&(n=e.name.slice(e.name.lastIndexOf(".")+1)),Ir.indexOf(n.toLowerCase())<0)throw new s.ChatError({code:fr})}_checkImageSize(e){const{utils:t,helper:s}=this._core;let n=0;if(n=(t.IN_MINI_APP,e.size),0===n)throw new s.ChatError({code:mr});if(n>=Er)throw new s.ChatError({message:`File size exceeds limit: ${zi(Er)}`})}_reset(){this._messageOptionsMap.clear()}_dispose(){this._reset();const{notificationCenter:e,InnerEvent:t}=this._core;e.unSubscribeInnerEvent(t.DESTROY,this._dispose,this)}};const Ar=2108,Tr=2401,Rr="2.5.0",Dr="1.18.0",br=104857600;function Nr(e,t){const s=e.split("."),n=t.split("."),o=Math.max(s.length,n.length);for(;s.length<o;)s.push("0");for(;n.length<o;)n.push("0");for(let e=0;e<o;e++){const t=parseInt(s[e]),o=parseInt(n[e]);if(t>o)return 1;if(t<o)return-1}return 0}const Lr=new class{init(e){this.core=e}};var Pr;class wr{constructor(e){this.type=Zi,this.uploadProgress=0,this[Pr]=!1;const t=this._getFileInfo(e);this[ur]=e.isCustomUpload||!1,this.content={downloadFlag:2,fileUrl:dr.generateURL(e.url||e.fileUrl,{needAddAuthToUrl:!this[ur]})||"",uuid:e.uuid,fileName:t.name||"",fileSize:t.size||0}}static parseServerPushElement(e){const{MsgContent:t}=e,{Download_Flag:s,Url:n,FileName:o,FileSize:i,UUID:r}=t;return new wr({downloadFlag:s,url:n,fileName:o,fileSize:i,uuid:r})}updatePercent(e){this.uploadProgress=Math.min(e,1)}updateFileUrl(e){this.content.fileUrl=e}validateBeforeSend(){if(this[ur])return{isValid:!0};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:n,downloadFlag:o,fileUrl:i,fileName:r,fileSize:a}=s;return{MsgType:this.type,MsgContent:{Download_Flag:o,Url:dr.removeAuthToUrl(i),FileName:r,FileSize:a,UUID:n}}}_getFileInfo(e){const{utils:{IN_UNI_NATIVE_APP:t}}=Lr.core;if(e.fileName&&e.fileSize)return{size:e.fileSize,name:e.fileName};const{file:s}=e;return s?(t&&this._processNativeAppFile(s),{size:s.size,name:s.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=`${Ki(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)}}Pr=ur;var Gr=new class{constructor(){this._messageOptionsMap=new Map}init(e){var t;this._core=e;const{notificationCenter:s,helper:n,InnerEvent:o,message:i}=e;n.registerApi({apiName:"createFileMessage",context:this}),n.registerExperimentalAPI("createFileMessage",this,"createCustomUploadFileMessage"),null===(t=null==i?void 0:i.messageFactory)||void 0===t||t.registerElementClass(Zi,wr),s.subscribeInnerEvent(o.DESTROY,this._dispose,this)}createFileMessage(e){var t,s,n;try{this._checkVersion();const o=this._processFile(e.payload.file);e.payload.file=o;const i=null===(t=this._core.store.get("login"))||void 0===t?void 0:t.userId,r=null===(n=null===(s=this._core)||void 0===s?void 0:s.message.messageFactory)||void 0===n?void 0:n.createMessage(Object.assign(Object.assign({},e),{from:i})),a={uuid:dr.generateUUID(o),file:o},c=new wr(a);return r.setElement(c),this._messageOptionsMap.set(r.clientSequence,e),r}catch(e){throw e}}createCustomUploadFileMessage(e){var t,s,n;try{const{store:o,message:i,utils:{isEmpty:r}}=this._core,a=null===(t=o.get("login"))||void 0===t?void 0:t.userId,{url:c,uuid:u,fileSize:l,fileName:d=""}=(null===(s=null==e?void 0:e.payload)||void 0===s?void 0:s.file)||{};if(r(c))throw new Error("url is required");const h=null===(n=i.messageFactory)||void 0===n?void 0:n.createMessage(Object.assign(Object.assign({},e),{from:a})),g=new wr({url:c,uuid:u,file:{size:l,name:d},isCustomUpload:!0});return h.setElement(g),h}catch(e){throw e}}upload(e){return de(this,void 0,void 0,function*(){const{file:t}=this._messageOptionsMap.get(e.clientSequence).payload;this._validateBeforeUploadFile(t);const s=e.getElements()[0],n=yield this._performFileUpload(s,e,t),o=dr.addAuthToUrl(null==n?void 0:n.location);return s.updateFileUrl(o),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:Tr});if(e.size>br)throw new s({message:`File size exceeds limit: ${zi(br)}`});if(0===e.size)throw new s({code:Ar})}_performFileUpload(e,t,s){return de(this,void 0,void 0,function*(){const{to:n}=t,o={uploadFileType:rr,file:s,to:n,message:t,onProgress:s=>{var n,o;e.updatePercent(s),null===(o=null===(n=this._messageOptionsMap.get(t.clientSequence))||void 0===n?void 0:n.onProgress)||void 0===o||o.call(n,s)}},{response:i}=yield _r.uploadToCOS(o);return i})}_processFile(e){var t,s;const{IN_BROWSER:n,IN_RN_APP:o,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(n||a){const t=dr.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 o?Object.assign(Object.assign({},e),{url:e.uri}):e}_checkVersion(){var e,t;const{MINI_APP_NAMESPACE:s,IN_MINI_APP:n,IN_WX_MINI_APP:o,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(n){if(!(o||i||r))throw new a({message:"Unsupported mini app environment"});const e=s.getSystemInfoSync().SDKVersion;if(o&&Nr(e,Rr)<0){throw new a({message:`WXChooseMessageFile requires SDK version ${Rr} or higher`})}if(i&&Nr(e,Dr)<0){throw new a({message:`QQChooseMessageFile requires SDK version ${Dr} or higher`})}}}_reset(){this._messageOptionsMap.clear()}_dispose(){this._reset();const{notificationCenter:e,InnerEvent:t}=this._core;e.unSubscribeInnerEvent(t.DESTROY,this._dispose,this)}};const Ur=2108,kr=2352,Fr=["mp4","quicktime","mov"],$r=104857600;var qr;class xr{constructor(e){this.type=er,this.uploadProgress=0,this[qr]=!1;const t="number"==typeof(null==e?void 0:e.videoSecond)?null==e?void 0:e.videoSecond:0;this[ur]=e.isCustomUpload||!1,this.content={remoteVideoUrl:dr.addAuthToUrl(e.remoteVideoUrl||e.videoUrl||""),videoFormat:e.videoFormat,videoSecond:parseInt(null==t?void 0:t.toString(),10),videoSize:e.videoSize,videoUrl:dr.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:dr.addAuthToUrl(e.thumbUrl),snapshotUrl:dr.addAuthToUrl(e.thumbUrl)}}static parseServerPushElement(e){const{MsgContent:t}=e,{VideoUrl:s,VideoFormat:n,VideoSecond:o,VideoSize:i,VideoDownloadFlag:r,VideoUUID:a,ThumbUUID:c,ThumbFormat:u,ThumbWidth:l,SnapshotWidth:d,ThumbHeight:h,SnapshotHeight:g,ThumbSize:p,SnapshotSize:_,ThumbDownloadFlag:m,ThumbUrl:v,SnapshotUrl:f}=t;return new xr({videoUrl:s,videoFormat:n,videoSecond:o,videoSize:i,videoDownloadFlag:r,videoUUID:a,thumbUUID:c,thumbFormat:u,thumbWidth:l,snapshotWidth:d,thumbHeight:h,snapshotHeight:g,thumbSize:p,snapshotSize:_,thumbDownloadFlag:m,thumbUrl:v,snapshotUrl:f})}updatePercent(e){this.uploadProgress=Math.min(e,1)}updateVideoUrl(e){e&&(this.content.remoteVideoUrl=e)}updateSnapshotInfo(e){const{snapshotUrl:t,snapshotWidth:s,snapshotHeight:n}=e;dr.isEmpty(t)||(this.content.thumbUrl=this.content.snapshotUrl=t),dr.isEmpty(s)||(this.content.thumbWidth=this.content.snapshotWidth=Number(s)),dr.isEmpty(n)||(this.content.thumbHeight=this.content.snapshotHeight=Number(n))}validateBeforeSend(){if(this[ur])return{isValid:!0};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:n,videoFormat:o,videoSecond:i,videoSize:r,videoDownloadFlag:a,videoUUID:c,thumbUUID:u,thumbFormat:l,thumbWidth:d,snapshotWidth:h,thumbHeight:g,snapshotHeight:p,thumbSize:_,snapshotSize:m,thumbDownloadFlag:v,thumbUrl:f,snapshotUrl:I}=s;return{MsgType:this.type,MsgContent:{VideoUrl:dr.removeAuthToUrl(n),VideoFormat:o,VideoSecond:i,VideoSize:r,VideoDownloadFlag:a,VideoUUID:c,ThumbUUID:u,ThumbFormat:l,ThumbWidth:d,SnapshotWidth:h,ThumbHeight:g,SnapshotHeight:p,ThumbSize:_,SnapshotSize:m,ThumbDownloadFlag:v,ThumbUrl:dr.removeAuthToUrl(f),SnapshotUrl:dr.removeAuthToUrl(I)}}}}qr=ur;var Vr,Br=new class{constructor(){this._messageOptionsMap=new Map}init(e){var t;this._core=e;const{notificationCenter:s,helper:n,InnerEvent:o,message:i}=e;n.registerApi({apiName:"createVideoMessage",context:this}),n.registerExperimentalAPI("createVideoMessage",this,"createCustomUploadVideoMessage"),null===(t=null==i?void 0:i.messageFactory)||void 0===t||t.registerElementClass(er,xr),s.subscribeInnerEvent(o.DESTROY,this._dispose,this)}createVideoMessage(e){var t,s,n;try{const o=this._processVideo(e);e.payload.file=o;const i=null===(t=this._core.store.get("login"))||void 0===t?void 0:t.userId,r=null===(n=null===(s=this._core)||void 0===s?void 0:s.message.messageFactory)||void 0===n?void 0:n.createMessage(Object.assign(Object.assign({},e),{from:i})),a={videoFormat:o.videoFile.type,videoSecond:Yi(o.videoFile.second,0),videoSize:o.videoFile.size,remoteVideoUrl:"",videoUrl:o.videoFile.url,videoUUID:dr.generateUUID(o.videoFile),thumbUUID:dr.generateUUID(o.videoFile,"jpg"),thumbWidth:o.width||200,thumbHeight:o.height||200,thumbUrl:o.thumbUrl,thumbSize:o.thumbSize,thumbFormat:"jpg"},c=new xr(a);return r.setElement(c),this._messageOptionsMap.set(r.clientSequence,e),r}catch(e){throw e}}createCustomUploadVideoMessage(e){var t,s,n;try{const{store:o,message:i}=this._core;this._validateCustomUploadVideoMessage(e);const r=null===(t=o.get("login"))||void 0===t?void 0:t.userId,{videoUrl:a,videoUuid:c,duration:u,snapshotUrl:l,snapshotUuid:d,videoFileSize:h,videoType:g,snapshotWidth:p,snapshotHeight:_,snapshotFileSize:m,snapshotType:v="jpg"}=(null===(s=null==e?void 0:e.payload)||void 0===s?void 0:s.file)||{},f=null===(n=i.messageFactory)||void 0===n?void 0:n.createMessage(Object.assign(Object.assign({},e),{from:r})),I=new xr({videoFormat:g,videoSecond:u||0,videoSize:h,remoteVideoUrl:a,videoUrl:a,videoUUID:c,thumbUUID:d,thumbWidth:p||200,thumbHeight:_||200,thumbUrl:l,thumbSize:m,thumbFormat:v,isCustomUpload:!0});return f.setElement(I),this._messageOptionsMap.set(f.clientSequence,e),f}catch(e){throw e}}upload(e){return de(this,void 0,void 0,function*(){const t=e.getElements()[0],{file:s}=this._messageOptionsMap.get(e.clientSequence).payload;this._validateBeforeUploadVideo(s);const n=yield this._performVideoUpload(t,e,s),{location:o,snapshotInfo:i}=n,r=dr.addAuthToUrl(o);return t.updateVideoUrl(r),dr.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>$r)throw new s({message:`File size exceeds limit: ${zi($r)}`});if(0===e.videoFile.size)throw new s({code:Ur});if(-1===Fr.indexOf(e.videoFile.type))throw new s({code:kr})}_validateCustomUploadVideoMessage(e){var t;const{utils:{isEmpty:s,isNumber:n}}=this._core,{videoUrl:o,videoUuid:i,duration:r,snapshotUrl:a,snapshotUuid:c}=(null===(t=null==e?void 0:e.payload)||void 0===t?void 0:t.file)||{};if(s(o)||s(i)||!n(r)||s(a)||s(c))throw new Error("Invalid video message options: missing required fields (videoUrl, videoUuid, duration, snapshotUrl, snapshotUuid)")}_performVideoUpload(e,t,s){return de(this,void 0,void 0,function*(){const{to:n}=t,o={uploadFileType:or,file:s,to:n,message:t,onProgress:s=>{var n,o;e.updatePercent(s),null===(o=null===(n=this._messageOptionsMap.get(t.clientSequence))||void 0===n?void 0:n.onProgress)||void 0===o||o.call(n,s)}},{response:i,uploadOptions:r}=yield _r.uploadToCOS(o);return{snapshotInfo:yield this._getSnapshotInfoByUrl(r.requestSnapshotUrl),location:i.location}})}_processVideo(e){var t,s;try{const{ChatError:n}=null===(t=this._core)||void 0===t?void 0:t.helper,{IN_MINI_APP:o,IN_BROWSER:i}=null===(s=this._core)||void 0===s?void 0:s.utils;let{file:r}=e.payload,a={};if(o&&(a=this._processMiniVideoFile(r),r.name=a.name,r.url=a.url,r.type=a.type),i){const e=dr.extractFileFromInput(r);if(!e)throw new n({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(`${tr} _processFile error:`,e),e}}_processMiniVideoFile(e){var t,s;const{IN_ALIPAY_MINI_APP:n,IN_UNI_NATIVE_APP:o}=null===(t=this._core)||void 0===t?void 0:t.utils,{ChatError:i}=null===(s=this._core)||void 0===s?void 0:s.helper;if(n)throw new i({message:"VideoUnsupportedInAlipay"});if(ji(e))throw new i({message:"FileUnsupportedInMiniApp"});Array.isArray(e.tempFiles)&&(e=e.tempFiles[0]);let r=e.tempFilePath.slice(e.tempFilePath.lastIndexOf(".")+1).toLowerCase();return o&&(r=e.fileType||r),{url:e.tempFilePath,name:e.tempFilePath.slice(e.tempFilePath.lastIndexOf("/")+1),size:e.size||1,second:e.duration||0,type:r}}_processWebVideoFile(e){const{name:t,size:s=1,duration:n=0,type:o}=e,i=o.split("/")[1];return{url:window.URL.createObjectURL(e),name:t,size:s,second:n,type:i}}_getSnapshotInfoByUrl(e){return de(this,void 0,void 0,function*(){const{ssoLog:t}=this._core;try{t.debug("_getSnapshotInfoByUrl",`${tr} _getSnapshotInfoByUrl url:${e}`);const s={version:1,platform:dr.getPlatform(),cover_name:Wi(Ki(99999)),snapshot_url:e},n=yield function(e,t){return de(this,void 0,void 0,function*(){try{const s="im_cos_msg.video_cover",{helper:n,channel:o}=t,i=n.generateCosSpecifiedData({servcmd:s,data:e}),r=`${i.head.seq}${s}`;return yield o.sendPacket(i,{requestId:r})}catch(e){throw console.warn("getSnapshotInfo error:",e),e}})}(s,this._core),{download_url:o}=n||{};if(t.debug("_getSnapshotInfoByUrl",`${tr} _getSnapshotInfoByUrl OK snapshotUrl:${o}`),dr.isEmpty(o))return{};const i=dr.addAuthToUrl(o),{width:r=0,height:a=0}=yield dr.probeImageWidthHeight(i);return{snapshotUrl:i,snapshotWidth:r,snapshotHeight:a}}catch(e){throw e}})}_reset(){this._messageOptionsMap.clear()}_dispose(){this._reset();const{notificationCenter:e,InnerEvent:t}=this._core;e.unSubscribeInnerEvent(t.DESTROY,this._dispose,this)}};class jr{constructor(e){this.uploadProgress=0,this.type=Xi,this[Vr]=!1,this[ur]=e.isCustomUpload||!1,this.content={downloadFlag:2,second:e.second,size:e.size,url:dr.generateURL(e.url,{needAddAuthToUrl:!this[ur]}),remoteAudioUrl:dr.addAuthToUrl(e.url||""),uuid:e.uuid}}static parseServerPushElement(e){const{MsgContent:t}=e,{Url:s,Download_Flag:n,Second:o,Size:i,UUID:r}=t;return new jr({url:s,downloadFlag:n,second:o,size:i,uuid:r})}updatePercent(e){this.uploadProgress=Math.min(e,1)}updateAudioUrl(e){this.content.remoteAudioUrl=e}validateBeforeSend(){if(this[ur])return{isValid:!0};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:n,downloadFlag:o,remoteAudioUrl:i,size:r,second:a}=s;return{MsgType:this.type,MsgContent:{Url:dr.removeAuthToUrl(i),Download_Flag:o,Second:a,Size:r,UUID:n}}}}Vr=ur;const Kr=2108,Hr=2300,Wr=20971520;var Yr=new class{constructor(){this._messageOptionsMap=new Map}init(e){var t;this._core=e;const{notificationCenter:s,helper:n,InnerEvent:o,message:i}=e;n.registerApi({apiName:"createAudioMessage",context:this}),n.registerExperimentalAPI("createAudioMessage",this,"createCustomUploadAudioMessage"),null===(t=null==i?void 0:i.messageFactory)||void 0===t||t.registerElementClass(Xi,jr),s.subscribeInnerEvent(o.DESTROY,this._dispose,this)}createAudioMessage(e){var t,s,n;try{let{file:o}=e.payload;o=this._processAudioFile(e.payload.file),e.payload.file=o;const i=null===(t=this._core.store.get("login"))||void 0===t?void 0:t.userId,r=null===(n=null===(s=this._core)||void 0===s?void 0:s.message.messageFactory)||void 0===n?void 0:n.createMessage(Object.assign(Object.assign({},e),{from:i})),a={second:Math.floor((o.duration||o.second)/1e3),size:o.fileSize||o.size||1,url:o.tempFilePath||o.uri||o.url,uuid:dr.generateUUID(o)},c=new jr(a);return r.setElement(c),this._messageOptionsMap.set(r.clientSequence,e),r}catch(e){throw e}}createCustomUploadAudioMessage(e){var t,s,n;try{this._validateCustomUploadOptions(e);const{store:o,message:i}=this._core,r=null===(t=o.get("login"))||void 0===t?void 0:t.userId,{url:a,uuid:c,duration:u,fileSize:l}=(null===(s=null==e?void 0:e.payload)||void 0===s?void 0:s.file)||{},d=null===(n=i.messageFactory)||void 0===n?void 0:n.createMessage(Object.assign(Object.assign({},e),{from:r})),h=new jr({second:u,size:l||1,url:a,uuid:c,isCustomUpload:!0});return d.setElement(h),this._messageOptionsMap.set(d.clientSequence,e),d}catch(e){throw e}}upload(e){return de(this,void 0,void 0,function*(){const{ssoLog:t,utils:{safeStringify:s}}=this._core;t.debug("upload",`${tr} uploadAudio message:${s(e)}`);const{file:n}=this._messageOptionsMap.get(e.clientSequence).payload;this._validateBeforeUploadAudio(n);const o=e.getElements()[0],i=yield this._performAudioUpload(o,e,n),r=dr.addAuthToUrl(null==i?void 0:i.location);return o.updateAudioUrl(r),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:Hr});if(e.size>Wr)throw new s({message:`File size exceeds limit: ${zi(Wr)}`});if(0===e.size)throw new s({code:Kr})}_performAudioUpload(e,t,s){return de(this,void 0,void 0,function*(){const{to:n}=t,o={uploadFileType:ir,file:s,to:n,message:t,onProgress:s=>{var n,o;e.updatePercent(s),null===(o=null===(n=this._messageOptionsMap.get(t.clientSequence))||void 0===n?void 0:n.onProgress)||void 0===o||o.call(n,s)}},{response:i}=yield _r.uploadToCOS(o);return i})}_processAudioFile(e){var t;const{IN_MINI_APP:s,IN_BROWSER:n}=null===(t=this._core)||void 0===t?void 0:t.utils;return s?this._processMiniFile(e):n?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}_validateCustomUploadOptions(e){var t;const{utils:{isEmpty:s}}=this._core,{url:n,uuid:o,duration:i}=(null===(t=null==e?void 0:e.payload)||void 0===t?void 0:t.file)||{};if(s(n)||s(o)||s(i))throw new Error("Invalid audio message options")}_reset(){this._messageOptionsMap.clear()}_dispose(){this._reset();const{notificationCenter:e,InnerEvent:t}=this._core;e.unSubscribeInnerEvent(t.DESTROY,this._dispose,this)}};const zr={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}},Jr={createImageMessage:zr,createAudioMessage:zr,createVideoMessage:zr,createFileMessage:zr},Qr={createImageMessage:!0,createAudioMessage:!0,createVideoMessage:!0,createFileMessage:!0},Xr={[Qi]:Or,[Zi]:Gr,[er]:Br,[Xi]:Yr};var Zr=new class{constructor(){this.name="RichMediaMessage"}install(e){this._core=e;const{constants:{OuterConstant:{MSG_AUDIO:t,MSG_FILE:s,MSG_IMAGE:n,MSG_VIDEO:o}}}=e;Lr.init(e),Or.init(e),Gr.init(e),Br.init(e),Yr.init(e),_r.init(e),dr.init(e),e.helper.registerApi({apiName:"sendMessage",context:this,matcher:e=>[t,s,n,o].includes(e[0].type)}),e.helper.registerValidateConfig({auth:Qr,params:Jr})}sendMessage(e,t){return de(this,void 0,void 0,function*(){var s,n,o;try{return this._isCustomUpload(e)||(yield this._upload(e)),yield null===(o=null===(n=null===(s=this._core)||void 0===s?void 0:s.message)||void 0===n?void 0:n.messageSender)||void 0===o?void 0:o.sendMessage(e,t)}catch(e){throw e}})}_upload(e){return de(this,void 0,void 0,function*(){const{ssoLog:t,utils:{safeStringify:s}}=this._core;if(t.debug("_upload",` uploadFile message:${s(e)}`),!0!==e._relayFlag)try{const s=Xr[e.type];s&&(yield s.upload(e),t.info("_upload",` type:${e.type}`))}catch(t){throw e.status=ar.FAIL,t instanceof Error&&(t.data={message:e}),this._core.message.messageDataHandler.storeConversationMessage(e),t}})}_isCustomUpload(e){var t,s;return!0===(null===(s=null===(t=e._elements)||void 0===t?void 0:t[0])||void 0===s?void 0:s[ur])}};const ea=new class{init(e){this.core=e}},ta=e=>{const{core:{OuterConstant:t,utils:{isString:s}}}=ea;return s(e)&&e.slice(0,3)===t.CONV_C2C},sa=e=>{const{core:{OuterConstant:t,utils:{isString:s}}}=ea;return s(e)&&e.slice(0,5)===t.CONV_GROUP},na=e=>{const{core:{OuterConstant:t,utils:{isString:s}}}=ea;return s(e)&&e===t.CONV_SYSTEM},oa=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:ea.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 ia(e){const{OuterConstant:t}=ea.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 ra(e){const{OuterConstant:t}=ea.core;let s;return e.startsWith(t.CONV_C2C)&&(s=e.replace(t.CONV_C2C,"")),"@TLS#ERROR"===s||"@TLS#NOT_FOUND"===s}function aa(e,t){const{helper:s}=ea.core,n=new s.ChatError({functionName:e,code:(null==t?void 0:t.errorCode)||(null==t?void 0:t.code),message:(null==t?void 0:t.errorInfo)||(null==t?void 0:t.message)});throw console.error(`${e} fail:`,n),n}class ca{constructor(e){this.conversationID=e.conversationID||"",this.unreadCount=e.unreadCount||0,this.type=e.type||"",this.lastMessage=oa(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}}}=ea;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}}}=ea,{nextUnreadCount:n,isFromGetConversations:o,isUnreadC2CMessage:i}=e;s(n)||(this.subType!==t.GRP_AVCHATROOM?o&&this.type===t.CONV_GROUP||i&&this.type===t.CONV_C2C?this.unreadCount=n:this.unreadCount+=n:this.unreadCount=0)}updateLastMessage(e){this.lastMessage=oa(e)}reduceUnreadCount(){return this.unreadCount>=1&&(this.unreadCount-=1,!0)}isLastMessageRevoked(e){const{core:{OuterConstant:t}}=ea,{sequence:s,time:n}=e;return this.type===t.CONV_C2C&&s===this.lastMessage.lastSequence&&n===this.lastMessage.lastTime||this.type===t.CONV_GROUP&&s===this.lastMessage.lastSequence}setLastMessageRevoked(e){this.lastMessage.isRevoked=e}setLastMessageRevoker(e){this.lastMessage.revoker=e}setDraftText(e){this.draftText=e}updateGroupAtInfoList(e){const{core:{common:{updateGroupAtInfo:t}}}=ea;t(e,this.groupAtInfoList)}clearGroupAtInfoList(){this.groupAtInfoList.length=0}getProfileCompleted(){return this._isInfoCompleted}setProfileCompleted(){this._isInfoCompleted=!0}}var ua,la;!function(e){e[e.OFF=0]="OFF",e[e.ON=1]="ON"}(ua||(ua={})),function(e){e[e.ONLY_CONVERSATIONID=1]="ONLY_CONVERSATIONID"}(la||(la={}));var da;!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"}(da||(da={}));const ha=0,ga=1;var pa=new class{constructor(){this._name="ConversationDataHandler",this._totalUnreadCount=0,this._groupAtTipsList=[]}init(e){this._core=e;const{helper:t,notificationCenter:s,appStore:{conversationStore:n},constants:{WORKFLOW_NAME:o,WORKFLOW_STEP:i},InnerEvent:{SYNC_CONVERSATION_LIST:r,MESSAGE_PUSH:a,NEW_MESSAGE:c,MESSAGE_DELETED:u,MESSAGE_REVOKED:l,MESSAGE_MODIFIED:d,CONVERSATION_UPDATED:h,LOGOUT:g,DESTROY:p},InnerEventSubType:{C2C_MESSAGE_PEER_READ:_}}=e;this._conversationStore=n,t.registerWorkflowStep(o.SYNC_SERVER_INFO_AFTER_LOGIN,i.CONVERSATION_UPDATE_AFTER_UNREAD_SYNC_FINISHED,this._handleUnreadSyncFinished,this),t.registerWorkflowStep(o.SYNC_SERVER_INFO_AFTER_LOGIN,i.CONVERSATION_UPDATE_AFTER_GROUP_LIST_SYNC_FINISHED,this._handleGroupListSyncFinished,this),t.registerWorkflowStep(o.RECEIVE_C2C_NEW_MESSAGE,i.CREATE_OR_UPDATE_CONVERSATION_BY_RECEIVE_NEW_MESSAGE,this._handleNewMessage,this),t.registerWorkflowStep(o.RECEIVE_C2C_NEW_MESSAGE,i.CONVERSATION_UPDATE_AFTER_UNREAD_SYNC_FINISHED,this._handleUnreadSyncFinished,this),t.registerWorkflowStep(o.RECEIVE_GROUP_NEW_MESSAGE,i.CREATE_OR_UPDATE_CONVERSATION_BY_RECEIVE_NEW_MESSAGE,this._handleNewMessage,this),t.registerWorkflowStep(o.SYNC_SERVER_INFO_AFTER_RE_ONLINE,i.CONVERSATION_UPDATE_AFTER_UNREAD_SYNC_FINISHED,this._handleUnreadSyncFinished,this),t.registerWorkflowStep(o.RECEIVE_GROUP_TIPS_NOTIFICATION,i.CREATE_OR_UPDATE_CONVERSATION_BY_RECEIVE_NEW_MESSAGE,this._handleNewMessage,this);const{InnerEventSubType:{GROUP_AT_TIPS:m}}=s;s.subscribeInnerEvent(r,this._handleConversationSynced,this),s.subscribeInnerEvent(c,this._handleNewMessage,this),s.subscribeInnerEvent(a,m,this._handleNewGroupAtTips,this),s.subscribeInnerEvent(u,this._handleMessageDeleted,this),s.subscribeInnerEvent(l,this._handleMessageRevoked,this),s.subscribeInnerEvent(d,this._handleMessageModified,this),s.subscribeInnerEvent(h,this._handleConversationUpdated,this),s.subscribeInnerEvent(a,_,this._handleMessageRead,this),s.subscribeInnerEvent(g,this._reset,this),s.subscribeInnerEvent(p,this._dispose,this),e.ssoLog.debug(`${this._name}.init`)}_handleConversationSynced(e){this.updateLocalConversationList({conversationUpdateFieldList:e.conversationUpdateFieldList||[],isFromGetConversations:!0,updateUnreadCount:!0}),this.emitConversationListUpdate()}_handleUnreadSyncFinished(e){const{constants:{WORKFLOW_STEP:t}}=this._core,{conversationUpdateFieldList:s=[],groupTipList:n=[],isUnreadC2CMessage:o}=e.result[t.UNREAD_MESSAGE_SYNC]||{};let i=!1;s.forEach(e=>{const{conversationID:t,unreadCount:s}=e,n=this.getLocalConversation(t);n&&n.unreadCount!==s&&(n.updateUnreadCount({nextUnreadCount:s,isUnreadC2CMessage:o}),i=!0)}),i&&this.emitConversationListUpdate(),this._handleGroupAtTipsSynced(n)}_handleGroupAtTipsSynced(e){var t;for(let s=0;s<e.length;s++)if(12===e[s].Event){if(null===(t=e[s].GroupTips[0].MsgBody)||void 0===t?void 0:t.TopicId)continue;this._handleNewGroupAtTips(e[s])}}_handleGroupListSyncFinished(e){var t;const{constants:{WORKFLOW_STEP:s}}=this._core,n=e.result[s.GROUP_LIST_SYNC]||[],{OuterConstant:{CONV_GROUP:o}}=this._core;let i=!1;for(let e=0;e<n.length;e++){const s=n[e],r=`${o}${s.groupID}`;if(!this.hasLocalConversation(r))continue;const a=this.getLocalConversation(r);a.groupProfile=JSON.parse(JSON.stringify(s)),a.lastMessage.lastSequence<s.nextMessageSeq&&(a.lastMessage.lastSequence=s.nextMessageSeq-1),a.subType||(a.subType=s.type),(null===(t=s._groupAtInfoList)||void 0===t?void 0:t.length)>0&&this._handleNewGroupAtTips({GroupTips:s._groupAtInfoList}),i=!0}i&&this.emitConversationListUpdate()}_handleNewMessage(e){const{conversationUpdateFieldList:t=[],isInstantMessage:s=!0,isUnreadC2CMessage:n=!1,updateUnreadCount:o=!0}=e.result||{};if(0===t.length)return;const{common:{isTopic:i}}=this._core;if(i(t[0].conversationID))return;this.updateLocalConversationList({conversationUpdateFieldList:t,isInstantMessage:s,isUnreadC2CMessage:n,isFromGetConversations:!1,updateUnreadCount:o});t.filter(e=>this._isConversationNeedShow(e.conversationID)).length>0&&this.emitConversationListUpdate()}_handleNewGroupAtTips(e){const{GroupTips:t=[]}=e;t.forEach(e=>{const{GroupAtTips:t,MsgBody:s,MsgRandom:n,ClientSeq:o}=e;let i={};t?i=this._convertGroupAtTipsKey(t):s?i=Object.assign({},this._convertGroupAtTipsKey(s)):e.groupAtType&&(i=Object.assign({},e)),i.__random=n,i.__sequence=o,this._groupAtTipsList.push(i)}),console.log(`${this._name}._handleNewGroupAtTips groupAtTipsList: ${JSON.stringify(this._groupAtTipsList)}`),this._updateGroupAtInfoList()}_convertGroupAtTipsKey(e){const{From_Account:t,GroupId:s,MsgSeq:n,GroupAtType:o}=e;return{from:t,groupID:s,sequence:n,groupAtType:o}}_updateGroupAtInfoList(){if(0===this._groupAtTipsList.length)return;const{common:e,OuterConstant:t}=this._core,s=e.getCurrentUserID();let n=!1;this._groupAtTipsList.forEach(e=>{const{groupID:o,from:i}=e;if(i!==s){const s=this.getLocalConversation(`${t.CONV_GROUP}${o}`);s&&(s.updateGroupAtInfoList(e),n=!0)}}),n&&this.emitConversationListUpdate(),this._groupAtTipsList.length=0}_handleMessageDeleted(e){var t,s;console.log(`${this._name}._handleMessageDeleted, conversationID:`,e);const{message:{messageDataHandler:n},OuterConstant:o}=this._core,i=(null==n?void 0:n.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(o.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 n=null,o=!1;t.forEach(e=>{n=this.getLocalConversation(e.conversationID),n&&(s&&n.reduceUnreadCount()&&(o=!0),n.isLastMessageRevoked({sequence:e.sequence,time:e.time})&&(n.setLastMessageRevoked(!0),n.setLastMessageRevoker(e.revoker),o=!0))}),o&&this.emitConversationListUpdate()}_handleMessageModified(e){console.log(`${this._name}._handleMessageModified`,JSON.stringify(e));const{conversationID:t,messageList:s}=e,n=this.getLocalConversation(t),{utils:{isEmpty:o},common:{getMessagePreviewText:i}}=this._core;if(o(n))return;const{lastMessage:r}=n;if(r){const e=(null==s?void 0:s[0])||{};r.lastTime===e.time&&r.lastSequence===e.sequence&&r.version!==e.version&&(r.type=e.type,r.payload=e.payload,r.messageForShow=i(e.type,e.payload),r.cloudCustomData=e.cloudCustomData,r.version=e.version,this.emitConversationListUpdate(),console.log(`${this._name} conversationID:${t} lastMessage updated`))}}_handleConversationUpdated(e){this.emitConversationListUpdate(null==e?void 0:e.needSort)}updateLocalConversationList(e){const{isFromGetConversations:t}=e,{newConversationList:s}=this._getTmpConversationListMapping(e);this._sortConversationList(),t||this._updateNewConversationProfile(s),this._core.ssoLog.debug("updateLocalConversationList",` newConversationList: ${s.length}`)}_getTmpConversationListMapping(e){const{OuterConstant:t}=this._core,{conversationUpdateFieldList:s,isFromGetConversations:n,isInstantMessage:o,isUnreadC2CMessage:i=!1,updateUnreadCount:r}=e,a=[],c=null==s?void 0:s.length;for(let e=0;e<c;e++){const c=new ca(s[e]),{conversationID:u,type:l}=c;if(!ra(u))if(this.hasLocalConversation(u)){const a=this.getLocalConversation(u);if(n){this.setLocalConversation(u,c),l===t.CONV_C2C?c.unreadCount=(null==a?void 0:a.unreadCount)||0:l===t.CONV_GROUP&&(c.groupProfile=JSON.parse(JSON.stringify(null==a?void 0:a.groupProfile)));continue}this._mergeConversationInfo({conversationID:u,tmpConversation:c,lastMessage:s[e].lastMessage,isFromGetConversations:n,isInstantMessage:o}),this._patchLastMessage({conversationID:u,lastMessage:s[e].lastMessage,isInstantMessage:o}),!0===r&&(null==a||a.updateUnreadCount({nextUnreadCount:c.unreadCount,isFromGetConversations:n,isUnreadC2CMessage:i}))}else a.push(c),this.setLocalConversation(u,c)}return{newConversationList:a}}_mergeConversationInfo(e){const{conversationID:t,tmpConversation:s,lastMessage:n,isFromGetConversations:o,isInstantMessage:i}=e,r=this.getLocalConversation(t),a=["unreadCount","allowType","adminForbidType","payload"];!1===i&&a.push("lastMessage"),o&&a.push("isPinned");const{utils:{isUndefined:c,isEmpty:u},common:{deepMerge:l}}=this._core;c(i)&&n&&null===(null==r?void 0:r.lastMessage.payload)&&(r.lastMessage.payload=n.payload),u(null==r?void 0:r.lastMessage.revoker)||(r.lastMessage.revoker=null);l(r,s,a,[null,void 0,"",0,NaN])}_patchLastMessage(e){const{OuterConstant:t}=this._core,{conversationID:s,lastMessage:n,isInstantMessage:o}=e,i=this.getLocalConversation(s);if(i&&n){const{payload:e,nameCard:s,nick:r,cloudCustomData:a=""}=n;o&&(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=[],n=[],o=[],i=[];t.forEach(t=>{!0===t[1].isPinned?e(t[1].lastMessage.lastTime)?n.push(t):s.push(t):e(t[1].lastMessage.lastTime)?i.push(t):o.push(t)});const r=s.sort((e,t)=>t[1].lastMessage.lastTime-e[1].lastMessage.lastTime).concat(n).concat(o.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:n,CONV_C2C:o}}=this._core;e.forEach(e=>{const{conversationID:i,type:r}=e;if(r===o){const e=i.replace(o,"");t.push(e)}else if(r===n){const e=i.replace(n,"");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:n},user:o}=this._core;let i=!1;null===(t=o.userProfile)||void 0===t||t.getUserProfile({userIDList:e}).then(e=>{((null==e?void 0:e.data)||[]).forEach(e=>{var t;const{userID:o}=e,r=this.getLocalConversation(`${s}${o}`);if(r){const s=(null===(t=n.getFriend(o))||void 0===t?void 0:t.remark)||"";r.remark=s,r.userProfile=e,i=!0}}),i&&this.emitConversationListUpdate()}).catch(e=>{})}_updateGroupConversation(e){return de(this,void 0,void 0,function*(){const{OuterConstant:{CONV_GROUP:t},appStore:{groupStore:s},utils:{isEmpty:n,safeStringify:o},ssoLog:i,apiMap:{getGroupProfile:r}}=this._core;let a=!1;try{yield Promise.all(e.map(e=>de(this,void 0,void 0,function*(){const o=s.getGroup(e),i=this.getLocalConversation(`${t}${e}`);o&&i&&(i.groupProfile=o,a=!0),n(o)&&i&&"function"==typeof r&&(yield r({groupID:e}))}))),a&&this.emitConversationListUpdate()}catch(e){i.debug("_updateGroupConversation",o(e))}})}_handleMessageRead(e){const{OuterConstant:{CONV_C2C:t}}=this._core,{C2cNotifyMsgArray:s=[]}=e||{};s.forEach(e=>{const{To_Account:s,UinPairReadArray:n=[]}=(null==e?void 0:e.C2cReadedReceipt)||{};null==n||n.forEach(e=>{const{LastReadTime:n}=e,o=`${t}${s}`;this._updateConversationReadInfo({conversationID:o,peerReadTime:n}),this._updateMessageListPeerRead({conversationID:o,peerReadTime:n})})})}_updateConversationReadInfo(e){const{appStore:t,utils:{isEmpty:s},common:{getCurrentUserID:n}}=this._core,{conversationID:o,peerReadTime:i}=e,r=t.conversationStore.getConversationMap();if(r.has(o)){const e=r.get(o);e.peerReadTime=i;const a=null==e?void 0:e.lastMessage;s(a)||a.fromAccount===n()&&a.lastTime<=i&&!a.isPeerRead&&(a.isPeerRead=!0,t.conversationStore.updateConversation(o,{lastMessage:a}))}}_updateMessageListPeerRead(e){const{notificationCenter:t,OuterEvent:s,message:n}=this._core,{conversationID:o,peerReadTime:i}=e,r=n.messageDataHandler.getLocalMessageList(o),a=n.messageDataHandler.getSparseMessageList(o),c=[];r.forEach(e=>{e.time<=i&&!e.isPeerRead&&"out"===e.flow&&(e.isPeerRead=!0,c.push(e))}),a.forEach(e=>{e.time<=i&&!e.isPeerRead&&"out"===e.flow&&(e.isPeerRead=!0,c.push(e))}),t.emitOuterEvent(s.MESSAGE_READ_BY_PEER,{name:s.MESSAGE_READ_BY_PEER,data:c})}_isConversationNeedShow(e){var t,s;const{OuterConstant:{CONV_GROUP:n,GRP_ROOM:o,GRP_LIVE:i},utils:{isUndefined:r}}=this._core,a=this.getLocalConversation(e);if(r(a))return!0;const c=a.type===n&&(null===(t=a.groupProfile)||void 0===t?void 0:t.type)===o,u=a.type===n&&(null===(s=a.groupProfile)||void 0===s?void 0:s.type)===i;return!(c||u)}updateUnreadCount(e,t=!0){var s,n;let o=!1;const i=this.getLocalConversation(e),r=null===(n=null===(s=this._core)||void 0===s?void 0:s.message.messageDataHandler)||void 0===n?void 0:n.getLocalMessageList(e);if(!i)return o;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,o=!0,!0===t&&this.emitConversationListUpdate()),o}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&&(this._core.ssoLog.debug("_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,utils:{isEmpty:t}}=this._core,s=this.getLocalConversationList();let n=0;return s.forEach(s=>{s.type!==e.CONV_SYSTEM&&(t(s.messageRemindType)||s.messageRemindType===e.MSG_REMIND_ACPT_AND_NOTE)&&(n+=s.unreadCount)}),n}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 n=this.getLocalConversation(e);(null==n?void 0:n.messageRemindType)!==t&&(n.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:n=0,lastReadSequence:o=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=n&&t.time>n,r=o&&t.sequence>o;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:n,MESSAGE_MODIFIED:o,CONVERSATION_UPDATED:i,LOGOUT:r,DESTROY:a,SYNC_CONVERSATION_LIST:c}}=this._core,{InnerEventSubType:{GROUP_AT_TIPS:u}}=e;e.unSubscribeInnerEvent(t,this._handleNewMessage,this),e.unSubscribeInnerEvent(t,u,this._handleNewGroupAtTips,this),e.unSubscribeInnerEvent(s,this._handleMessageDeleted,this),e.unSubscribeInnerEvent(n,this._handleMessageRevoked,this),e.unSubscribeInnerEvent(o,this._handleMessageModified,this),e.unSubscribeInnerEvent(i,this._handleConversationUpdated,this),e.unSubscribeInnerEvent(c,this._handleConversationSynced,this),e.unSubscribeInnerEvent(r,this._reset,this),e.unSubscribeInnerEvent(a,this._dispose,this)}};var _a=new class{constructor(){this._name="GetConversationList"}init(e){this._core=e;const{helper:t}=e;t.registerApi({apiName:"getConversationList",context:this})}getConversationList(e){return de(this,void 0,void 0,function*(){return{code:0,data:{conversationList:this._getConversationList(e),isSyncCompleted:this._core.conversation.syncConversationHandler.isSyncCompleted()}}})}_getConversationList(e){const{utils:{isUndefined:t,isArray:s,isPlainObject:n}}=this._core;if(t(e))return pa.getLocalConversationList();if(s(e)){if(0===e.length)return[];return pa.getLocalConversationList().filter(t=>e.includes(t.conversationID))}if(n(e)){const{type:t,markType:s,groupName:n,hasUnreadCount:o,hasGroupAtInfo:i}=e;return pa.getLocalConversationList().filter(e=>this._filterType(e,t)&&this._filterMarkType(e,s)&&this._filterGroupName(e,n)&&this._filterUnreadCount(e,o)&&this._filterGroupAtInfo(e,i))}return[]}_filterType(e,t){const{OuterConstant:s}=this._core;return t!==s.CONV_C2C&&t!==s.CONV_GROUP||e.type===t}_filterGroupName(e,t){const{utils:{isString:s}}=this._core;return!s(t)||(""===t?0===e.conversationGroupList.length:e.conversationGroupList.includes(t))}_filterMarkType(e,t){const{utils:{isNumber:s}}=this._core;return!s(t)||(0===t?0===e.markList.length:e.markList.includes(t))}_filterUnreadCount(e,t){let s=!0;return!0===t?s=e.unreadCount>=1:!1===t&&(s=0===e.unreadCount),s}_filterGroupAtInfo(e,t){let s=!0;return!0===t?s=e.groupAtInfoList.length>=1:!1===t&&(s=0===e.groupAtInfoList.length),s}};var ma=new class{constructor(){this._name="GetC2CMessageRemindType"}init(e){this._core=e}get(e){return de(this,void 0,void 0,function*(){try{const{common:t}=this._core,s=yield function(e,t){return de(this,void 0,void 0,function*(){const{toAccount:s,userIDList:n}=e,o={To_Account:s,Peer_Account:n};return t.common.buildAndSendPacket({servcmd:"openim.get_c2c_peer_mute_notifications",data:o})})}({toAccount:t.getCurrentUserID(),userIDList:e},this._core),{MuteNotificationsList:n=[]}=s||{};n.forEach(e=>{const{Peer_Account:t,MuteNotifications:s}=e,n=`${this._core.OuterConstant.CONV_C2C}${t}`,o=ia(s);pa.patchMessageRemindType([n],o)})}catch(e){console.error(`${this._name}.get fail:`,e)}})}};var va=new class{constructor(){this._name="GetGroupMessageRemindType"}init(e){this._core=e}get(e){return de(this,void 0,void 0,function*(){if(0!==e.length)try{const t=yield function(e,t){return de(this,void 0,void 0,function*(){const{groupIDList:s,responseFilter:n}=e,o={GroupIdList:s,ResponseFilter:n};return t.common.buildAndSendPacket({servcmd:"group_open_http_svc.get_group_self_member_info",data:o})})}({groupIDList:e,responseFilter:{MemberInfoFilter:["MsgFlag"]}},this._core),{GroupInfo:s=[]}=t||{};s.forEach(e=>{var t;const{GroupId:s,MemberList:n}=e,o=(null===(t=n[0])||void 0===t?void 0:t.MsgFlag)||"",i=`${this._core.OuterConstant.CONV_GROUP}${s}`;pa.patchMessageRemindType([i],o)})}catch(e){console.error(`${this._name}.get fail:`,e)}})}};var fa=new class{constructor(){this._name="GetConversationProfile"}init(e){this._core=e;const{helper:t}=e;t.registerApi({apiName:"getConversationProfile",context:this})}getConversationProfile(e){return de(this,void 0,void 0,function*(){const{OuterConstant:{CONV_C2C:t,CONV_GROUP:s,GRP_AVCHATROOM:n},appStore:{groupStore:o},utils:{isEmpty:i}}=this._core,r={code:0,data:{}};let a=pa.getLocalConversation(e);if(na(e))return r.data.conversation=a,r;let c=!1;const u=ta(e)?t:s;if(i(a)&&(c=!0,a=new ca({conversationID:e,type:u})),console.log(`${this._name}.getConversationProfile conversationID:${e} isNewConversation:${c}`),r.data.conversation=a,null==a?void 0:a.getProfileCompleted())return r;if(u===t){const s=e.replace(t,"");yield this._handleC2CConversation(a,s),c&&(yield ma.get([s]))}if(u===s){const t=e.replace(s,"");if(!o.getGroup(t))return r;yield this._handleGroupConversation(a,t),c&&a.groupProfile.type!==n&&(yield va.get([t]))}return r})}_handleC2CConversation(e,t){return de(this,void 0,void 0,function*(){var s,n;const{user:o,helper:i,utils:{isEmpty:r},appStore:{conversationStore:a,userStore:c}}=this._core,{conversationID:u}=e,l=yield null===(s=o.userProfile)||void 0===s?void 0:s.getUserProfile({userIDList:[t]});if(0===(null==l?void 0:l.data.length))throw new i.ChatError({code:da.USER_OR_GRP_NOT_FOUND});e.userProfile=null==l?void 0:l.data[0];const d=null===(n=c.getFriend(t))||void 0===n?void 0:n.remark;r(d)||e.remark===d||(e.remark=d),e.setProfileCompleted();const h=pa.hasLocalConversation(u);console.log(`${this._name}._handleC2CConversation conversationID:${u} hasLocalConversation: ${h}`),h?a.updateConversation(u,e):pa.appendToPinnedConversation(e)})}_handleGroupConversation(e,t){return de(this,void 0,void 0,function*(){const{apiMap:{getGroupProfile:s},appStore:{conversationStore:n}}=this._core,{conversationID:o}=e,i=yield s({groupID:t});e.groupProfile=null==i?void 0:i.data.group,e.setProfileCompleted();const r=pa.hasLocalConversation(o);console.log(`${this._name}._handleGroupConversation conversationID:${o} hasLocalConversation: ${r}`),r?n.updateConversation(o,e):pa.appendToPinnedConversation(e)})}};var Ia=new class{init(e){const{helper:t}=e;t.registerApi({apiName:"getTotalUnreadMessageCount",context:this})}getTotalUnreadMessageCount(){return pa.getTotalUnreadMessageCount()}};var Ea=new class{constructor(){this._serverGroupConversationLastReadSeqMap=new Map,this._name="SetMessageRead"}init(e){this._core=e;const{helper:t,common:{isTopic:s},notificationCenter:n,InnerEvent:{MESSAGE_PUSH:o},InnerEventSubType:{ALL_MESSAGE_READ:i}}=e;t.registerApi({apiName:"setMessageRead",context:this,matcher:e=>!s(e[0].conversationID)}),t.registerApi({apiName:"setAllMessageRead",context:this}),n.subscribeInnerEvent(o,i,this._handleAllMessageRead,this)}handleC2CMessageReadSync(e){const{helper:{isEmpty:t},OuterConstant:s}=this._core;e.forEach(e=>{const{ReadC2cMsgNotify:n}=e;if(!t(n)){const{UinPairReadArray:e=[]}=n;e.forEach(e=>{const{From_Account:t,LastReadTime:n}=e,o=`${s.CONV_C2C}${t}`;console.log(`${this._name}.handleC2CMessageReadSync conversationID:${o} lastReadTime:${n}`),pa.markMessageAsRead({conversationID:o,lastReadTime:n}),pa.updateUnreadCount(o)})}})}handleGroupMessageReadSync(e){const{OuterConstant:t,utils:{isUndefined:s}}=this._core;e.forEach(e=>{const{GroupReadInfoArray:n}=e.MsgBody;s(n)||n.forEach(e=>{const{GroupId:s,LastReadMsgSeq:n}=e,o=`${t.CONV_GROUP}${s}`;console.log(`${this._name}.handleGroupMessageReadSync conversationID:${o} lastReadSequence:${n}`),pa.markMessageAsRead({conversationID:o,lastReadSequence:n}),pa.updateUnreadCount(o),this._clearGroupAtInfoList(o)})})}setMessageRead(e){return de(this,void 0,void 0,function*(){var t,s;const{OuterConstant:n}=this._core,{conversationID:o}=e,i={code:0,data:{}},r=pa.getLocalConversation(o);let a=`${this._name}.setMessageRead conversationID:${o} unreadCount:${(null==r?void 0:r.unreadCount)||0}`;if(i.successLog={message:a},!r)return i;const c=!(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===n.CONV_GROUP&&c&&this._deleteGroupAtTips(o),0===r.unreadCount)return i;const{helper:{ChatError:u}}=this._core;try{if(r.type===n.CONV_C2C){const e=this._getLocalMessageMaxTime(r);yield this._setC2CMessageRead(o,e),a+=`lastMessageTime:${e}`}if(r.type===n.CONV_GROUP){const e=this._getLocalMessageMaxSequence(r);yield this._setGroupMessageRead(o,e),a+=`lastMessageSequence:${e}`}}catch(e){const{errorCode:t,errorInfo:s}=e;throw new u({functionName:"setMessageRead",code:t,message:s,moreMessage:a})}return r.type===n.CONV_SYSTEM&&(r.unreadCount=0),pa.emitConversationListUpdate(),Object.assign(Object.assign({},i),{successLog:{message:a}})})}setAllMessageRead(){return de(this,arguments,void 0,function*(e={}){const{OuterConstant:{READ_ALL_MSG:t},utils:{safeStringify:s}}=this._core;let n=`scope:${e.scope}`;e.scope||(e.scope=t);const{scope:o}=e,i=this._generateSetAllMessageReadRequestData(o);if(i.allC2CMessageReadStatus===ha&&0===i.groupMessageReadInfoList.length)return{code:0};try{const e=yield function(e){return de(this,void 0,void 0,function*(){const{allC2CMessageReadStatus:t,groupMessageReadInfoList:s}=e,n={C2CReadAllMsg:t,GroupReadInfo:s};return ea.core.common.buildAndSendPacket({servcmd:"openim.read_all_unread_msg",data:n})})}(i);if(e){const{GroupReadInfoArray:t,C2CReadAllMsg:o}=e,i=this._parseGroupReadInfo(t);this._updateAllConversationReadStatus({allC2CMessageReadStatus:o})>0&&pa.emitConversationListUpdate(),n+=`failureGroupInfoList:${s(i)}`}return{code:0,successLog:{message:n}}}catch(e){const{errorCode:t}=e;throw new this._core.helper.ChatError({functionName:"setAllMessageRead",code:t,moreMessage:n})}})}_handleAllMessageRead(e){const{GroupReadInfoArray:t,C2CReadAllMsg:s}=e;this._parseGroupReadInfo(t);this._updateAllConversationReadStatus({allC2CMessageReadStatus:s})>0&&pa.emitConversationListUpdate()}_updateAllConversationReadStatus(e){const{OuterConstant:{CONV_C2C:t,CONV_GROUP:s},appStore:n}=this._core,o=n.conversationStore.getConversationMap(),{allC2CMessageReadStatus:i}=e;let r=0;for(const[e,n]of o)if(n.unreadCount>=1){if(i===ga&&n.type===t){const t=this._getLocalMessageMaxTime(n);pa.markMessageAsRead({conversationID:e,lastReadTime:t})}else if(n.type===s){const t=e.replace(s,"");if(this._serverGroupConversationLastReadSeqMap.has(t)){const s=this._serverGroupConversationLastReadSeqMap.get(t);pa.markMessageAsRead({conversationID:e,lastReadSequence:s})}}pa.updateUnreadCount(e,!1)&&(r+=1)}return r}_generateSetAllMessageReadRequestData(e){const{OuterConstant:{CONV_C2C:t,CONV_GROUP:s,READ_ALL_C2C_MSG:n},appStore:o}=this._core,i={allC2CMessageReadStatus:ha,groupMessageReadInfoList:[]},r=o.conversationStore.getConversationMap();for(const[,o]of r){const{type:r,unreadCount:a}=o;if(this._shouldSetAllMessageRead({scope:e,type:r,unreadCount:a}))if(r===t&&i.allC2CMessageReadStatus===ha){if(i.allC2CMessageReadStatus=ga,e===n)break}else if(r===s){const e=this._getLocalMessageMaxSequence(o),{groupID:t}=o.groupProfile;i.groupMessageReadInfoList.push({GroupId:t,MsgSeq:e})}}return i}_parseGroupReadInfo(e){const{utils:{isUndefined:t}}=this._core,s=[];return null==e||e.forEach(e=>{const{GroupId:n,MsgSeq:o,RetCode:i,LastReadMsgSeq:r}=e;t(i)?this._serverGroupConversationLastReadSeqMap.set(n,r):(this._serverGroupConversationLastReadSeqMap.set(n,o),0!==i&&s.push(`${n}-${o}-${i}`))}),s}_deleteGroupAtTips(e){return de(this,void 0,void 0,function*(){console.log(`${this._name}._deleteGroupAtTips conversationID:${e}`);const t=pa.getLocalConversation(e);if(!t)return;const s=(null==t?void 0:t.groupAtInfoList)||[];if(0!==s.length)try{const{common:{getCurrentUserID:t,isCommunity:n},OuterConstant:{CONV_GROUP:o,CONV_AT_ALL:i}}=this._core;let r=[...s];if(n({groupID:e.replace(o,"")})&&(r=s.filter(e=>!e.atTypeArray.includes(i)),0===r.length))return void this._clearGroupAtInfoList(e,!1);const a=r.map(e=>({From_Account:e.from,To_Account:t(),MsgSeq:e.__sequence,MsgRandom:e.__random,GroupId:e.groupID}));yield function(e,t){return de(this,void 0,void 0,function*(){const{messageListToDelete:s}=e,n={DelMsgList:s};return t.common.buildAndSendPacket({servcmd:"openim.deletemsg",data:n})})}({messageListToDelete:a},this._core),console.log(`${this._name}._deleteGroupAtTips ok. count:${s.length}`),this._clearGroupAtInfoList(e)}catch(e){console.error(`${this._name}._deleteGroupAtTips fail:`,e)}})}_clearGroupAtInfoList(e,t=!0){const s=pa.getLocalConversation(e);s&&(s.groupAtInfoList.length>0&&(s.clearGroupAtInfoList(),console.log(`${this._name}._clearGroupAtInfoList conversationID:${e} needEmitConversationUpdate:${t}`)),t&&pa.emitConversationListUpdate())}_getLocalMessageMaxTime(e){var t;const{conversationID:s}=e,n=this._core.message.messageDataHandler.getLocalMessageList(s),o=Math.max(...n.map(e=>e.time));let i=(null===(t=null==e?void 0:e.lastMessage)||void 0===t?void 0:t.lastTime)||0;return o>i&&(console.log(`${this._name}._getLocalMessageMaxTime update lastMessageTime from ${i} to ${o}`),i=o),i}_getLocalMessageMaxSequence(e){var t;const{conversationID:s}=e,n=this._core.message.messageDataHandler.getLocalMessageList(s),o=Math.max(...n.map(e=>e.sequence));let i=(null===(t=null==e?void 0:e.lastMessage)||void 0===t?void 0:t.lastSequence)||0;return o>i&&(console.log(`${this._name}._getLocalMessageMaxSequence update lastMessageSequence from ${i} to ${o}`),i=o),i}_setC2CMessageRead(e,t){return de(this,void 0,void 0,function*(){try{yield function(e,t){return de(this,void 0,void 0,function*(){return t.common.buildAndSendPacket({servcmd:"openim.msgreaded",data:e})})}({C2CMsgReaded:{Cookie:"",C2CMsgReadedItem:[{To_Account:e.replace("C2C",""),LastedMsgTime:t,Receipt:1}]}},this._core),console.log(`${this._name}._setC2CMessageRead ok, lastReadTime:${t}`),pa.markMessageAsRead({conversationID:e,lastReadTime:t}),pa.updateUnreadCount(e)}catch(e){throw console.warn(`${this._name}._setC2CMessageRead fail:`,e),e}})}_setGroupMessageRead(e,t){return de(this,void 0,void 0,function*(){try{yield function(e,t){return de(this,void 0,void 0,function*(){const{groupID:s,lastMessageSequence:n}=e,o={GroupId:s,MsgReadedSeq:n};return t.common.buildAndSendPacket({servcmd:"group_open_http_svc.msg_read_report",data:o})})}({groupID:e.replace("GROUP",""),lastMessageSequence:t},this._core),console.log(`${this._name}._setGroupMessageRead ok, lastReadSequence:${t}`),pa.markMessageAsRead({conversationID:e,lastReadSequence:t}),pa.updateUnreadCount(e)}catch(e){throw console.warn(`${this._name}._setGroupMessageRead fail:`,e),e}})}_shouldSetAllMessageRead(e){const{OuterConstant:{CONV_C2C:t,CONV_GROUP:s,READ_ALL_MSG:n,READ_ALL_C2C_MSG:o,READ_ALL_GROUP_MSG:i}}=this._core,{type:r,scope:a,unreadCount:c}=e;return!(c<=0)&&(!(r!==t||![n,o].includes(a))||!(r!==s||![n,i].includes(a)))}};var Sa=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:n}=this._core;let o=!1;e.forEach(e=>{const{Type:s,To_Account:i,GroupId:r}=e;let a;1===s?a=pa.getLocalConversation(`${n.CONV_C2C}${i}`):2===s&&(a=pa.getLocalConversation(`${n.CONV_GROUP}${r}`)),a&&(console.log(`${this._name}.handleConversationPinned conversationID:${a.conversationID} localPinned:${a.isPinned} remotePinned:${t}`),t&&!a.isPinned&&(a.isPinned=!0,o=!0),!t&&a.isPinned&&(a.isPinned=!1,o=!0))}),o&&pa.emitConversationListUpdate(!0)}pinConversation(e){return de(this,void 0,void 0,function*(){const{OuterConstant:t,common:s,helper:{ChatError:n}}=this._core,{conversationID:o,isPinned:i}=e,r={code:0,data:{conversationID:o}},a=pa.getLocalConversation(o);if(a&&a.isPinned===i)return r;if(na(o))return a&&(a.isPinned=i),pa.emitConversationListUpdate(!0),r;const c=`conversationID:${o} isPinned:${i}`;try{let e=null;ta(o)?e={Type:1,To_Account:o.replace(t.CONV_C2C,"")}:sa(o)&&(e={Type:2,GroupId:o.replace(t.CONV_GROUP,"")});const n=yield function(e,t){return de(this,void 0,void 0,function*(){const{fromAccount:s,operationType:n,itemList:o}=e,i={From_Account:s,OperationType:n,RecentContactItem:o};return t.common.buildAndSendPacket({servcmd:"recentcontact.top",data:i})})}({fromAccount:s.getCurrentUserID(),operationType:!0===i?1:2,itemList:[e]},this._core);if(n){if(a)a.isPinned!==i&&(a.isPinned=i);else{const e=new ca({conversationID:o,type:ta(o)?t.CONV_C2C:t.CONV_GROUP,isPinned:i});pa.setLocalConversation(o,e)}pa.emitConversationListUpdate(!0)}return Object.assign(Object.assign({},r),{successLog:{message:c}})}catch(e){const{errorCode:t,errorInfo:s}=e;throw new n({functionName:"pinConversation",code:t,message:s,moreMessage:c})}})}};var Ca=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,n=[];e.forEach(e=>{const{Type:t,Peer_Account:o,GroupId:i}=e;1===t&&n.push(`${s.CONV_C2C}${o}`),2===t&&n.push(`${s.CONV_GROUP}${i}`)}),console.log(`${this._name}.handleConversationDeleted conversationIDList:${n}`),this._deleteLocalConversationList(n)}deleteConversation(e){return de(this,void 0,void 0,function*(){const{utils:{isString:t}}=this._core;if(t(e))return void(yield this._deleteConversation({conversationIDList:[e],flag:la.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 de(this,void 0,void 0,function*(){const{conversationIDList:t,clearHistoryMessage:s=!0,flag:n=0}=e,{helper:{ChatError:o}}=this._core,i=`conversationIDList:${t} clearHistoryMessage:${s}`;try{const e=yield Promise.all([this._deleteConversationFromLocal(t),this._deleteConversationFromServer(t,s)]),o=[...e[0],...e[1]];if(0===o.length)throw new this._core.helper.ChatError({code:da.CONV_NOT_FOUND});return{code:0,data:n===la.ONLY_CONVERSATIONID?{conversationID:o[0]}:{conversationIDList:o},successLog:{message:i}}}catch(e){const{errorCode:t,errorInfo:s}=e;throw new o({code:t,message:s,moreMessage:i})}})}_deleteConversationFromLocal(e){const{OuterConstant:t}=this._core;return e.filter(e=>{var s;if(!pa.hasLocalConversation(e))return!1;const n=null===(s=pa.getLocalConversation(e))||void 0===s?void 0:s.type;return n!==t.CONV_GROUP||this._hasLocalGroup(e)?n===t.CONV_SYSTEM&&(this._deleteLocalConversation(e),!0):(this._deleteLocalConversation(e),!0)})}_deleteConversationFromServer(e,t){return de(this,void 0,void 0,function*(){const{OuterConstant:s,common:n}=this._core,o={fromAccount:n.getCurrentUserID(),conversationList:[],clearHistoryMessage:t?1:0};if(e.forEach(e=>{var t;if(pa.hasLocalConversation(e)){const n=(null===(t=pa.getLocalConversation(e))||void 0===t?void 0:t.type)||"",i=e.replace(n,"");n===s.CONV_C2C?o.conversationList.push({To_Account:i,Type:1}):n===s.CONV_GROUP&&this._hasLocalGroup(e)&&o.conversationList.push({ToGroupid:i,Type:2})}}),0===o.conversationList.length)return[];const i=yield function(e,t){return de(this,void 0,void 0,function*(){const{fromAccount:s,conversationList:n,clearHistoryMessage:o}=e,i={From_Account:s,ContactItem:n,ClearRamble:o};return t.common.buildAndSendPacket({servcmd:"recentcontact.batch_delete",data:i})})}(o,this._core);if(i){const{ResultItem:e=[]}=i,t=[];return e.length>0&&e.forEach(e=>{if(0===e.ResultCode){const n=1===e.Type?`${s.CONV_C2C}${e.To_Account}`:`${s.CONV_GROUP}${e.ToGroupid}`;t.push(n)}}),this._deleteLocalConversationList(t),t}return[]})}_deleteLocalConversationList(e){let t=!1;e.forEach(e=>{pa.hasLocalConversation(e)&&(this._deleteLocalConversation(e,!1),t=!0)}),console.log(`${this._name}._deleteLocalConversationList isUpdate:${t}`),t&&pa.emitConversationListUpdate()}_deleteLocalConversation(e,t=!0){const s=pa.hasLocalConversation(e);console.log(`${this._name}._deleteLocalConversation conversationID:${e} has:${s}`),s&&(pa.deleteLocalConversation(e),this._deleteConversationLocalMessage(e),t&&pa.emitConversationListUpdate())}_hasLocalGroup(e){const{OuterConstant:{CONV_GROUP:t},appStore:{groupStore:s}}=this._core,n=e.replace(t,"");return!!s.getGroup(n)}_deleteConversationLocalMessage(e){console.log(`${this._name}._deleteConversationLocalMessage conversationID:${e}`),this._core.message.messageDataHandler.deleteConversationMessageList(e)}};var Ma=new class{constructor(){this._name="SetConversationDraft"}init(e){this._core=e;const{helper:t}=e;t.registerApi({apiName:"setConversationDraft",context:this})}setConversationDraft(e){return de(this,void 0,void 0,function*(){const{conversationID:t,draftText:s}=e;if(console.log(`${this._name} conversationID:${t} draftText:${s}`),!pa.hasLocalConversation(t))throw new this._core.helper.ChatError({code:da.CONV_NOT_FOUND});const n=pa.getLocalConversation(t);return null==n||n.setDraftText(s),pa.emitConversationListUpdate(),{code:0,data:{conversation:n}}})}};var ya=new class{constructor(){this._name="SetC2CMessageRemindType"}init(e){this._core=e}set(e,t){return de(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}=ea.core.OuterConstant;return{[e]:0,[t]:1,[s]:2}}()[t],n=yield function(e,t){return de(this,void 0,void 0,function*(){const{userIDList:s,receiveMessageOption:n}=e,o={Peer_Account:s,Mute_Notifications:n};return t.common.buildAndSendPacket({servcmd:"openim.set_c2c_peer_mute_notifications",data:o})})}({userIDList:e,receiveMessageOption:s},this._core),{ErrorList:o=[]}=n||{},i=[];o.forEach(t=>{const{Peer_Account:s,ErrorCode:n}=t;i.push({userID:s,code:n});const o=e.indexOf(s);o>-1&&e.splice(o,1)});const r=[],a=[],{OuterConstant:c}=this._core;return e.forEach(e=>{a.push(`${c.CONV_C2C}${e}`),r.push({userID:e})}),pa.patchMessageRemindType(a,t),{code:0,data:{successUserIDList:r,failureUserIDList:i}}})}};var Oa=new class{constructor(){this._name="SetGroupMessageRemindType"}init(e){this._core=e}set(e,t){return de(this,void 0,void 0,function*(){const{common:{getCurrentUserID:s,isTopic:n},OuterConstant:o}=this._core;if(yield function(e,t){return de(this,void 0,void 0,function*(){const{groupID:s,userID:n,receiveMessageOption:o}=e,i={GroupId:s,Member_Account:n,MsgFlag:o};return t.common.buildAndSendPacket({servcmd:"group_open_http_svc.modify_group_member_info",data:i})})}({groupID:e,userID:s(),receiveMessageOption:t},this._core),!n(e)){const s=`${o.CONV_GROUP}${e}`;pa.patchMessageRemindType([s],t)}return{code:0,data:{groupID:e,messageRemindType:t}}})}};var Aa=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,ssoLog:n}=this._core;e.forEach(e=>{const{MuteNotificationsSync:o}=e;if(!t(o)){const{To_Account:e,MuteNotifications:t}=o,i=e.map(e=>`${s.CONV_C2C}${e}`),r=ia(t);n.debug(`${this._name}.handleC2CMessageRemindTypeSync conversationIDList:${i} messageRemindType:${r}`),pa.patchMessageRemindType(i,r)}})}setMessageRemindType(e){return de(this,void 0,void 0,function*(){const t="setMessageRemindType",{groupID:s,userIDList:n,messageRemindType:o}=e,{helper:i,utils:{isUndefined:r},ssoLog:a}=this._core;try{if(!r(s)){a.debug(`${this._name}.${t} groupID:${s} messageRemindType:${o}`);return yield Oa.set(s,o)}if(!r(n)){a.debug(`${this._name}.${t} userIDList:${n} messageRemindType:${o}`);return yield ya.set(n,o)}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 Ta=new class{init(e){e.ssoLog.debug("ConversationAction.init"),this._core=e,_a.init(e),fa.init(e),Ia.init(e),Ea.init(e),Sa.init(e),Ca.init(e),Ma.init(e),Aa.init(e);const{notificationCenter:t,InnerEvent:{MESSAGE_PUSH:s,DESTROY:n}}=this._core,{InnerEventSubType:{CONV_MODIFIED:o,C2C_MESSAGE_READ_SYNC:i,GROUP_MESSAGE_READ_SYNC:r,C2C_REMIND_TYPE_SYNC:a}}=t;t.subscribeInnerEvent(s,o,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(n,this._dispose,this)}_onConversationModified(e){const{constants:{ConvModifyPushType:t}}=this._core,{RecentContactMod:s=[]}=e;s.forEach(e=>{const{PushType:s}=e;if(s===t.CONV_DELETED){const{RecentContactList:t}=e.RecentContactDeleteItem;Ca.handleConversationDeleted(t)}if(s===t.CONV_PINED){const{RecentContactList:t}=e.RecentContactTopItem;Sa.handleConversationPinned(t,!0)}if(s===t.CONV_UNPINED){const{RecentContactList:t}=e.RecentContactTopItem;Sa.handleConversationPinned(t,!1)}})}_onC2CMessageReadSync(e){const{C2cNotifyMsgArray:t=[]}=e;Ea.handleC2CMessageReadSync(t)}_onC2CMessageRemindTypeSync(e){const{C2cNotifyMsgArray:t=[]}=e;Aa.handleC2CMessageRemindTypeSync(t)}_onGroupMessageReadSync(e){const{GroupTips:t=[]}=e;Ea.handleGroupMessageReadSync(t)}_dispose(){const{notificationCenter:e,InnerEvent:{MESSAGE_PUSH:t,DESTROY:s}}=this._core,{InnerEventSubType:{CONV_MODIFIED:n,C2C_MESSAGE_READ_SYNC:o,GROUP_MESSAGE_READ_SYNC:i,C2C_REMIND_TYPE_SYNC:r}}=e;e.unSubscribeInnerEvent(t,n,this._onConversationModified,this),e.unSubscribeInnerEvent(t,o,this._onC2CMessageReadSync,this),e.unSubscribeInnerEvent(t,r,this._onC2CMessageRemindTypeSync,this),e.unSubscribeInnerEvent(t,i,this._onGroupMessageReadSync,this),e.unSubscribeInnerEvent(s,this._dispose,this)}};var Ra=new class{init(e){this._core=e;const{helper:t}=e;t.registerApi({apiName:"setAllReceiveMessageOpt",context:this})}setAllReceiveMessageOpt(e){return de(this,void 0,void 0,function*(){try{const{OuterConstant:{MSG_REMIND_ACPT_NOT_NOTE:t}}=this._core,{messageRemindType:s=t,isRepeated:n=!0}=e,{startTime:o=0,endTime:i=0}=this._calcStartAndEndTime(e),r=yield function(e){return de(this,void 0,void 0,function*(){const{common:t}=ea.core,{startTime:s,endTime:n,isRepeated:o,messageRemindType:i}=e,r={StartTime:s,EndTime:n,IsRepeated:o,Level:i};return t.buildAndSendPacket({servcmd:"im_msg_db_logic.ws_set_do_not_disturb",data:r})})}({messageRemindType:this._getType(s),startTime:o,endTime:i,isRepeated:n?ua.ON:ua.OFF});return{code:0,data:{errorCode:r.ErrorCode,errorInfo:r.ErrorInfo}}}catch(e){aa("setAllReceiveMessageOpt",e)}})}_calcStartAndEndTime(e){const{startHour:t=0,startMinute:s=0,startSecond:n=0,duration:o=0,isRepeated:i=!0}=e,r=new Date,a=new Date(r.getFullYear(),r.getMonth(),r.getDate(),t,s,n),c=Math.round(a.getTime()/1e3);let u=c+o;return i&&o>=86400&&(u=c+86400),{startTime:c,endTime:u}}_getType(e){const{OuterConstant:t}=this._core;return{[t.MSG_REMIND_ACPT_AND_NOTE]:0,[t.MSG_REMIND_DISCARD]:1,[t.MSG_REMIND_ACPT_NOT_NOTE]:2}[e]}};var Da=new class{init(e){this._core=e;const{helper:t,notificationCenter:s,InnerEvent:n}=e;t.registerApi({apiName:"getAllReceiveMessageOpt",context:this}),s.subscribeInnerEvent(n.MESSAGE_PUSH,s.InnerEventSubType.ALL_RECEIVE_MESSAGE_OPTION,this.onAllReceiveMsgOptionNotify,this)}onAllReceiveMsgOptionNotify(e){const t=this._handleResult(e),{notificationCenter:s,OuterEvent:{ALL_RECEIVE_MESSAGE_OPT_UPDATED:n}}=this._core;s.emitOuterEvent(n,{name:n,data:t})}getAllReceiveMessageOpt(){return de(this,void 0,void 0,function*(){try{const e=yield function(){return de(this,void 0,void 0,function*(){const{common:e}=ea.core,t={To_Account:e.getCurrentUserID()};return e.buildAndSendPacket({servcmd:"im_msg_db_logic.ws_get_do_not_disturb",data:t})})}();return{code:0,data:this._handleResult(e)}}catch(e){aa("getAllReceiveMessageOpt",e)}})}_handleResult(e){const{OuterConstant:t}=this._core,{MSG_REMIND_ACPT_AND_NOTE:s,MSG_REMIND_DISCARD:n,MSG_REMIND_ACPT_NOT_NOTE:o}=t,i={0:s,1:n,2:o},{Level:r,StartTime:a,EndTime:c,IsRepeated:u}=e;return{messageRemindType:i[r]||s,startTime:a,endTime:c,isRepeated:u===ua.ON}}};var ba=new class{init(e){e.ssoLog.debug("ReceiveMessageOptions.init"),this._core=e,ya.init(e),Oa.init(e),ma.init(e),va.init(e),Ra.init(e),Da.init(e)}};const Na=e=>!ta(e)&&!sa(e)&&!na(e),La={getConversationProfile:[{key:"conversationID",required:!0,rules:["string"],allowEmpty:!1,customValidator:e=>!Na(e)||"conversationID is invalid."}],setMessageRead:{conversationID:{required:!0,rules:["string"],allowEmpty:!1,customValidator:e=>!Na(e)||"conversationID is invalid."}},pinConversation:{conversationID:{required:!0,rules:["string"],allowEmpty:!1,customValidator:e=>!Na(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:n}}}=ea;if(!n(e)&&!s(e))return"options is String or Object.";if(n(e)&&Na(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(Na(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=>!(!ta(e)&&!sa(e))||"conversationID is invalid."},draftText:{required:!0,rules:["string"],allowEmpty:!0}},setAllReceiveMessageOpt:{messageRemindType:{required:!1,rules:["string"],allowEmpty:!0},startHour:{required:!1,rules:["number"],allowEmpty:!0},startMinute:{required:!1,rules:["number"],allowEmpty:!0},startSecond:{required:!1,rules:["number"],allowEmpty:!0},duration:{required:!1,rules:["number"],allowEmpty:!0},isRepeated:{required:!1,rules:["boolean"],allowEmpty:!0}}},Pa={getConversationList:!0,getConversationProfile:!0,getTotalUnreadCount:!0,setMessageRead:!0,pinConversation:!0,deleteConversation:!0,setConversationDraft:!0,setMessageRemindType:!0,getAllReceiveMessageOpt:!0,setAllReceiveMessageOpt:!0};var wa=new class{constructor(){this.name="Conversation"}install(e){ea.init(e),Ta.init(e),ba.init(e),pa.init(e),e.helper.registerValidateConfig({auth:Pa,params:La})}};const Ga=new class{init(e){this.core=e}},Ua="AVChatRoom",ka="AV_HISTORY_MSG",Fa="GRP_COUNTER",$a="Set",qa="Increase",xa="Decrease",Va=0,Ba=1,ja=2,Ka=["Type","Name","Introduction","Notification","FaceUrl","Owner_Account","CreateTime","InfoSeq","LastInfoTime","LastMsgTime","MemberNum","MaxMemberNum","ApplyJoinOption","NextMsgSeq","ShutUpAllMember","InviteJoinOption","LastRecallTime"],Ha=["Type","Name","Introduction","Notification","FaceUrl","CreateTime","Owner_Account","LastInfoTime","LastMsgTime","NextMsgSeq","MemberNum","MaxMemberNum","ApplyJoinOption","InviteJoinOption"],Wa=["Role","JoinTime","MsgFlag","MsgSeq"],Ya=["Role","JoinTime","MsgSeq","MsgFlag","NameCard"],za=0,Ja=1,Qa="notStart",Xa="resolved",Za="rejected",ec=10018,tc=11e3,sc=2,nc=["Owner","Admin","Member"],oc=["Role","JoinTime","NameCard","ShutUpUntil","OnlineStatus"],ic=0,rc=1,ac=2,cc=4,uc=1,lc=2,dc=3,hc=4,gc=5,pc=1,_c=0,mc=4,vc=6,fc=400,Ic=300,Ec={from:!0,groupID:!0,groupName:!0,to:!0},Sc={from:!0,groupID:!0,groupName:!0,to:!0,type:!0},Cc=2,Mc=4,yc=5,Oc=7,Ac=8,Tc=15,Rc=20,Dc=21,bc=2600,Nc=2602,Lc=2603,Pc=2620,wc=2621,Gc=2623,Uc=2660,kc=2661,Fc=2681,$c=2683,qc=2684,xc=2685,Vc=2687,Bc=3122,jc=10018,Kc=e=>e===Ga.core.OuterConstant.GRP_PUBLIC,Hc=e=>e===Ga.core.OuterConstant.GRP_AVCHATROOM,Wc=(e,t)=>{const{isArray:s}=Ga.core.utils;if(!s(e)||!s(t))return!1;let n=!1;return t.forEach(({key:t,value:s})=>{const o=e.find(e=>e.key===t);o?o.value!==s&&(o.value=s,n=!0):(e.push({key:t,value:s}),n=!0)}),n},Yc=e=>{const t=[];if(!e)return t;for(let s=0,n=e.length;s<n;s++){const{Key:n,Value:o}=e[s];t.push({key:n,value:o})}return t},zc=e=>{const t=[];for(let s=0,n=e.length;s<n;s++){const{key:n,value:o}=e[s];t.push({Key:n,Value:o})}return t};function Jc(e,t){const{helper:s}=Ga.core;if(!s.checkBusinessCapabilityBits(t))throw new s.ChatError({functionName:e,code:Bc,replacement1:e})}function Qc(e,t){const{helper:s}=Ga.core,n=new s.ChatError({functionName:e,code:(null==t?void 0:t.errorCode)||(null==t?void 0:t.code),message:(null==t?void 0:t.errorInfo)||(null==t?void 0:t.message)});throw console.error(`${e} fail:`,n),n}const Xc=["groupID","name","avatar","type","introduction","notification","ownerID","selfInfo","createTime","infoSequence","lastInfoTime","lastMessage","nextMessageSeq","memberCount","maxMemberCount","memberList","joinOption","groupCustomField","muteAllMembers","isSupportTopic","inviteOption","_lastRevokedTime","_groupAtInfoList"];class Zc{constructor(e){this.groupID="",this.name="",this.avatar="",this.type="",this.introduction="",this.notification="",this.ownerID="",this.createTime=0,this.selfInfo={messageRemindType:"",joinTime:"",nameCard:"",role:"",userID:"",memberCustomField:void 0,readedSequence:0,excludedUnreadSequenceList:void 0},this.lastMessage={lastTime:0,lastSequence:0,fromAccount:"",messageForShow:""},this.nextMessageSeq=0,this.memberCount=0,this.maxMemberCount=0,this.joinOption="",this.inviteOption="",this.groupCustomField=[],this.muteAllMembers=!1,this.isSupportTopic=!1,this._lastRevokedTime=0,this._groupAtInfoList=[],this._initGroup(e)}_initGroup(e){const{utils:{isString:t}}=Ga.core;for(const s in e)Xc.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:n,isString:o},common:{deepMerge:i}}=Ga.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),o(r.muteAllMembers)&&(r.muteAllMembers="On"===r.muteAllMembers),r.groupCustomField&&Wc(this.groupCustomField,r.groupCustomField),s(r.isSupportTopic)||(this.isSupportTopic=n(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:n,messageRemindType:o,readedSequence:i,excludedUnreadSequenceList:r}=e,{common:{deepMerge:a}}=Ga.core;a(this.selfInfo,{nameCard:t,joinTime:s,role:n,messageRemindType:o,readedSequence:i,excludedUnreadSequenceList:r},[],["",null,void 0,0,NaN])}setSelfNameCard(e){this.selfInfo.nameCard=e}}var eu=new class{constructor(){this._name="GroupDataHandler"}init(e){this._core=e;const{appStore:{groupStore:t}}=e;this._groupMap=t.getGroupMap()}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 Zc(e))});const n=t();for(const[,e]of this._groupMap)e.selfInfo.userID=n,"Owner"===e.selfInfo.role&&(e.ownerID=n)}deleteLocalGroup(e){this._groupMap.delete(e)}getLocalGroupList(){const{OuterConstant:{GRP_ROOM:e,GRP_LIVE:t}}=this._core;return[...this._groupMap.values()].filter(s=>{const{type:n}=s;return n!==e&&n!==t})}clearLocalGroup(){this._groupMap.clear()}emitGroupListUpdate(){const e=this.getLocalGroupList(),{OuterEvent:{GROUP_LIST_UPDATED:t},notificationCenter:s}=this._core;s.emitOuterEvent(t,{name:t,data:e})}updateConversationGroupProfile(e){const{appStore:{conversationStore:t},OuterConstant:{CONV_GROUP:s}}=this._core,n=`${s}${e}`;if(t.getConversation(n)){const s=this.getLocalGroup(e);t.updateConversation(n,{groupProfile:s})}}reset(){this.clearLocalGroup()}};function tu(e,t){return de(this,void 0,void 0,function*(){const{type:s,limit:n,offset:o,supportTopic:i=0,memberAccount:r,responseFilter:a}=e,c={Type:s,Limit:n,Offset:o,Member_Account:r,ResponseFilter:a,SupportTopic:i,NeedAppDefineData:1};return t.common.buildAndSendPacket({servcmd:"group_open_http_svc.get_joined_group_list",data:c})})}const su=function(e,t){return{code:0,data:e||{},successLog:t}};var nu=new class{constructor(){this._name="GetGroupList",this._pagingStatus=Qa,this.PAGING_GRP_COUNT_LIMIT=200}init(e){this._core=e;const{helper:t,constants:{WORKFLOW_NAME:s,WORKFLOW_STEP:n}}=e;t.registerApi({apiName:"getGroupList",context:this}),t.registerWorkflowStep(s.SYNC_SERVER_INFO_AFTER_LOGIN,n.GROUP_LIST_SYNC,this._syncGroupList,this)}getGroupList(){return de(this,arguments,void 0,function*(e=!1){if(e){const e=[];return yield this._pagingGetJoinedCommunityList({limit:this.PAGING_GRP_COUNT_LIMIT,offset:0,groupList:e}),eu.updateLocalGroup(e),eu.getLocalGroupList()}if(this._core.ssoLog.debug("getGroupList",`${this._name}.getGroupList pagingStatus:${this._pagingStatus}`),this._pagingStatus===Za||this._pagingStatus===Qa)return this._syncGroupList().then(()=>{const e=eu.getLocalGroupList();return su({groupList:e,isSyncCompleted:this._isSyncCompleted()})}).catch(e=>{throw e});const t=eu.getLocalGroupList();return su({groupList:t,isSyncCompleted:this._isSyncCompleted()},{message:`return group count:${t.length}`})})}_syncGroupList(){return de(this,void 0,void 0,function*(){this._pagingStatus===Qa&&eu.clearLocalGroup();const e=this.PAGING_GRP_COUNT_LIMIT,t=[];try{yield this._pagingGetGroupList({limit:e,offset:0,groupList:t}),this._pagingStatus=Xa,this._groupListTreeShaking(t),eu.updateLocalGroup(t);const s=eu.getLocalGroupList();return this._core.ssoLog.debug("_syncGroupList",`${this._name}._syncGroupList ok, count:${s.length}`),eu.emitGroupListUpdate(),s}catch(e){throw this._pagingStatus=Za,e}})}_pagingGetGroupList(e){return de(this,void 0,void 0,function*(){const{ssoLog:t}=this._core,{isCommunityRelay:s=!1,groupList:n}=e;let o,{limit:i,offset:r}=e;const a=[...Ka];s&&(o=this._core.OuterConstant.GRP_COMMUNITY,a.push("AtInfoList"));try{const e=yield tu({type:o,limit:i,offset:r,memberAccount:this._core.store.get("login").userId,responseFilter:{GroupBaseInfoFilter:a,SelfInfoFilter:[...Wa]}},this._core),{GroupIdList:c=[],TotalCount:u=0}=e||{},l=this._convertGroupKey(c);n.push(...l);const d=r+i,h=!(u>d),g=`offset:${r} limit:${i} total:${u} isCompleted:${h} current:${n.length} isCommunityRelay:${s}`;return t.debug("_pagingGetGroupList",`${this._name}._pagingGetGroupList ok. ${g}`),s?h?n:(r=d,this._pagingGetGroupList({isCommunityRelay:!0,limit:i,offset:r,groupList:n})):h?(t.debug("_pagingGetGroupList",`${this._name}._pagingGetGroupList start to get community list`),r=0,this._pagingGetGroupList({isCommunityRelay:!0,limit:i,offset:r,groupList:n})):(r=d,this._pagingGetGroupList({limit:i,offset:r,groupList:n}))}catch(e){if(e.ErrorCode===ec)return t.warn("_pagingGetGroupList",`${this._name}._pagingGetGroupList response size exceeds the limit, request count:${i}`),i=50,this._pagingGetGroupList({isCommunityRelay:s,limit:i,offset:r,groupList:n});if(s)return e.code===tc&&t.debug("_pagingGetGroupList",`${this._name}._pagingGetGroupList ok. community unavailable`),n;throw e}})}_pagingGetJoinedCommunityList(e){return de(this,void 0,void 0,function*(){const{common:{getCurrentUserID:t},OuterConstant:s,ssoLog:n}=this._core,{groupList:o}=e;let{limit:i,offset:r}=e;try{const e=yield tu({limit:i,offset:r,type:s.GRP_COMMUNITY,memberAccount:t(),supportTopic:1,responseFilter:{GroupBaseInfoFilter:[...Ka],SelfInfoFilter:[...Wa]}},this._core),{GroupIdList:a=[],TotalCount:c=0}=e||{},u=this._convertGroupKey(a);o.push(...u);const l=r+i,d=!(c>l),h=`offset:${r} limit:${i} total:${c} isCompleted:${d} current:${o.length}`;return n.debug("_pagingGetJoinedCommunityList",`${this._name}._pagingGetJoinedCommunityList ok. ${h}`),d?o:(r=l,this._pagingGetJoinedCommunityList({limit:i,offset:r,groupList:o}))}catch(e){if(e.code===jc)return n.warn("_pagingGetJoinedCommunityList",`${this._name}._pagingGetJoinedCommunityList response size exceeds the limit, request count:${i}`),i=50,this._pagingGetJoinedCommunityList({limit:i,offset:r,groupList:o});throw e}})}_groupListTreeShaking(e){const t=new Map([...eu.getLocalGroupList()]);for(let s=0,n=e.length;s<n;s++)t.delete(e[s].groupID);const s=[...t.keys()];for(let e=0,t=s.length;e<t;e++)eu.deleteLocalGroup(s[e])}_isSyncCompleted(){return this._pagingStatus===Xa}_convertGroupKey(e){const t=[];for(let s=0,n=e.length;s<n;s++){const{AppDefinedData:n,ApplyJoinOption:o,CreateTime:i,FaceUrl:r,GroupId:a,Introduction:c,InviteJoinOption:u,LastInfoTime:l,LastMsgTime:d,MemberNum:h,MaxMemberNum:g,MuteAllMember:p,Name:_,NextMsgSeq:m,Notification:v,Owner_Account:f,Type:I,LastRecallTime:E,SelfInfo:S,AtInfoList:C=[],SupportTopic:M}=e[s],y=Yc(n),O=this._convertSelfInfo(S),A=this._convertAtInfoList(a,C);t.push({groupCustomField:y,joinOption:o,createTime:i,avatar:r,groupID:a,introduction:c,inviteOption:u,lastInfoTime:l,lastMsgTime:d,memberCount:h,maxMemberCount:g,muteAllMembers:p,name:_,nextMessageSeq:m,notification:v,ownerID:f,type:I,selfInfo:O,_lastRevokedTime:E,_groupAtInfoList:A,isSupportTopic:M})}return t}_convertSelfInfo(e){const{JoinTime:t,MsgFlag:s,MsgSeq:n,NoUnreadSeqList:o,Role:i}=e;return{joinTime:t,messageRemindType:s,readedSequence:n,excludedUnreadSequenceList:o,role:i}}_convertAtInfoList(e,t){if(0===t.length)return[];const s=[];return t.forEach(t=>{const{AtFlagList:n,AtMsgSeq:o,From_Account:i}=t;s.push({groupID:e,groupAtType:n,sequence:o,from:i})}),s}};var ou=new class{constructor(){this._name="CreateGroup"}init(e){this._core=e;const{helper:t}=e;t.registerApi({apiName:"createGroup",context:this})}createGroup(e){return de(this,void 0,void 0,function*(){var t;this._preCheckParams(e);const{helper:{ChatError:s}}=this._core;try{const{utils:{isEmpty:s},common:{getCurrentUserID:n}}=this._core,o=yield function(e,t){return de(this,void 0,void 0,function*(){const{name:s,type:n,groupID:o,introduction:i,notification:r,avatar:a,maxMemberNum:c,joinOption:u,inviteOption:l,memberList:d,groupCustomField:h,isSupportTopic:g}=e;let p;d&&(p=d.map(e=>{const{userID:t,memberCustomField:s}=e;return{Member_Account:t,AppMemberDefinedData:s?zc(s):void 0}}));const _={Name:s,Type:n,GroupId:o,Introduction:i,Notification:r,FaceUrl:a,MaxMemberCount:c,ApplyJoinOption:u,InviteJoinOption:l,MemberList:p,AppDefinedData:h,SupportTopic:g,webPushFlag:1};return t.common.buildAndSendPacket({servcmd:"group_open_http_svc.create_group",data:_})})}(Object.assign(Object.assign({},e),{ownerID:n()}),this._core),{GroupId:i,OverJoinedGroupLimit_Account:r=[]}=o||{},a=`${this._name}.createGroup ok, type:${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))),eu.updateLocalGroup([Object.assign(Object.assign({},e),{groupID:i})]);const c=eu.getLocalGroup(i);return this._notNeedSendCustomMessage(e)||(this._sendCustomMessage(i,e.type),eu.emitGroupListUpdate()),su({group:c},{message:a})}catch(t){const{errorCode:n,errorInfo:o}=t;throw new s({functionName:"createGroup",code:n,message:o,moreMessage:` groupID:${e.groupID}`})}})}_preCheckParams(e){const{type:t,groupID:s}=e,{utils:{isEmpty:n,isUndefined:o},common:{isCommunity:i}}=this._core,r=!n(s);if(!(()=>{const{GRP_PUBLIC:e,GRP_WORK:t,GRP_MEETING:s,GRP_AVCHATROOM:n,GRP_COMMUNITY:o}=Ga.core.OuterConstant;return[e,t,s,n,o]})().includes(t))throw new this._core.helper.ChatError({code:bc});if(!i({type:t})){if(r&&i({groupID:s}))throw new this._core.helper.ChatError({code:Nc});o(e.isSupportTopic)||(e.isSupportTopic=void 0)}if(this._canIUseMemberList(t)||o(e.memberList)||(e.memberList=void 0),this._canIUseJoinOption(t)||o(e.joinOption)||(e.joinOption=void 0),i({type:t})){if(r&&!i({groupID:s}))throw new this._core.helper.ChatError({code:Nc});e.isSupportTopic=this._canIUseTopic(e)?1:0}}_canIUseMemberList(e){return!Hc(e)}_canIUseJoinOption(e){return Kc(e)||this._core.common.isCommunity({type:e})}_canIUseTopic(e){const{isSupportTopic:t}=e;return!0===t}_notNeedSendCustomMessage(e){const{type:t,isSupportTopic:s}=e,{OuterConstant:{GRP_AVCHATROOM:n,GRP_COMMUNITY:o}}=this._core;return t===n||t===o&&1===s}_sendCustomMessage(e,t){var s,n,o,i,r,a;const{OuterConstant:c}=this._core;let u="Create Group",l=za;t===c.GRP_COMMUNITY&&(u="Create Community",l=Ja);const d={to:e,conversationType:"GROUP",payload:{data:JSON.stringify({businessID:"group_create",content:u,cmd:l,opUser:this._core.store.get("login").userId,version:4})}},h=null===(o=null===(n=null===(s=this._core)||void 0===s?void 0:s.message)||void 0===n?void 0:n.messageFactory)||void 0===o?void 0:o.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 iu=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:n}}=this._core;return!n(t)&&!s(t.groupAttributeOption)}handleGroupAttributesUpdated(e){const{groupID:t,groupAttributeOption:s}=e,{serverMainSequence:n,groupAttributeList:o=[],operation:i}=s;this._core.ssoLog.debug("handleGroupAttributesUpdated",`${this._name}.handleGroupAttributesUpdated groupID:${t} operation:${i}`);const{utils:{isUndefined:r}}=this._core;r(i)||(this.refreshGroupAttributesCache({groupID:t,serverMainSequence:n,groupAttributeList:o,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}),this._core.ssoLog.debug("initGroupAttributesCache",`${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:n,operation:o}=e;if(this.hasGroupAttributesCache(t)){const e=this.getGroupAttributesCache(t),{localMainSequence:i}=e;o!==gc&&s-i!==1||(e.serverMainSequence=s,e.localMainSequence=s,e.lastUpdateTime=Date.now(),this._updateGroupAttributesCacheValues({groupAttributes:e,groupAttributeList:n,operation:o})),s-i>1&&(e.serverMainSequence=s),this._groupAttributesCache.set(t,e),this._core.ssoLog.debug("refreshGroupAttributesCache",`${this._name}.refreshGroupAttributesCache. operation:${o} localMainSequence:${i} serverMainSequence:${s}`)}}_updateGroupAttributesCacheValues(e){const{groupAttributes:t,groupAttributeList:s=[],operation:n}=e;n!==dc?n!==hc?(n===uc&&t.values.clear(),s.forEach(e=>{const{key:s,value:n,sequence:o}=e;t.values.set(s,{value:n,sequence:o})})):s.forEach(e=>{t.values.delete(e.key)}):t.values.clear()}getGroupAttributesCacheValues(e){var t;const{groupID:s,keyList:n=[]}=e,o={};if(this.hasGroupAttributesCache(s)){const{values:e}=this.getGroupAttributesCache(s);if(0===n.length){for(const s of e.keys())o[s]=(null===(t=e.get(s))||void 0===t?void 0:t.value)||"";return o}return n.forEach(t=>{var s;e.has(t)&&(o[t]=(null===(s=e.get(t))||void 0===s?void 0:s.value)||"")}),o}return o}saveGroupAttributesCacheValuesCopy(e){this._groupAttributesCacheValuesCopy=this.getGroupAttributesCacheValues({groupID:e})}emitGroupAttributesUpdated(e){var t;const s=this.getGroupAttributesCacheValues({groupID:e}),{updatedKeyList:n,deletedKeyList:o}=this._computeValuesChangedData(s);this._core.ssoLog.debug("emitGroupAttributesUpdated",`${this._name}.emitGroupAttributesUpdated update count:${n.length}, delete count:${o.length}`),0===n.length&&0===o.length||this._emitEvent({name:null===(t=this._core)||void 0===t?void 0:t.OuterEvent.GROUP_ATTRIBUTES_UPDATED,data:{groupID:e,groupAttributes:s,updatedKeyList:n,deletedKeyList:o}})}_computeValuesChangedData(e){const{utils:{isUndefined:t}}=this._core,s=[],n=[];return Object.keys(e).forEach(t=>{e[t]!==this._groupAttributesCacheValuesCopy[t]&&s.push(t)}),Object.keys(this._groupAttributesCacheValuesCopy).forEach(s=>{t(e[s])&&n.push(s)}),this._groupAttributesCacheValuesCopy={},{updatedKeyList:s,deletedKeyList:n}}_emitEvent(e){var t;null===(t=this._core)||void 0===t||t.notificationCenter.emitOuterEvent(e.name,e)}convertKeyValueMapToList(e){const t=[];return Object.keys(e).forEach(s=>{t.push({key:s,value:e[s]})}),t}reset(){this._groupAttributesCache.clear(),this._groupAttributesCacheValuesCopy={}}};var ru=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(Ua)})}dismissGroup(e){return de(this,void 0,void 0,function*(){const{helper:{ChatError:t}}=this._core;try{yield function(e,t){return de(this,void 0,void 0,function*(){const s={GroupId:e};return t.common.buildAndSendPacket({servcmd:"group_open_http_svc.destroy_group",data:s})})}(e,this._core);const{type:t}=eu.getLocalGroup(e);return eu.deleteLocalGroup(e),eu.emitGroupListUpdate(),iu.deleteGroupAttributesCache(e),su({groupID:e,type:t},{message:e})}catch(e){const{errorCode:s,errorInfo:n}=e;throw new t({functionName:"dismissGroup",code:s,message:n})}})}};var au=new class{constructor(){this._name="GetGroupProfile"}init(e){this._core=e;const{helper:t}=e;t.registerApi({apiName:"getGroupProfile",context:this})}getGroupProfile(e){return de(this,void 0,void 0,function*(){const{groupID:t,groupCustomFieldFilter:s}=e,n={groupIDList:[t],responseFilter:{GroupBaseInfoFilter:[...Ka],AppDefinedDataFilter_Group:s,MemberInfoFilter:[...Ya]}},{helper:{ChatError:o}}=this._core;try{const e=yield this.getGroupProfileAdvance(n),{successGroupList:s,failureGroupList:o}=e;if(o.length>0)throw o[0];let i;return!eu.hasLocalGroup(t)&&Hc(s[0].type)?i=new Zc(s[0]):(eu.updateLocalGroup(s),i=eu.getLocalGroup(t)),i.isSupportTopic||eu.updateConversationGroupProfile(t),su({group:i},{message:`groupID:${t}`})}catch(e){const{code:t,message:s}=e;throw new o({functionName:"getGroupProfile",code:t,message:s})}})}getGroupProfileAdvance(e){return de(this,void 0,void 0,function*(){const{groupIDList:t}=e,{common:{isCommunity:s}}=this._core,n=t.filter(e=>!s({groupID:e})),o=t.filter(e=>s({groupID:e}));n.length>50&&(n.length=50),o.length>50&&(o.length=50);const i=yield Promise.all([this._getGroupProfileAdvance(Object.assign(Object.assign({},e),{groupIDList:n})),this._getGroupProfileAdvance(Object.assign(Object.assign({},e),{groupIDList:o,isCommunityProfile:!0}))]),r=[],a=[];return i.forEach(e=>{r.push(...e.successGroupList),a.push(...e.failureGroupList)}),{successGroupList:r,failureGroupList:a}})}_getGroupProfileAdvance(e){return de(this,void 0,void 0,function*(){const{ssoLog:t,utils:{isUndefined:s}}=this._core,{isCommunityProfile:n=!1}=e,o=le(e,["isCommunityProfile"]);if(0===o.groupIDList.length)return{successGroupList:[],failureGroupList:[]};try{const e=yield function(e,t){return de(this,void 0,void 0,function*(){const{groupIDList:s,responseFilter:n}=e,o={GroupIdList:s,ResponseFilter:n};return t.common.buildAndSendPacket({servcmd:"group_open_http_svc.get_group_self_member_info",data:o})})}(o,this._core),{GroupInfo:n=[]}=e||{},i=this._convertGroupProfileKey(n),r=i.filter(e=>s(e.errorCode)||0===e.errorCode),a=i.filter(e=>e.errorCode&&0!==e.errorCode).map(e=>({code:e.errorCode,message:e.errorInfo,data:{groupID:e.groupID}}));return t.debug("_getGroupProfileAdvance",`${this._name}._getGroupProfileAdvance ok, groupID:${o.groupIDList.join(",")}`),{successGroupList:r,failureGroupList:a}}catch(e){if(n)return{successGroupList:[],failureGroupList:[]};throw e}})}_convertGroupProfileKey(e){const t=[];for(let s=0,n=e.length;s<n;s++){const{AppDefinedData:n,ApplyJoinOption:o,CreateTime:i,FaceUrl:r,GroupId:a,InfoSeq:c,Introduction:u,InviteJoinOption:l,LastInfoTime:d,LastMsgTime:h,MaxMemberNum:g,MemberNum:p,MuteAllMember:_,Name:m,NextMsgSeq:v,Notification:f,Owner_Account:I,ShutUpAllMember:E,ShutUpUntil:S,Type:C,MemberList:M,ErrorCode:y,ErrorInfo:O}=e[s],A=Yc(n),T=this._convertMembers(M);t.push({groupCustomField:A,joinOption:o,createTime:i,avatar:r,groupID:a,infoSequence:c,introduction:u,inviteOption:l,lastInfoTime:d,lastMsgTime:h,maxMemberCount:g,memberCount:p,muteAllMembers:_,name:m,nextMessageSeq:v,notification:f,ownerID:I,shutUpAllMember:E,muteUntil:S,type:C,members:T,errorCode:y,errorInfo:O})}return t}_convertMembers(e){if(!e)return[];const t=[];for(let s=0,n=e.length;s<n;s++){const{AppMemberDefinedData:n,JoinTime:o,Member_Account:i,MsgFlag:r,MsgSeq:a,NameCard:c,Role:u}=e[s],l=Yc(n);t.push({memberCustomField:l,joinTime:o,userID:i,messageRemindType:r,sequence:a,nameCard:c,role:u})}return t}};var cu=new class{constructor(){this._groupCountersMap=new Map}init(e){this._core=e}getLocalGroupCounters(e){return this._hasLocalGroupCounters(e)||this.initGroupCountersCache({groupID:e}),this._groupCountersMap.get(e)}updateLocalGroupCounters(e){const{groupID:t,counterList:s=[],groupCounterSeq:n}=e;if(this._hasLocalGroupCounters(t)){const{counters:e,avChatRoomKey:o,groupCounterSeq:i}=this.getLocalGroupCounters(t);if(n>0&&n<i)return;s.forEach(t=>{const{Key:s,Value:n=0}=t;e.set(s,n)}),this._groupCountersMap.set(t,{lastUpdateTime:Date.now(),groupCounterSeq:n,counters:e,avChatRoomKey:o})}}initGroupCountersCache(e){const{groupID:t,avChatRoomKey:s}=e;this._groupCountersMap.set(t,{lastUpdateTime:0,groupCounterSeq:0,counters:new Map,avChatRoomKey:s})}getLocalCounters(e,t){const s={};if(!this._hasLocalGroupCounters(e))return s;const{counters:n}=this.getLocalGroupCounters(e);if(t.length>0)t.forEach(e=>{n.has(e)&&(s[e]=n.get(e))});else for(const e of n.keys())s[e]=n.get(e);return s}deleteLocalGroupCounters(e){const{groupID:t,counterList:s=[],groupCounterSeq:n}=e;if(this._hasLocalGroupCounters(t)){const{counters:e,avChatRoomKey:o}=this.getLocalGroupCounters(t);s.forEach(t=>{e.delete(t.key)}),this._groupCountersMap.set(t,{lastUpdateTime:Date.now(),groupCounterSeq:n,counters:e,avChatRoomKey:o})}}setGroupCounters(e,t){if(!this._hasLocalGroupCounters(e))return;const s=this.getLocalGroupCounters(e),{counters:n}=s;let o=!1;Object.entries(t).forEach(([e,t])=>{n.has(e)&&n.get(e)!==t&&(n.set(e,t),o=!0)}),o&&this._groupCountersMap.set(e,Object.assign(Object.assign({},s),{lastUpdateTime:Date.now(),counters:n}))}_hasLocalGroupCounters(e){return this._groupCountersMap.has(e)}reset(){this._groupCountersMap.clear()}};var uu=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(Ua)})}joinGroup(e){return de(this,void 0,void 0,function*(){const{groupID:t}=e,{helper:{ChatError:s},OuterConstant:n,ssoLog:o}=this._core;try{if(eu.hasLocalGroup(t))try{return yield au.getGroupProfile({groupID:t}),su({status:n.JOIN_STATUS_ALREADY_IN_GROUP,group:eu.getLocalGroup(t)},{message:`groupID:${t} joinedStatus:${n.JOIN_STATUS_ALREADY_IN_GROUP}`})}catch(s){o.warn("joinGroup",`${this._name}.joinGroup ${t} was unjoined, start to join!`),eu.deleteLocalGroup(t);return yield this._applyJoinGroup(e)}return yield this._applyJoinGroup(e)}catch(e){const{errorCode:n,errorInfo:o}=e;throw new s({functionName:"joinGroup",code:n,message:o,moreMessage:`groupID:${t}`})}})}_applyJoinGroup(e){return de(this,void 0,void 0,function*(){const{OuterConstant:t,helper:s,ssoLog:n}=this._core,{groupID:o}=e,i=Object.assign({},e),r=s.checkBusinessCapabilityBits(ka);r&&(i.historyMessageFlag=1);const a=yield function(e,t){return de(this,void 0,void 0,function*(){const{groupID:s,applyMessage:n,historyMessageFlag:o}=e,i={GroupId:s,ApplyMsg:n,HugeGroupHistoryMsgFlag:o};return t.common.buildAndSendPacket({servcmd:"group_open_http_svc.apply_join_group",data:i})})}(i,this._core),{Type:c,JoinedStatus:u,LongPollingKey:l,StartSeq:d,HugeGroupFlag:h,AVChatRoomKey:g,RspMsgList:p=[]}=a||{},_=`groupID:${o} joinedStatus:${u} longPollingKey:${l} startSeq:${d} avChatRoomFlag:${h} canGetAVChatRoomHistoryMsg:${r}, historyMessageCount:${p.length}`;n.debug("_applyJoinGroup",`${this._name}._applyJoinGroup ok, ${_}`);let m=new Zc({groupID:o,type:c});if(u===t.JOIN_STATUS_WAIT_APPROVAL)return su({status:t.JOIN_STATUS_WAIT_APPROVAL,group:m});if(u===t.JOIN_STATUS_SUCCESS){try{m=(yield au.getGroupProfile({groupID:o})).data.group}catch(e){n.warn("_applyJoinGroup",`${this._name}._applyJoinGroup getGroupProfile failed, groupID: ${o}, errorCode:${null==e?void 0:e.code}`)}return this._handleJoinResult({group:m,avChatRoomFlag:h,longPollingKey:l,startSequence:d,avChatRoomKey:g,historyMessageList:p})}throw new this._core.helper.ChatError({code:Uc})})}_handleJoinResult(e){const{group:t,avChatRoomFlag:s,avChatRoomKey:n}=e;return 1===s?(iu.initGroupAttributesCache({groupID:t.groupID,avChatRoomKey:n}),cu.initGroupCountersCache({groupID:t.groupID,avChatRoomKey:n}),su(e)):(eu.updateLocalGroup([t]),eu.emitGroupListUpdate(),su({status:this._core.OuterConstant.JOIN_STATUS_SUCCESS,group:t},{message:`groupID:${t.groupID}`}))}};var lu=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(Ua)})}quitGroup(e){return de(this,void 0,void 0,function*(){if(!eu.hasLocalGroup(e))throw new this._core.helper.ChatError({code:Gc});const{helper:{ChatError:t}}=this._core;try{yield function(e,t){return de(this,void 0,void 0,function*(){const s={GroupId:e};return t.common.buildAndSendPacket({servcmd:"group_open_http_svc.quit_group",data:s})})}(e,this._core);const{type:t}=eu.getLocalGroup(e);return eu.deleteLocalGroup(e),eu.emitGroupListUpdate(),iu.deleteGroupAttributesCache(e),su({groupID:e,type:t},{message:`groupID:${e}`})}catch(s){const{errorCode:n,errorInfo:o}=s;throw new t({functionName:"quitGroup",code:n,message:o,moreMessage:`groupID:${e}`})}})}};var du=new class{constructor(){this._name="SearchGroup"}init(e){this._core=e;const{helper:t}=e;t.registerApi({apiName:"searchGroupByID",context:this})}searchGroupByID(e){return de(this,void 0,void 0,function*(){try{const t=yield function(e,t){return de(this,void 0,void 0,function*(){const s={GroupIdList:[e],GroupBasePublicInfoFilter:[...Ha]};return t.common.buildAndSendPacket({servcmd:"group_open_http_svc.get_group_public_info",data:s})})}(e,this._core),{GroupInfo:s=[]}=t||{},{AppDefinedData:n=[],ApplyJoinOption:o,CreateTime:i,FaceUrl:r,Introduction:a,InviteJoinOption:c,MaxMemberNum:u,MemberNum:l,Name:d,Owner_Account:h,Type:g,ErrorCode:p,ErrorInfo:_}=s[0];if(0!==p)throw new this._core.helper.ChatError({code:p,message:_});const m=Yc(n),v=new Zc({groupID:e,name:d,avatar:r,introduction:a,joinOption:o,inviteOption:c,maxMemberCount:u,memberCount:l,type:g,ownerID:h,createTime:i,groupCustomField:m});return su({group:v})}catch(e){const{errorCode:t,errorInfo:s}=e;throw new this._core.helper.ChatError({functionName:"searchGroupByID",code:t,message:s})}})}};var hu=new class{constructor(){this._name="UpdateGroupProfile"}init(e){this._core=e;const{helper:t}=e;t.registerApi({apiName:"updateGroupProfile",context:this})}updateGroupProfile(e){return de(this,void 0,void 0,function*(){const{groupID:t}=e,{utils:{isUndefined:s},ssoLog:n,helper:o}=this._core;let i=eu.getLocalGroup(t);if(i){const{type:o}=i;this._canIUseJoinOption(o)||s(e.joinOption)||(n.warn("updateGroupProfile",`${this._name}.updateGroupProfile groupID:${t} 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 de(this,void 0,void 0,function*(){const{groupID:s,name:n,avatar:o,introduction:i,notification:r,muteAllMembers:a,joinOption:c,inviteOption:u,groupCustomField:l}=e,d={GroupId:s,Name:n,FaceUrl:o,Introduction:i,Notification:r,ShutUpAllMember:a,ApplyJoinOption:c,InviteJoinOption:u,AppDefinedData:l?zc(l):void 0};return t.common.buildAndSendPacket({servcmd:"group_open_http_svc.modify_group_base_info",data:d})})}(e,this._core),i?(i.updateGroup(e),eu.emitGroupListUpdate()):i=new Zc(e),su({group:i},{message:`groupID:${t}`})}catch(e){const{errorCode:s,errorInfo:n}=e;throw new o.ChatError({code:s,message:n,moreMessage:`groupID:${t}`})}})}_canIUseJoinOption(e){return Kc(e)||this._core.common.isCommunity({type:e})}};var gu=new class{constructor(){this._name="ChangeGroupOwner"}init(e){this._core=e;const{helper:t}=e;t.registerApi({apiName:"changeGroupOwner",context:this})}changeGroupOwner(e){return de(this,void 0,void 0,function*(){const t="changeGroupOwner",{groupID:s,newOwnerID:n}=e,o=eu.getLocalGroup(s),{helper:i,OuterConstant:r,common:{getCurrentUserID:a}}=this._core;if((null==o?void 0:o.type)===r.GRP_AVCHATROOM)throw new i.ChatError({functionName:t,code:Pc});if(n===a())throw new i.ChatError({functionName:t,code:wc});try{return yield function(e,t){return de(this,void 0,void 0,function*(){const{groupID:s,newOwnerID:n}=e,o={GroupId:s,NewOwner_Account:n};return t.common.buildAndSendPacket({servcmd:"group_open_http_svc.change_group_owner",data:o})})}(e,this._core),o.ownerID=n,eu.emitGroupListUpdate(),su({group:o})}catch(e){throw new i.ChatError({functionName:t,code:null==e?void 0:e.errorCode,message:null==e?void 0:e.errorInfo})}})}};var pu=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(Ua)})}getGroupOnlineMemberCount(e){return de(this,void 0,void 0,function*(){const t="getGroupOnlineMemberCount";if(!eu.hasLocalGroup(e))return su({memberCount:0});const s=Date.now();if(this._onlineMemberCountMap.has(e)){const t=this._onlineMemberCountMap.get(e),{lastReqTime:n=0,memberCount:o=0}=t||{};if(s-n<=6e4)return su({memberCount:o})}try{const s=yield function(e,t){return de(this,void 0,void 0,function*(){const s={GroupId:e};return t.common.buildAndSendPacket({servcmd:"group_open_http_svc.get_online_member_num",data:s})})}(e,this._core),{OnlineMemberNum:n=0}=s||{};this._onlineMemberCountMap.set(e,{lastReqTime:Date.now(),memberCount:n});const o=`${this._name}.${t} ok. groupID:${e} memberCount:${n}`;return su({memberCount:n},{message:o})}catch(e){throw new this._core.helper.ChatError({functionName:t,code:null==e?void 0:e.errorCode,message:null==e?void 0:e.errorInfo})}})}};var _u=new class{init(e,t){e.ssoLog.debug("GroupAction.init"),nu.init(e),ou.init(e),ru.init(e,t),uu.init(e,t),lu.init(e,t),du.init(e),au.init(e),hu.init(e),gu.init(e),pu.init(e,t)}dismissGroup(e){return ru.dismissGroup(e)}joinGroup(e){return uu.joinGroup(e)}quitGroup(e){return lu.quitGroup(e)}getGroupOnlineMemberCount(e){return pu.getGroupOnlineMemberCount(e)}};var mu=new class{constructor(){this._name="GetGroupApplicationList"}init(e){this._core=e;const{helper:t}=e;t.registerApi({apiName:"getGroupApplicationList",context:this})}getGroupApplicationList(){return de(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})]);this._core.ssoLog.debug("getGroupApplicationList",`${this._name}.${e} ok.`);const s=this._handleGroupApplicationResult([...t[0],...t[1]]);return su({applicationList:s})}catch(t){throw new this._core.helper.ChatError({functionName:e,code:null==t?void 0:t.errorCode,message:null==t?void 0:t.errorInfo})}})}_getGroupApplicationList(e){return de(this,void 0,void 0,function*(){const{type:t,startTime:s=0,limit:n=20}=e||{},{common:o}=this._core;let i;try{i=yield function(e,t){return de(this,void 0,void 0,function*(){const{type:s,startTime:n,limit:o,handleAccount:i}=e,r={Type:s,StartTime:n,Limit:o,Handle_Account:i};return t.common.buildAndSendPacket({servcmd:"group_open_http_svc.get_pendency",data:r})})}({type:t,startTime:s,limit:n,handleAccount:o.getCurrentUserID()},this._core)}catch(e){if(11e3!==(null==e?void 0:e.errorCode))throw e;i={}}const{NextStartTime:r=0,PendencyList:a=[]}=i||{};if(0===r)return a;const c=yield this._getGroupApplicationList(Object.assign(Object.assign({},e),{startTime:r}));return[...a,...c]})}_handleGroupApplicationResult(e){const t=[];return e.forEach(e=>{const s=this._convertApplicationData(e),{handled:n}=s,o=le(s,["handled"]);0===n&&t.push(o)}),t}_convertApplicationData(e){const{Handled:t,AddTime:s,ApplyInviteMsg:n,Authentication:o,FromUserNickName:i,From_Account:r,GroupId:a,GroupName:c,PendencyType:u,To_Account:l}=e;return{handled:t,messageKey:s,applicant:r,applicantNick:i,groupID:a,groupName:c,authentication:o,applicationType:u,userID:l,note:n}}};var vu=new class{constructor(){this._name="HandleGroupApplication"}init(e){this._core=e;const{helper:t}=e;t.registerApi({apiName:"handleGroupApplication",context:this})}handleGroupApplication(e){return de(this,void 0,void 0,function*(){const{application:t}=e,s=this._handleParams(e);try{(null==t?void 0:t.applicationType)===sc?yield function(e,t){return de(this,void 0,void 0,function*(){const{groupID:s,handleAction:n,handleMessage:o,applicant:i,authentication:r,invitee:a}=e,c={GroupId:s,HandleMsg:n,ApprovalMsg:o,Applicant_Account:i,Authentication:r,Invited_Account:a};return t.common.buildAndSendPacket({servcmd:"group_open_http_svc.handle_invite_join_permission_group",data:c})})}(s,this._core):yield function(e,t){return de(this,void 0,void 0,function*(){const{groupID:s,handleAction:n,handleMessage:o,applicant:i,authentication:r,messageKey:a}=e,c={GroupId:s,HandleMsg:n,ApprovalMsg:o,Applicant_Account:i,Authentication:r,MsgKey:a};return t.common.buildAndSendPacket({servcmd:"group_open_http_svc.handle_apply_join_group",data:c})})}(s,this._core);const e=eu.getLocalGroup(s.groupID);return su({group:e})}catch(e){throw new this._core.helper.ChatError({functionName:"handleGroupApplication",code:null==e?void 0:e.errorCode,message:null==e?void 0:e.errorInfo})}})}_handleParams(e){var t;const{handleAction:s,handleMessage:n,message:o,application:i}=e;let r,a,c,u,l;if(o){const{payload:e}=o||{};r=e.operatorID,a=null===(t=e.groupProfile)||void 0===t?void 0:t.groupID,c=e.authentication,u=e.messageKey}else r=(null==i?void 0:i.applicant)||"",a=(null==i?void 0:i.groupID)||"",c=(null==i?void 0:i.authentication)||"",u=(null==i?void 0:i.messageKey)||0;return(null==i?void 0:i.applicationType)===sc&&(l=i.userID),{handleAction:s,handleMessage:n,applicant:r,invitee:l,groupID:a,authentication:c,messageKey:u}}};var fu=new class{init(e){e.ssoLog.debug("GroupApplication.init"),mu.init(e),vu.init(e)}};let Iu=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}}}=Ga;t(e.muteTime)||(this.muteUntil=Math.floor((Date.now()+1e3*e.muteTime)/1e3)),t(e.onlineStatus)||(this.isOnline="Online"===e.onlineStatus);const n=[null,void 0,"",0,NaN];e.memberCustomField&&Wc(this.memberCustomField,e.memberCustomField),s(this,e,["memberCustomField","marks","onlineStatus","muteTime"],n)}};function Eu(e,t){return de(this,void 0,void 0,function*(){const{groupID:s,userID:n,muteTime:o,role:i,nameCard:r,memberCustomField:a}=e;let c;a&&(c=zc(a));const u={GroupId:s,Member_Account:n,ShutUpTime:o,Role:i,NameCard:r,AppMemberDefinedData:c};return t.common.buildAndSendPacket({servcmd:"group_open_http_svc.modify_group_member_info",data:u})})}var Su=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(Ua)})}getGroupMemberList(e){return de(this,void 0,void 0,function*(){const t="getGroupMemberList",{groupID:s,offset:n=0,count:o=100,role:i="",filter:r=""}=e,a=eu.getLocalGroup(s),c=o>100?100:o,u={groupID:s,offset:n,limit:c,memberRoleFilter:nc.includes(i)?[i]:void 0,memberInfoFilter:oc};try{const e=yield function(e,t){return de(this,void 0,void 0,function*(){const{isCommunity:s}=t.common,{groupID:n,offset:o,limit:i,memberRoleFilter:r,memberInfoFilter:a}=e,c={GroupId:n,Limit:i,MemberRoleFilter:r,MemberInfoFilter:a};return s({groupID:n})?c.Next=String(o):c.Offset=o,t.common.buildAndSendPacket({servcmd:"group_open_http_svc.get_group_member_info",data:c})})}(u,this._core),{MemberList:o,MemberNum:i,Next:r}=e||{},l=`${this._name}.${t} ok, totalMemberCount:${i} next:${r}`,{utils:{isArray:d,isEmpty:h},common:{isCommunity:g}}=this._core;if(a&&(a.memberCount=i),!d(o)||0===o.length)return su({memberList:[],offset:0},{message:l});let p=n+c;g({groupID:s})&&(p=h(r)?0:r),o.length<c&&(p=0);let _=this._convertMemberInfo(o);_=yield this._patchAvatarAndNick(_);const m=this._generateGroupMember(_);return su({memberList:m,offset:p},{message:l})}catch(e){throw new this._core.helper.ChatError({functionName:t,code:null==e?void 0:e.errorCode,message:null==e?void 0:e.errorInfo})}})}_convertMemberInfo(e){const t=[];for(let s=0,n=e.length;s<n;s++){const{AppMemberDefinedData:n,JoinTime:o,Member_Account:i,OnlineStatus:r,Role:a,ShutUpUntil:c,NameCard:u}=e[s],l=Yc(n);t.push({userID:i,joinTime:o,onlineStatus:r,role:a,muteUntil:c,memberCustomField:l,nameCard:u})}return t}_patchAvatarAndNick(e){return de(this,void 0,void 0,function*(){var t;const s=e.map(e=>e.userID),n=yield null===(t=this._core.user.userProfile)||void 0===t?void 0:t.getUserProfile({userIDList:s}),o=(null==n?void 0:n.data)||[],i=new Map(o.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,n=e.length;s<n;s++){const n=new Iu(e[s]);t.push(n)}return t}};var Cu=new class{constructor(){this._name="GetGroupMemberProfile"}init(e){this._core=e;const{helper:t}=e;t.registerApi({apiName:"getGroupMemberProfile",context:this})}getGroupMemberProfile(e){return de(this,void 0,void 0,function*(){const t="getGroupMemberProfile",{groupID:s,userIDList:n,memberCustomFieldFilter:o}=e,i=eu.getLocalGroup(s),{helper:r,utils:{isArray:a},ssoLog:c}=this._core;if(i&&Hc(i.type))throw new r.ChatError({functionName:t,replacement1:t,code:Vc});n.length>50&&(c.warn("getGroupMemberProfile",`${this._name}.${t} userIDList length:${n.length} exceeds limit 50`),n.splice(50));const u=`userIDList length:${n.length} groupID:${s}`;try{const e=yield function(e,t){return de(this,void 0,void 0,function*(){const{groupID:s,userIDList:n,memberInfoFilter:o,memberCustomFieldFilter:i}=e,r={GroupId:s,Member_List_Account:n,MemberInfoFilter:o,AppDefinedDataFilter_GroupMember:i};return t.common.buildAndSendPacket({servcmd:"group_open_http_svc.get_specified_group_member_info",data:r})})}({groupID:s,userIDList:n,memberCustomFieldFilter:o,memberInfoFilter:[...oc]},this._core),{MemberList:t}=e||{};if(!a(t)||0===t.length)return su({memberList:[]});let i=this._convertMemberInfo(t);i=yield this._getMemberAvatarAndNick(i);const r=this._generateGroupMember(i);return su({memberList:r},{message:u})}catch(e){throw new r.ChatError({functionName:t,code:null==e?void 0:e.errorCode,message:null==e?void 0:e.errorInfo,moreMessage:u})}})}_convertMemberInfo(e){const t=[];for(let s=0,n=e.length;s<n;s++){const{AppMemberDefinedData:n,JoinTime:o,Member_Account:i,OnlineStatus:r,Role:a,ShutUpUntil:c,NameCard:u}=e[s],l=Yc(n);t.push({userID:i,joinTime:o,onlineStatus:r,role:a,muteUntil:c,memberCustomField:l,nameCard:u})}return t}_getMemberAvatarAndNick(e){return de(this,void 0,void 0,function*(){var t;const s=e.map(e=>e.userID),n=yield null===(t=this._core.user.userProfile)||void 0===t?void 0:t.getUserProfile({userIDList:s}),o=(null==n?void 0:n.data)||[],i=new Map(o.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,n=e.length;s<n;s++){const n=new Iu(e[s]);t.push(n)}return t}};var Mu=new class{constructor(){this._name="AddGroupMember"}init(e){this._core=e;const{helper:t}=e;t.registerApi({apiName:"addGroupMember",context:this})}addGroupMember(e){return de(this,void 0,void 0,function*(){const t="addGroupMember",{groupID:s,userIDList:n}=e,o=eu.getLocalGroup(s),{helper:i}=this._core;if(o&&Hc(o.type))throw new i.ChatError({functionName:t,code:kc});const r=n.map(e=>({Member_Account:e}));try{const e=yield function(e,t){return de(this,void 0,void 0,function*(){const{groupID:s,userIDList:n}=e,o={GroupId:s,MemberList:n};return t.common.buildAndSendPacket({servcmd:"group_open_http_svc.add_group_member",data:o})})}({groupID:s,userIDList:r},this._core),{MemberList:t=[]}=e||{},{failureUserIDList:n,successUserIDList:i,existedUserIDList:a,overLimitUserIDList:c}=this._handleResult(t);return su({failureUserIDList:n,successUserIDList:i,existedUserIDList:a,overLimitUserIDList:c,group:o},{message:` groupID:${s} successUserIDList:${i} failureUserIDList:${n} existedUserIDList:${a} overLimitUserIDList:${c}`})}catch(e){throw new i.ChatError({functionName:t,code:null==e?void 0:e.errorCode,message:null==e?void 0:e.errorInfo})}})}_handleResult(e){const t=[],s=[],n=[],o=[];return e.forEach(e=>{const{Result:i,Member_Account:r}=e;i===ic?t.push(r):i===rc?s.push(r):i===ac?n.push(r):i===cc&&o.push(r)}),{failureUserIDList:t,successUserIDList:s,existedUserIDList:n,overLimitUserIDList:o}}};var yu=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(Ua)})}deleteGroupMember(e){return de(this,void 0,void 0,function*(){const t="deleteGroupMember",{groupID:s,userIDList:n}=e,o=eu.getLocalGroup(s),{helper:i,utils:{isUndefined:r},ssoLog:a}=this._core;if(r(o))throw new i.ChatError({functionName:t,code:Lc});n.length>20&&(a.warn("deleteGroupMember",`${this._name}.${t} userIDList length:${n.length} exceeds limit 20`),n.splice(20));try{return yield function(e,t){return de(this,void 0,void 0,function*(){const{groupID:s,userIDList:n,reason:o}=e,i={GroupId:s,MemberToDel_Account:n,Reason:o};return t.common.buildAndSendPacket({servcmd:"group_open_http_svc.delete_group_member",data:i})})}({groupID:s,userIDList:n},this._core),su({group:o,userIDList:n},{message:`groupID:${s} userIDList length:${n.length}`})}catch(e){throw new i.ChatError({functionName:t,code:null==e?void 0:e.errorCode,message:null==e?void 0:e.errorInfo})}})}};var Ou=new class{constructor(){this._name="SetGroupMemberMuteTime"}init(e){this._core=e;const{helper:t}=e;t.registerApi({apiName:"setGroupMemberMuteTime",context:this})}setGroupMemberMuteTime(e){return de(this,void 0,void 0,function*(){const{helper:t}=this._core,{groupID:s,userID:n,muteTime:o}=e,i=` groupID:${s} userID:${n} muteTime:${o}`;this._preCheckSettingMuteParams(e);try{yield Eu(e,this._core);const t=eu.getLocalGroup(s),r=new Iu({userID:n,muteTime:o});return su({group:t,member:r},{message:i})}catch(e){throw new t.ChatError({functionName:"setGroupMemberMuteTime",code:null==e?void 0:e.errorCode,message:null==e?void 0:e.errorInfo,moreMessage:i})}})}_preCheckSettingMuteParams(e){const{userID:t}=e,{store:s,helper:n}=this._core;if(t===s.get("login").userId)throw new n.ChatError({functionName:"setGroupMemberMuteTime",code:xc})}};var Au=new class{constructor(){this._name="SetGroupMemberRole"}init(e){this._core=e;const{helper:t}=e;t.registerApi({apiName:"setGroupMemberRole",context:this})}setGroupMemberRole(e){return de(this,void 0,void 0,function*(){const t="setGroupMemberRole",{helper:s}=this._core,{groupID:n,userID:o,role:i}=e,r=`${this._name}.${t} ok, groupID:${n} userID:${o} role:${i}`;this._preCheckSettingRoleParams(e);try{yield Eu(e,this._core);const t=eu.getLocalGroup(n),s=new Iu({userID:o,role:i});return su({group:t,member:s},{message:r})}catch(e){throw new s.ChatError({functionName:t,code:null==e?void 0:e.errorCode,message:null==e?void 0:e.errorInfo,moreMessage:r})}})}_preCheckSettingRoleParams(e){var t;const{groupID:s,userID:n,role:o}=e,{store:i,helper:r,OuterConstant:a,common:{isCommunity:c}}=this._core,u=eu.getLocalGroup(s);if((null===(t=null==u?void 0:u.selfInfo)||void 0===t?void 0:t.role)!==a.GRP_MBR_ROLE_OWNER)throw new r.ChatError({functionName:"setGroupMemberRole",code:Fc});if(n===i.get("login").userId)throw new r.ChatError({functionName:"setGroupMemberRole",code:qc});const l=[...nc];if(c({groupID:s})&&l.push(a.GRP_MBR_ROLE_CUSTOM),!l.includes(o))throw new r.ChatError({functionName:"setGroupMemberRole",code:$c})}};var Tu=new class{constructor(){this._name="SetGroupMemberNameCard"}init(e){this._core=e;const{helper:t}=e;t.registerApi({apiName:"setGroupMemberNameCard",context:this})}setGroupMemberNameCard(e){return de(this,void 0,void 0,function*(){const t="setGroupMemberNameCard",{helper:s,common:{getCurrentUserID:n}}=this._core;this._preCheckSettingNameCardParams(e);try{const{groupID:s,userID:o=n(),nameCard:i}=e,r={groupID:s,userID:o,nameCard:i};yield Eu(r,this._core);const a=`${this._name}.${t} ok, groupID:${s} userID:${o} nameCard:${i}`,c=eu.getLocalGroup(s),u=new Iu({userID:o,nameCard:i});return su({group:c,member:u},{message:a})}catch(e){throw new s.ChatError({functionName:t,code:null==e?void 0:e.errorCode,message:null==e?void 0:e.errorInfo,moreMessage:logText})}})}_preCheckSettingNameCardParams(e){const{groupID:t}=e,{helper:s}=this._core,n=eu.getLocalGroup(t);if(Hc(null==n?void 0:n.type))throw new s.ChatError({functionName:"setGroupMemberNameCard",code:Vc})}};var Ru=new class{constructor(){this._name="SetGroupMemberCustomField"}init(e){this._core=e;const{helper:t}=e;t.registerApi({apiName:"setGroupMemberCustomField",context:this})}setGroupMemberCustomField(e){return de(this,void 0,void 0,function*(){const t="setGroupMemberCustomField",{helper:s,common:{getCurrentUserID:n}}=this._core;this._preCheckSettingCustomFiledParams(e);const{groupID:o,userID:i=n(),memberCustomField:r}=e,a=`${this._name}.${t} ok, groupID:${o}userID:${i} memberCustomField:${JSON.stringify(r)}`;try{const e={groupID:o,userID:i,memberCustomField:r};yield Eu(e,this._core);const t=eu.getLocalGroup(o),s=new Iu({userID:i,memberCustomField:r});return su({group:t,member:s},{message:a})}catch(e){throw new s.ChatError({functionName:t,code:null==e?void 0:e.errorCode,message:null==e?void 0:e.errorInfo,moreMessage:a})}})}_preCheckSettingCustomFiledParams(e){const{groupID:t}=e,{helper:s}=this._core,n=eu.getLocalGroup(t);if(Hc(null==n?void 0:n.type))throw new s.ChatError({functionName:"setGroupMemberCustomField",code:Vc})}};var Du=new class{init(e,t){e.ssoLog.debug("GroupMember.init"),Su.init(e,t),Cu.init(e),Mu.init(e),yu.init(e,t),Ou.init(e),Au.init(e),Tu.init(e),Ru.init(e)}getGroupMemberList(e){return Su.getGroupMemberList(e)}deleteGroupMember(e){return yu.deleteGroupMember(e)}};var bu=new class{init(e){this._core=e;const{helper:t}=e;t.registerApi({apiName:"getGroupCounters",context:this})}getGroupCounters(e){return de(this,void 0,void 0,function*(){const t="getGroupCounters";try{Jc(t,Fa);const{groupID:s,keyList:n=[]}=e,{avChatRoomKey:o,lastUpdateTime:i}=cu.getLocalGroupCounters(s);if(!(Date.now()-i>=this._getExpireTime())){return{code:0,data:{counters:cu.getLocalCounters(s,n)}}}const r=yield function(e){return de(this,void 0,void 0,function*(){const{groupID:t,GroupCounterKeys:s,avChatRoomKey:n}=e,{common:o}=Ga.core,i={GroupId:t,keyList:s,BytesKey:n};return o.buildAndSendPacket({servcmd:"group_open_http_svc.get_group_counter",data:i})})}({groupID:s,keyList:n,avChatRoomKey:o}),{GroupCounter:a=[],GroupCounterSeq:c}=r;cu.updateLocalGroupCounters({groupID:s,counterList:a,groupCounterSeq:c});return{code:0,data:{counters:cu.getLocalCounters(s,n)}}}catch(e){Qc(t,e)}})}_getExpireTime(){const{store:e,utils:{isUndefined:t}}=this._core,s=e.get("cloudConfig")||{},{grp_counter_expire_time:n}=s;return t(n)?3e4:Number(n)}};var Nu=new class{init(e){const{helper:t}=e;t.registerApi({apiName:"setGroupCounters",context:this}),t.registerApi({apiName:"increaseGroupCounter",context:this}),t.registerApi({apiName:"decreaseGroupCounter",context:this})}setGroupCounters(e){return de(this,void 0,void 0,function*(){return this._handleCounterOperation($a,e)})}increaseGroupCounter(e){return de(this,void 0,void 0,function*(){return this._handleCounterOperation(qa,e)})}decreaseGroupCounter(e){return de(this,void 0,void 0,function*(){return this._handleCounterOperation(xa,e)})}_handleCounterOperation(e,t){return de(this,void 0,void 0,function*(){const s=`${e}GroupCounter`;try{Jc(s,Fa);const{groupID:n,key:o,value:i=0}=t,{avChatRoomKey:r}=cu.getLocalGroupCounters(n),a=e===$a?this._convertObjectToList(t.counters):[{Key:o,Value:i}],c=yield this._updateGroupCounters({groupID:n,counterList:a,avChatRoomKey:r,mode:e});return cu.setGroupCounters(n,c),{code:0,data:{counters:c}}}catch(e){Qc(s,e)}})}_updateGroupCounters(e){return de(this,void 0,void 0,function*(){const t=yield function(e){const{groupID:t,counterList:s,mode:n,avChatRoomKey:o}=e,{common:i}=Ga.core,r={GroupId:t,GroupCounter:s,Mode:n,BytesKey:o};return i.buildAndSendPacket({servcmd:"group_open_http_svc.update_group_counter",data:r})}(e),{GroupCounter:s=[]}=t,n={};return s.forEach(e=>{const{Key:t,Value:s=0}=e;n[t]=s}),n})}_convertObjectToList(e){return Object.entries(e).map(([e,t])=>({Key:e,Value:t||0}))}};var Lu=new class{init(e){this._core=e,bu.init(e),Nu.init(e)}isGroupCounterUpdated(e){const{elements:{groupCounterInfo:t}}=e,{utils:{isEmpty:s}}=this._core;return!s(t)}handleGroupCounterUpdated(e){const{to:t,elements:{groupCounterInfo:s}}=e;s.forEach(e=>{const{type:s,groupCounterSeq:n,counterList:o=[]}=e;s!==Va&&s!==ja||this._processAndNotifyCounterUpdate(t,n,o),s===Ba&&cu.deleteLocalGroupCounters({groupID:t,groupCounterSeq:n,counterList:o})})}_processAndNotifyCounterUpdate(e,t,s){const{OuterEvent:n,notificationCenter:o}=this._core;cu.updateLocalGroupCounters({groupID:e,groupCounterSeq:t,counterList:s}),s.forEach(({Key:t,Value:s=0})=>{o.emitOuterEvent(n.GROUP_COUNTER_UPDATED,{name:n.GROUP_COUNTER_UPDATED,data:{groupID:e,key:t,value:s}})})}reset(){cu.reset()}};var Pu=new class{constructor(){this._name="InitGroupAttributes"}init(e){this._core=e;const{helper:t}=e;t.registerApi({apiName:"initGroupAttributes",context:this})}initGroupAttributes(e){return de(this,void 0,void 0,function*(){const{groupID:t,groupAttributes:s}=e,{serverMainSequence:n,avChatRoomKey:o}=iu.getGroupAttributesCache(t),i=iu.convertKeyValueMapToList(s);try{const e=yield function(e,t){return de(this,void 0,void 0,function*(){const{groupID:s,mainSequence:n,groupAttributeList:o,avChatRoomKey:i}=e,r={GroupId:s,AttrMainSeq:n,GroupAttr:o,BytesKey:i,AttrControl:["RaceConflict"]};return t.common.buildAndSendPacket({servcmd:"group_open_http_svc.set_group_attr",data:r})})}({groupID:t,avChatRoomKey:o,groupAttributeList:i,mainSequence:n},this._core),{AttrMainSeq:r,GroupAttr:a}=e||{},c=a.map(e=>{const{Key:t,seq:n}=e;return{key:t,value:s[t],sequence:n}});return iu.saveGroupAttributesCacheValuesCopy(t),iu.refreshGroupAttributesCache({groupID:t,serverMainSequence:r,groupAttributeList:c,operation:uc}),iu.emitGroupAttributesUpdated(t),su({groupAttributes:s},{message:` groupID:${t} serverMainSequence:${r}`})}catch(e){throw new this._core.helper.ChatError({functionName:"initGroupAttributes",code:null==e?void 0:e.errorCode,message:null==e?void 0:e.errorInfo})}})}};var wu=new class{constructor(){this._name="SetGroupAttributes"}init(e){this._core=e;const{helper:t}=e;t.registerApi({apiName:"setGroupAttributes",context:this})}setGroupAttributes(e){return de(this,void 0,void 0,function*(){const{groupID:t,groupAttributes:s}=e,{serverMainSequence:n,avChatRoomKey:o,values:i}=iu.getGroupAttributesCache(t),r=iu.convertKeyValueMapToList(s).map(e=>{var t;const{key:s,value:n}=e;return{key:s,value:n,seq:(null===(t=i.get(e.key))||void 0===t?void 0:t.sequence)||0}});try{const e=yield function(e,t){return de(this,void 0,void 0,function*(){const{groupID:s,mainSequence:n,groupAttributeList:o,avChatRoomKey:i}=e,r={GroupId:s,AttrMainSeq:n,GroupAttr:o,BytesKey:i,AttrControl:["RaceConflict"]};return t.common.buildAndSendPacket({servcmd:"group_open_http_svc.modify_group_attr",data:r})})}({groupID:t,avChatRoomKey:o,groupAttributeList:r,mainSequence:n},this._core),{AttrMainSeq:i,GroupAttr:a}=e||{},c=a.map(e=>{const{Key:t,seq:n}=e;return{key:t,value:s[t],sequence:n}});return iu.saveGroupAttributesCacheValuesCopy(t),iu.refreshGroupAttributesCache({groupID:t,serverMainSequence:i,groupAttributeList:c,operation:lc}),iu.emitGroupAttributesUpdated(t),su({groupAttributes:s},{message:` groupID:${t} serverMainSequence:${i}`})}catch(e){throw new this._core.helper.ChatError({functionName:"setGroupAttributes",code:null==e?void 0:e.errorCode,message:null==e?void 0:e.errorInfo})}})}};var Gu=new class{constructor(){this._name="DeleteGroupAttributes"}init(e){this._core=e;const{helper:t}=e;t.registerApi({apiName:"deleteGroupAttributes",context:this})}deleteGroupAttributes(e){return de(this,void 0,void 0,function*(){const t="deleteGroupAttributes",{groupID:s,keyList:n=[]}=e;try{let e;e=0===n.length?yield this._clearGroupAttributes(s):yield this._deleteGroupAttributes(s,n);const{resultList:o,serverMainSequence:i,operation:r,groupAttributeList:a}=e||{},c=`${this._name}.${t} ok. groupID:${s} operation: ${r}`;return iu.saveGroupAttributesCacheValuesCopy(s),iu.refreshGroupAttributesCache({groupID:s,serverMainSequence:i,groupAttributeList:a,operation:r}),iu.emitGroupAttributesUpdated(s),su({keyList:o},{message:c})}catch(e){throw new this._core.helper.ChatError({functionName:t,code:null==e?void 0:e.errorCode,message:null==e?void 0:e.errorInfo})}})}_deleteGroupAttributes(e,t){return de(this,void 0,void 0,function*(){const{serverMainSequence:s,avChatRoomKey:n,values:o}=iu.getGroupAttributesCache(e),i=[],r=[];t.forEach(e=>{if(o.has(e)){const{sequence:t=0}=o.get(e)||{};r.push({key:e,seq:t}),i.push(e)}});const a=yield function(e,t){return de(this,void 0,void 0,function*(){const{groupID:s,mainSequence:n,groupAttributeList:o,avChatRoomKey:i}=e,r={GroupId:s,AttrMainSeq:n,GroupAttr:o,BytesKey:i,AttrControl:["RaceConflict"]};return t.common.buildAndSendPacket({servcmd:"group_open_http_svc.delete_group_attr",data:r})})}({groupID:e,avChatRoomKey:n,groupAttributeList:r,mainSequence:s},this._core),{AttrMainSeq:c}=a||{};return{resultList:i,serverMainSequence:c,groupAttributeList:r,operation:hc}})}_clearGroupAttributes(e){return de(this,void 0,void 0,function*(){const{serverMainSequence:t,avChatRoomKey:s,values:n}=iu.getGroupAttributesCache(e),o=[...n.keys()],i=yield function(e,t){return de(this,void 0,void 0,function*(){const{groupID:s,mainSequence:n,avChatRoomKey:o}=e,i={GroupId:s,AttrMainSeq:n,BytesKey:o,AttrControl:["RaceConflict"]};return t.common.buildAndSendPacket({servcmd:"group_open_http_svc.clear_group_attr",data:i})})}({groupID:e,avChatRoomKey:s,mainSequence:t},this._core),{AttrMainSeq:r}=i||{};return{resultList:o,serverMainSequence:r,operation:dc}})}};var Uu=new class{constructor(){this._name="GetGroupAttributes"}init(e){this._core=e;const{helper:t}=e;t.registerApi({apiName:"getGroupAttributes",context:this})}getGroupAttributes(e){return de(this,void 0,void 0,function*(){const{groupID:t}=e,{avChatRoomKey:s,lastUpdateTime:n,localMainSequence:o,serverMainSequence:i}=iu.getGroupAttributesCache(t),{helper:{ChatError:r}}=this._core,a=`groupID:${t} localMainSequence:${o} serverMainSequence:${i} keyList:${e.keyList}`;if(Date.now()-n>=3e4||o<i)try{const n=yield this.getGroupAttributesFromServer({groupID:t,avChatRoomKey:s}),o=iu.getGroupAttributesCacheValues(e),{serverGroupAttributeList:i=[]}=n||{};return su({groupAttributes:o},{message:a,moreMessage:`from server, count:${i.length}`})}catch(e){throw new r({functionName:"getGroupAttributes",code:null==e?void 0:e.errorCode,message:null==e?void 0:e.errorInfo})}const c=iu.getGroupAttributesCacheValues(e);return su({groupAttributes:c},{message:a,moreMessage:"from cache"})})}getGroupAttributesFromServer(e){return de(this,void 0,void 0,function*(){const{utils:{isUndefined:t},ssoLog:s}=this._core,{groupID:n,avChatRoomKey:o}=e,i=t(o)?_c:pc,r=yield function(e,t){return de(this,void 0,void 0,function*(){const{groupID:s,groupType:n,avChatRoomKey:o}=e,i={GroupId:s,GroupType:n,Key:o};return t.common.buildAndSendPacket({servcmd:"group_open_attr_http_svc.get_group_attr",data:i})})}({groupID:n,avChatRoomKey:o,groupType:i},this._core),{AttrMainSeq:a=0,GroupAttrAry:c}=r||{};s.debug("getGroupAttributesFromServer",`${this._name}._getGroupAttributesFromServer ok. groupID:${n} serverMainSequence:${a}`);const u=c.map(e=>{const{key:t,value:s,seq:n}=e;return{key:t,value:s,sequence:n}});return iu.refreshGroupAttributesCache({groupID:n,serverMainSequence:a,groupAttributeList:u,operation:gc}),{serverGroupAttributeList:c}})}};var ku=new class{init(e){e.ssoLog.debug("GroupAttribute.init"),Pu.init(e),wu.init(e),Gu.init(e),Uu.init(e),iu.init(e)}isGroupAttributesUpdated(e){return iu.isGroupAttributesUpdated(e)}handleGroupAttributesUpdated(e){const{to:t,elements:{newGroupProfile:s}}=e,{groupAttributeOption:n}=s,{serverMainSequence:o,withChangedAttributeInfo:i}=n,{localMainSequence:r}=iu.getGroupAttributesCache(t),a=o-r;if(console.log(`GroupAttribute.handleGroupAttributesUpdated groupID:${t} withChangedAttributeInfo:${i} diffSequence:${a}`),0!==a)if(iu.saveGroupAttributesCacheValuesCopy(t),1!==i||1!==a){if(iu.hasGroupAttributesCache(t)){const{avChatRoomKey:e}=iu.getGroupAttributesCache(t);Uu.getGroupAttributesFromServer({groupID:t,avChatRoomKey:e}).then(()=>{iu.emitGroupAttributesUpdated(t)}).catch(()=>{})}}else iu.handleGroupAttributesUpdated({groupID:t,groupAttributeOption:n})}reset(){iu.reset()}};function Fu(e,t="tips"){const{ClientSeq:s,From_Account:n,MsgClientTime:o,MsgPriority:i,MsgRandom:r,MsgSeq:a,MsgTimeStamp:c,TinyId:u,ToGroupId:l,GroupInfo:d,MsgBody:h}=e,g=function(e){const{GroupCode:t,GroupId:s,GroupName:n,GroupType:o,MsgFrom_AccountExtraInfo:i,From_Account:r,To_Account:a}=e;return{groupCode:t,groupID:s,groupName:n,type:o,messageFromAccountExtraInformation:i,from:r,to:a}}(d);return{clientSequence:s,from:n,clientTime:o,priority:i,random:r,sequence:a,time:c,tinyID:u,to:l,groupProfile:g,elements:"tips"===t?$u(h):xu(h)}}function $u(e){const t={};return Object.keys(e).forEach(s=>{var n,o;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=null===(n=e[s])||void 0===n?void 0:n.map(e=>qu(e));break;case"MsgOperatorMemberExtraInfo":t.operatorInfo=qu(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:n,PushChangedAttrValFlag:o,GroupAttrInfo:i}=e,r=i.map(e=>{const{Key:t,Val:s,SubKeySeq:n}=e;return{key:t,value:s,sequence:n}});return{changedKeyList:t,groupAttributeList:r,serverMainSequence:s,operation:n,withChangedAttributeInfo:o}}(e[s])}}),t}(e[s]);break;case"MsgMemberInfo":t.msgMemberInfo=null===(o=e[s])||void 0===o?void 0:o.map(e=>function(e){const{ShutupTime:t,User_Account:s}=e;return{muteTime:t,userID:s}}(e));break;case"OnlineMemberInfo":t.onlineMemberInfo=function(e){const{ExpireTime:t,OnlineMemberNum:s}=e;return{expireTime:t,onlineMemberNum:s}}(e[s]);break;case"GroupCounterInfo":t.groupCounterInfo=function(e){return e.map(e=>{const{GroupCounterSeq:t,GroupCounter:s,Type:n}=e;return{type:n,groupCounterSeq:t,counterList:s}})}(e[s])}}),t}function qu(e){const{ImageUrl:t,NickName:s,Role:n,UserId:o}=e;return{avatar:t,nick:s,role:n,userID:o}}function xu(e){const t={};return Object.keys(e).forEach(s=>{switch(s){case"MsgKey":t.messageKey=e[s];break;case"Operator_Account":t.operatorID=e[s];break;case"ReportType":t.operationType=e[s];break;case"Authentication":t.authentication=e[s];break;case"MsgFlag":t.messageRemindType=e[s];break;case"UserDefinedField":t.userDefinedField=e[s];break;case"RemarkInfo":t.remarkInfo=e[s];break;case"BanDuration":t.duration=e[s];break;case"MuteTime":t.muteTime=e[s]}}),t}class Vu{constructor(e){this.type=Ga.core.OuterConstant.MSG_GRP_TIP,this.content={},this._initContent(e)}static parseServerPushElement(e){const t=$u(e);return new Vu(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 n=t[s];Ec[n]&&(this.content.groupProfile[n]=e[n])}}_initOperatorInfo(e){this.content.operatorInfo={};const t=Object.keys(e);for(let s=0;s<t.length;s++){const n=t[s];this.content.operatorInfo[n]=e[n]}}_updateMemberList(e){this.content.memberList?this.content.memberList.forEach(t=>{e.forEach(e=>{t.userID===e.userID&&Object.assign(t,e)})}):this.content.memberList=e}_initNewGroupProfile(e){this.content.newGroupProfile={};const t=Object.keys(e);for(let s=0;s<t.length;s++){const n=t[s];"muteAllMembers"!==n?this.content.newGroupProfile[n]=e[n]:this.content.newGroupProfile.muteAllMembers=1===e.muteAllMembers}}}var Bu=new class{constructor(){this._name="GroupTipsNotification"}init(e){this._core=e;const{common:{workflowManager:t},constants:{WORKFLOW_NAME:s,WORKFLOW_STEP:n}}=e,{message:{messageFactory:o},OuterConstant:i}=e;null==o||o.registerElementClass(i.MSG_GRP_TIP,Vu),t.registerWorkflowStep(s.SYNC_SERVER_INFO_AFTER_RE_ONLINE,n.GROUP_TIPS_RECOVER,this._handleGroupTipsRecover,this),t.registerWorkflowStep(s.RECEIVE_GROUP_TIPS_NOTIFICATION,n.HANDLE_GROUP_TIPS_NOTIFICATION,this.onNewGroupTips,this)}onNewGroupTips(e){const{data:t}=e||{},{messageList:s,conversationUpdateFieldList:n}=this._handleGroupTips(t),{notificationCenter:o,OuterEvent:i,appStore:{conversationStore:r}}=this._core;return null==n||n.forEach(e=>{const{conversationID:t,lastMessage:s,unreadCount:n}=e,{unreadCount:o=0}=r.getConversation(t)||{};r.updateConversation(t,{lastMessage:s,unreadCount:n+o})}),s.length>0&&(o.emitOuterEvent(i.MESSAGE_RECEIVED,{name:i.MESSAGE_RECEIVED,data:s}),this._handleGroupTipMessage(s)),{conversationUpdateFieldList:n}}_handleGroupTips(e,t=!0){const{Event:s,GroupTips:n}=e,o=new Map,i=[],r=[];for(let e=0,i=n.length;e<i;e++){const i=Fu(n[e],"tips");if(s===vc){if(ku.isGroupAttributesUpdated(i)){ku.handleGroupAttributesUpdated(i);continue}if(Lu.isGroupCounterUpdated(i)){Lu.handleGroupCounterUpdated(i);continue}}const{groupProfile:{groupID:a}}=i;if(!eu.hasLocalGroup(a))continue;const c=this._assembleMessage(i);if(s===vc&&(c._onlineOnlyFlag=!0,r.push(c)),s===mc){if(!this._core.message.messageDataHandler.storeConversationMessage(c)&&t)continue;r.push(c)}this._handleConversationOptions(o,c)}return i.push(...o.values()),{conversationUpdateFieldList:i,messageList:r}}_assembleMessage(e){const{OuterConstant:t,message:{messageFactory:s}}=this._core;e.flow="in",e.conversationType=t.CONV_GROUP;const n=s.createMessage(e);this._patchNickAndAvatar(e.elements,n);const o=new Vu(Object.assign(Object.assign({},e.elements),{groupProfile:Object.assign({},e.groupProfile)}));return n.setElement(o),n.isSystemMessage=!1,n}_patchNickAndAvatar(e,t){const{utils:{isEmpty:s},OuterConstant:{GROUP_TIPS_OPERATION_TYPE:n}}=this._core,{operationType:o,memberInfoList:i,operatorInfo:r}=e;let a={};if(s(i)?s(r)||(a=r):o!==n.JOINED&&o!==n.KICKED&&o!==n.ADMIN_SET&&o!==n.ADMIN_CANCELED||(a=Object.assign({},i[0])),!s(a)){const{nick:e="",avatar:s=""}=a;t.nick=e,t.avatar=s}}_handleConversationOptions(e,t){const{common:{getMessagePreviewText:s},utils:{isObject:n}}=this._core,{conversationID:o,conversationType:i}=t;let r;if(e.has(o))r=e.get(o),"in"===t.flow&&(t._isExcludedFromUnreadCount||t._onlineOnlyFlag||r.unreadCount++),r.type=i,r.lastMessage=t._isExcludedFromLastMessage?"":Object.assign({},t);else{let e=0;"in"===t.flow&&(t._isExcludedFromUnreadCount||t._onlineOnlyFlag||(e=1)),r={conversationID:o,unreadCount:e,type:i,lastMessage:t._isExcludedFromLastMessage?"":Object.assign({},t)}}n(r.lastMessage)&&(r.lastMessage.messageForShow=s(r.lastMessage.type,r.lastMessage.payload)),e.set(o,r)}_handleGroupTipMessage(e){const{OuterConstant:{GROUP_TIPS_OPERATION_TYPE:t}}=this._core;e.forEach(e=>{const{operationType:s}=e.payload;switch(s){case t.JOINED:this._handleNewMemberJoined(e);break;case t.QUITTED:this._handleMemberQuitted(e);break;case t.KICKED:this._handleMemberKicked(e);break;case t.GROUP_PROFILE_UPDATED:this._handleGroupProfileUpdated(e)}})}_handleNewMemberJoined(e){this._handleGroupMemberCountUpdated(e)}_handleMemberQuitted(e){this._handleGroupMemberCountUpdated(e)}_handleMemberKicked(e){this._handleGroupMemberCountUpdated(e)}_handleGroupProfileUpdated(e){var t;const{newGroupProfile:s,groupProfile:n,operatorInfo:o}=e.payload,{groupID:i}=n,r=eu.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(o)||(null===(t=null==r?void 0:r.selfInfo)||void 0===t?void 0:t.userID)!==o.userID||Object.keys(o).forEach(e=>{"nameCard"===e&&r.updateSelfInfo({nameCard:o[e]}),"role"===e&&this._updateSelfRole(r,o[e])}),eu.emitGroupListUpdate(),eu.updateConversationGroupProfile(i)}_handleGroupOwnerChanged(e,t){const{common:s,OuterConstant:n}=this._core,o=eu.getLocalGroup(e),i=s.getCurrentUserID(),{ownerID:r}=t;i===r&&o.updateGroup({ownerID:r,selfInfo:{role:n.GRP_MBR_ROLE_OWNER}})}_updateSelfRole(e,t){const{OuterConstant:s}=this._core;let n=s.GRP_MBR_ROLE_MEMBER;t===fc?n=s.GRP_MBR_ROLE_OWNER:t===Ic&&(n=s.GRP_MBR_ROLE_ADMIN),e.updateSelfInfo({role:n})}_handleGroupMemberCountUpdated(e){const{memberCount:t,groupProfile:{groupID:s}}=e.payload,n=eu.getLocalGroup(s),{utils:{isNumber:o}}=this._core;n&&o(t)&&n.memberCount!==t&&(n.memberCount=t,eu.emitGroupListUpdate(),eu.updateConversationGroupProfile(s))}_handleGroupTipsRecover(e){const{utils:{isArray:t}}=this._core,{groupTipList:s}=(null==e?void 0:e.result)||{};t(s)&&s.forEach(e=>{const{messageList:t}=this._handleGroupTips({Event:e.Event,GroupTips:[e]},!1);this._handleGroupTipMessage(t)})}};class ju{constructor(e){this.type=Ga.core.OuterConstant.MSG_GRP_SYS_NOTICE,this.content={},this._initContent(e)}static parseServerPushElement(e){const t=xu(e);return new ju(t)}_initContent(e){Object.keys(e).forEach(t=>{switch(t){case"remarkInfo":this.content.handleMessage=e[t];break;case"groupProfile":this._initGroupProfile(e[t]);break;case"memberInfoList":break;default:this.content[t]=e[t]}})}_initGroupProfile(e){this.content.groupProfile={};const t=Object.keys(e);for(let s=0;s<t.length;s++){const n=t[s];Sc[n]&&(this.content.groupProfile[n]=e[n])}}}var Ku=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,ju)}onNewGroupSystemNotification(e){const{GroupTips:t=[],isInstantMessage:s=!0}=e;this._core.ssoLog.debug("onNewGroupSystemNotification",` count:${t.length} isInstantMessage:${s}`);const{conversationUpdateFieldList:n,messageList:o}=this._handleGroupSystemNotification(t,s),{notificationCenter:i,OuterEvent:r}=this._core;n.length>0&&this._handleGroupSysTemMessage(s,o),!0===s&&o.length>0&&i.emitOuterEvent(r.MESSAGE_RECEIVED,{name:r.MESSAGE_RECEIVED,data:o})}_handleGroupSystemNotification(e,t){const s=[];let n={};for(let o=0;o<e.length;o++){const i=Fu(e[o],"system"),{elements:{operationType:r}}=i;if(r===Tc)continue;const a=this._assembleMessage(i);this._core.message.messageDataHandler.storeConversationMessage(a)&&(s.push(a),n=this._handleConversationOptions(a,t))}return n.lastMessage=s[s.length-1],{conversationUpdateFieldList:s.length>0?[n]:[],messageList:s}}_assembleMessage(e){const{message:{messageFactory:t},OuterConstant:s,utils:{randomInt:n}}=this._core;e.flow="in",e.conversationType=s.CONV_SYSTEM,e.conversationSubType=e.groupProfile.type,e.conversationID=s.CONV_SYSTEM;const o=t.createMessage(e),i=new ju(Object.assign(Object.assign({},e.elements),{groupProfile:Object.assign({},e.groupProfile)}));o.setElement(i),o.isSystemMessage=!0;const r=1===o.sequence&&1===o.random,a=2===o.sequence&&2===o.random;return(r||a)&&(o.sequence=n(),o.random=n(),o.generateMessageID()),o}_handleConversationOptions(e,t){const{OuterConstant:s}=this._core,n={conversationID:s.CONV_SYSTEM,unreadCount:0,type:s.CONV_SYSTEM,subType:e.conversationSubType,lastMessage:null};return t&&n.unreadCount++,n}_handleGroupSysTemMessage(e,t){e&&t.forEach(e=>{const{operationType:t}=e.payload;switch(t){case Cc:this._handleGroupJoinResult(e);break;case Mc:this._handleMemberKicked(e);break;case yc:this._handleGroupDismissed(e);break;case Oc:this._handleGroupInvitedResult(e);break;case Ac:this._handleGroupQuitResult(e);break;case Rc:this._handleMessageRemindTypeSynced(e);break;case Dc:this._handleAVChatRoomMemberBanned(e)}})}_handleGroupJoinResult(e){const{groupProfile:t}=e.payload,{groupID:s,type:n}=t,o=eu.hasLocalGroup(s);this._core.ssoLog.debug("_handleGroupJoinResult",` groupID:${s} type:${n} hasLocalGroup:${o}`),o||Hc(n)||(eu.updateLocalGroup([Object.assign({},t)]),eu.emitGroupListUpdate())}_handleMemberKicked(e){const{groupProfile:{groupID:t,type:s}}=e.payload;eu.hasLocalGroup(t)&&this._deleteLocalGroup(t,s),this._updateConversationProfile(t,{unreadCount:0})}_handleGroupDismissed(e){const{groupProfile:{groupID:t,type:s}}=e.payload;eu.hasLocalGroup(t)&&this._deleteLocalGroup(t,s),this._updateConversationProfile(t,{unreadCount:0})}_handleGroupInvitedResult(e){const{groupProfile:t}=e.payload,{groupID:s}=t,n=eu.hasLocalGroup(s);this._core.ssoLog.debug("_handleGroupInvitedResult",` groupID:${s} hasLocalGroup:${n}`),n||au.getGroupProfile({groupID:s}).then(e=>{const{data:{group:t}}=e;eu.updateLocalGroup([Object.assign({},t)]),eu.emitGroupListUpdate()})}_handleGroupQuitResult(e){const{groupProfile:{groupID:t,type:s}}=e.payload,n=eu.hasLocalGroup(t);this._core.ssoLog.debug("_handleGroupQuitResult",` groupID:${t} type:${s} hasLocalGroup:${n}`),n&&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(Hc(t)){const{appStore:{conversationStore:t},OuterConstant:{CONV_GROUP:s}}=this._core;t.deleteConversation(`${s}${e}`)}eu.deleteLocalGroup(e),eu.emitGroupListUpdate()}_updateConversationProfile(e,t){const{appStore:{conversationStore:s},OuterConstant:{CONV_GROUP:n}}=this._core,o=`${n}${e}`;s.getConversation(o)&&s.updateConversation(o,t)}};var Hu=new class{init(e){this._core=e,e.ssoLog.debug("GroupNotificationHandler.init"),Bu.init(e),Ku.init(e);const{notificationCenter:t,InnerEvent:s}=e,{InnerEventSubType:n}=t;t.subscribeInnerEvent(s.MESSAGE_PUSH,n.GROUP_TIPS_NOTIFICATION,this._onNewGroupTipsNotification,this),t.subscribeInnerEvent(s.MESSAGE_PUSH,n.GROUP_SYSTEM_NOTIFICATION,this._onNewGroupSystemNotification,this),t.subscribeInnerEvent(s.DESTROY,this._dispose,this)}_onNewGroupTipsNotification(e){const{common:{workflowManager:t},constants:{WORKFLOW_NAME:s}}=this._core;t.executeWorkflow(s.RECEIVE_GROUP_TIPS_NOTIFICATION,e)}_onNewGroupSystemNotification(e){Ku.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 Wu={required:!0,rules:["string"],allowEmpty:!1},Yu={required:!0,rules:["number"],allowEmpty:!1},zu={required:!0,rules:["array"],allowEmpty:!1},Ju={required:!0,rules:["object"],allowEmpty:!1},Qu={createGroup:{name:Wu,type:Wu},dismissGroup:[Object.assign({key:"groupID"},Wu)],joinGroup:{groupID:Wu,applyMessage:{required:!1,rules:["string"],allowEmpty:!0}},quitGroup:[Object.assign({key:"groupID"},Wu)],searchGroupByID:[Object.assign({key:"groupID"},Wu)],getGroupProfile:{groupID:Wu,groupCustomFieldFilter:{required:!1,rules:["array"],allowEmpty:!0}},updateGroupProfile:{groupID:Wu,muteAllMembers:{required:!1,rules:["boolean"],allowEmpty:!1}},changeGroupOwner:{groupID:Wu,newOwnerID:Wu},getGroupOnlineMemberCount:[Object.assign({key:"groupID"},Wu)],handleGroupApplication:{handleAction:Wu},getGroupMemberList:{groupID:Wu},getGroupMemberProfile:{groupID:Wu,userIDList:zu,memberCustomFieldFilter:{required:!1,rules:["array"],allowEmpty:!0}},addGroupMember:{groupID:Wu,userIDList:zu},deleteGroupMember:{groupID:Wu,userIDList:zu},setGroupMemberMuteTime:{groupID:Wu,userID:Wu,muteTime:Object.assign(Object.assign({},Yu),{customValidator:e=>!(e<0)||"muteTime must be a non-negative number."})},setGroupMemberRole:{groupID:Wu,userID:Wu,role:Wu},setGroupMemberNameCard:{groupID:Wu,userID:{required:!1,rules:["string"],allowEmpty:!1},nameCard:Wu},setGroupMemberCustomField:{groupID:Wu,userID:{required:!1,rules:["string"],allowEmpty:!1},memberCustomField:zu},markGroupMemberList:{groupID:Wu,markType:Object.assign(Object.assign({},Yu),{customValidator:e=>!(e<1e3)||"markType must be greater than or equal to 1000."}),enableMark:{required:!0,rules:["boolean"],allowEmpty:!1},userIDList:zu},initGroupAttributes:{groupID:Wu,groupAttributes:Ju},setGroupAttributes:{groupID:Wu,groupAttributes:Ju},deleteGroupAttributes:{groupID:Wu,keyList:Object.assign(Object.assign({},zu),{allowEmpty:!0})},getGroupAttributes:{groupID:Wu,keyList:Object.assign(Object.assign({},zu),{allowEmpty:!0})},getGroupCounters:{groupID:Wu,keyList:{required:!1,rules:["array"],allowEmpty:!0}},setGroupCounters:{groupID:Wu,counters:Ju},increaseGroupCounter:{groupID:Wu,key:Wu,value:Yu},decreaseGroupCounter:{groupID:Wu,key:Wu,value:Yu}},Xu={getGroupList:!0,createGroup:!0,dismissGroup:!0,joinGroup:!0,quitGroup:!0,searchGroupByID:!0,getGroupProfile:!0,updateGroupProfile:!0,changeGroupOwner:!0,getGroupOnlineMemberCount:!0,getGroupApplicationList:!0,handleGroupApplication:!0,getGroupMemberList:!0,getGroupMemberProfile:!0,addGroupMember:!0,deleteGroupMember:!0,setGroupMemberMuteTime:!0,setGroupMemberRole:!0,setGroupMemberNameCard:!0,setGroupMemberCustomField:!0,markGroupMemberList:!0,initGroupAttributes:!0,setGroupAttributes:!0,getGroupAttributes:!0,deleteGroupAttributes:!0,getGroupCounters:!0,setGroupCounters:!0,increaseGroupCounter:!0,decreaseGroupCounter:!0};var Zu=new class{constructor(){this._installedSubPlugins=[],this.groupDataHandler=eu,this.groupAction=_u,this.groupAttribute=ku,this.groupMember=Du,this.name="Group"}install(e,t=[]){this._core=e,Ga.init(e),eu.init(e),_u.init(e,this),Du.init(e,this),fu.init(e),Lu.init(e),ku.init(e),Hu.init(e),e.helper.registerValidateConfig({auth:Xu,params:Qu}),this._installSubPlugins(t);const{notificationCenter:s,InnerEvent:n}=e;s.subscribeInnerEvent(n.LOGOUT,this._reset,this),s.subscribeInnerEvent(n.DESTROY,this._dispose,this)}getInstalledSubPlugins(){return this._installedSubPlugins}_installSubPlugins(e){const{utils:{isArray:t}}=this._core;e&&t(e)&&e.forEach(e=>{var t;this._installedSubPlugins.includes(e.name)||(null===(t=e.install)||void 0===t||t.call(e,this._core,this),this._installedSubPlugins.push(e.name))})}_reset(){eu.reset(),ku.reset(),Lu.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 el=new class{init(e){this.core=e}};const tl="AV_MBR_LIST",sl="AV_BAN_MBR",nl={NORMAL_MESSAGE:3,GROUP_TIPS_HAS_ROAMING:4,GROUP_SYSTEM_MESSAGE:5,GROUP_TIPS_HAS_NO_ROAMING:6,BROADCAST_MESSAGE:17,MESSAGE_REVOKED:20,MESSAGE_REACTION:21,LIVE_CUSTOM_DATA:100},ol={GROUP_DISMISSED:5,QUIT_GROUP:8,AVCHATROOM_MEMBER_BANNED:21},il=60,rl=2603,al=2686,cl=2688,ul=3122;class ll{constructor(e){const{core:t,manager:s,groupID:n,getRequestParams:o,onSuccess:i,onFail:r}=e;this._name="Polling",this._core=t,this._manager=s,this._timeoutID=-1,this._isRunning=!1,this._groupID=n,this._getRequestParams=o,this._onSuccess=i,this._onFail=r}start(){this._isRunning=!0,this._request(),console.log(`${this._name}.start pollingInterval:${this._manager.getCurrentPollingInterval(this._groupID)}`)}isRunning(){return this._isRunning}_request(){return de(this,void 0,void 0,function*(){try{const e=this._getRequestParams(this._groupID),t=yield function(e,t){return de(this,void 0,void 0,function*(){const{longPollingKey:s,startSequence:n,startBroadcastSeq:o,simplifiedMessage:i}=e,r={Key:s,StartSeq:n,StartBroadcastSeq:o,DownsizeFlag:i,USP:1,HoldTime:90};return t.common.buildAndSendPacket({servcmd:"group_open_long_polling_http_svc.get_msg",data:r})})}(e,this._core);this._onSuccess(this._groupID,t);const s=this._manager.getCurrentPollingInterval(this._groupID);this._runNextPolling(s)}catch(e){this._onFail(this._groupID,e),this._runNextPolling(2e3)}})}_runNextPolling(e){this.isRunning()&&(this._timeoutID>-1&&clearTimeout(this._timeoutID),this._timeoutID=setTimeout(this._request.bind(this),e))}stop(){console.log(`${this._name}.stop timerID:${this._timeoutID}`),this._timeoutID>-1&&(clearTimeout(this._timeoutID),this._timeoutID=-1),this._isRunning=!1}}class dl{constructor(e){this._maxLength=e,this._map=new Map}set(e){var t;if(this._map.size>=this._maxLength){const e=(null===(t=this._map.entries().next().value)||void 0===t?void 0:t[0])||"";this._map.delete(e)}this._map.set(e,1)}has(e){return this._map.has(e)}delete(e){this.has(e)&&this._map.delete(e)}clear(){this._map.clear()}}const hl=e=>e===nl.GROUP_TIPS_HAS_NO_ROAMING||e===nl.GROUP_TIPS_HAS_ROAMING,gl=e=>e===nl.GROUP_SYSTEM_MESSAGE;function pl(e){const t=function(e){const{E:t,MCT:s,MR:n,MP:o,MTS:i,GId:r,MS:a,CCD:c,F_Account:u,IsSys:l,GInf:d,MsgBody:h}=e,g=le(e,["E","MCT","MR","MP","MTS","GId","MS","CCD","F_Account","IsSys","GInf","MsgBody"]);return Object.assign({Event:t,MsgClientTime:s,MsgRandom:n,MsgPriority:o,MsgTimeStamp:i,ToGroupId:r,MsgSeq:a,CloudCustomData:c,From_Account:u,IsSystemMsg:l,GroupInfo:_l(d),MsgBody:ml(h)},g)}(e);return function(e){const{Event:t}=e;(hl(t)||gl(t))&&(e.From_Account=e.From_Account||"@TIM#SYSTEM");s=t,(s===nl.BROADCAST_MESSAGE||(e=>e===nl.NORMAL_MESSAGE)(t))&&function(e){const{core:{OuterConstant:t}}=el;e.CloudCustomData=e.CloudCustomData||"",e.MsgBody=e.MsgBody.map(e=>{if(e.MsgType===t.MSG_CUSTOM){const{content:t={}}=e;e.content=Object.assign({Data:"",Desc:"",Ext:""},t)}return e})}(e);var s;hl(t)&&function(e){const{GroupJoinType:t,MsgOperatorMemberExtraInfo:s={},MsgMemberExtraInfo:n,Operator_Account:o,List_Account:i,OpType:r}=e.MsgBody||{};"number"==typeof t||1!==r&&2!==r||(e.MsgBody.GroupJoinType=2===r?0:1);n||(e.MsgBody.MsgMemberExtraInfo=null==i?void 0:i.map(e=>({UserId:e})));1!==r||n||(e.MsgBody.MsgMemberExtraInfo=[{UserId:s.UserId}]);e.MsgBody.MsgOperatorMemberExtraInfo=Object.assign({Operator_Account:o,ImageUrl:"",NickName:""},s)}(e);gl(t)&&function(e){const{MsgOperatorMemberExtraInfo:t={},Operator_Account:s}=e.MsgBody||{};e.MsgBody.MsgMemberExtraInfo=Object.assign({UserId:s,ImageUrl:"",NickName:""},t),e.MsgBody=Object.assign({Authentication:"",RemarkInfo:"",MsgKey:1e3*e.MsgTimeStamp},e.MsgBody),e.MsgBody=Object.keys(e.MsgBody).filter(e=>"MsgOperatorMemberExtraInfo"!==e).reduce((t,s)=>Object.assign(Object.assign({},t),{[s]:e.MsgBody[s]}),{})}(e)}(t),t}function _l(e){const t=e||{},{GN:s,GT:n,F_Hd:o,F_NN:i,F_Ll:r}=t,a=le(t,["GN","GT","F_Hd","F_NN","F_Ll"]),c=Object.assign({GroupName:s,GroupType:n},a);return o&&(c.From_AccountHeadurl=o),i&&(c.From_AccountNick=i),r&&(c.From_AccountLevel=r),c}function ml(e){let t=e;Array.isArray(e)||(t=[e]);const s=t.map(e=>{const{O_Account:t,Opt:s,L_Account:n,RT:o,UDF:i,OpInf:r,OnlineInf:a,MsgMemberExtraInfo:c}=e,u=le(e,["O_Account","Opt","L_Account","RT","UDF","OpInf","OnlineInf","MsgMemberExtraInfo"]),l=Object.assign({Operator_Account:t,OpType:s,List_Account:n,ReportType:o,UserDefinedField:i},u);return r&&(l.MsgOperatorMemberExtraInfo=function(e){const{Img:t,NN:s}=e,n=le(e,["Img","NN"]);return Object.assign({ImageUrl:t,NickName:s},n)}(r)),c&&(l.MsgMemberExtraInfo=function(e){return null==e?void 0:e.map(e=>{const{Img:t,NN:s}=e,n=le(e,["Img","NN"]);return Object.assign({ImageUrl:t,NickName:s},n)})}(c)),a&&(l.OnlineMemberInfo=function(e){const{ET:t,Num:s}=e;return{ExpireTime:t,OnlineMemberNum:s}}(a)),l});return Array.isArray(e)?s:s[0]}var vl=new class{constructor(){this._name="MessageParser",this._sequenceList=new dl(200),this._messageIDList=new dl(100),this._broadcastMessageIDMap=new Map,this._reportMessageStackedCount=0}init(e,t){this._core=e,this._avChatRoomHandler=t}onMessageReceived(e,t,s=!1){this._sortServerMessageList({groupID:e,serverMessageList:t,isHistoryMessage:s});const n=this._handleMessageList(e,t);if(0===n.length)return;if(!s){const{appStore:{conversationStore:t},OuterConstant:{CONV_GROUP:s}}=this._core,o=(e=>{const{core:{common:{getMessagePreviewText:t}}}=el;return{lastTime:(null==e?void 0:e.time)||(null==e?void 0:e.lastTime)||0,lastSequence:(null==e?void 0:e.sequence)||(null==e?void 0:e.lastSequence)||0,fromAccount:(null==e?void 0:e.from)||(null==e?void 0:e.fromAccount)||"",messageForShow:t(null==e?void 0:e.type,null==e?void 0:e.payload),payload:(null==e?void 0:e.payload)||null,type:(null==e?void 0:e.type)||"",isRevoked:(null==e?void 0:e.isRevoked)||!1,cloudCustomData:(null==e?void 0:e.cloudCustomData)||"",onlineOnlyFlag:(null==e?void 0:e._onlineOnlyFlag)||!1,nick:(null==e?void 0:e.nick)||"",nameCard:(null==e?void 0:e.nameCard)||"",version:(null==e?void 0:e.version)||0,isPeerRead:(null==e?void 0:e.isPeerRead)||!1,revoker:(null==e?void 0:e.revoker)||null}})(n[n.length-1]);t.updateConversation(`${s}${e}`,{lastMessage:o})}this._checkMessageStacked(n);const o=n.filter(e=>!0===e.isModified),i=n.filter(e=>!1===e.isModified),{OuterEvent:{MESSAGE_RECEIVED:r,MESSAGE_MODIFIED:a}}=this._core;o.length>0&&this._emitEvent({name:a,data:o}),i.length>0&&this._emitEvent({name:r,data:i})}_sortServerMessageList(e){const{groupID:t,serverMessageList:s,isHistoryMessage:n}=e;let o=[];this._avChatRoomHandler.isPollingSimplifiedMessage()&&!n?(s.sort((e,t)=>e.MS-t.MS),o=s.map(e=>e.MS)):(s.sort((e,t)=>e.MsgSeq-t.MsgSeq),o=s.map(e=>e.MsgSeq)),console.log(`${this._name}._sortServerMessageList groupID:${t} count:${o.length} sequenceList:${o}`),o.length=0}_handleMessageList(e,t){const{message:{messageDataHandler:s,messageHelper:n}}=this._core,o=this._avChatRoomHandler.isPollingSimplifiedMessage(),i=[],r=t.length;for(let a=0;a<r;a++){let r=t[a];if(o&&(r=pl(r)),gl(r.Event)&&Object.values(ol).includes(r.MsgBody.ReportType)){this._onGroupDismissed(e);break}if(null===this._filterMessageItem(r))continue;this._patchMessageType(r);const c=n.parseServerGroupMessage(r),u=this._createMessage(c);u.level=r.GroupInfo.From_AccountLevel,hl(r.Event)&&this._avChatRoomHandler.isGroupAttributesUpdated(c)?this._avChatRoomHandler.handleGroupAttributesUpdated(c):null!==this._filterDuplicateMessage(u)&&(s.isMessageSentByCurrentInstance(u)||(1===c.isModified&&(u.isModified=!0),hl(r.Event)&&this._updateLocalOnlineMemberCountFromTips(r),i.push(u)))}return i}_patchMessageType(e){const{OuterConstant:t}=this._core;hl(e.Event)&&(e.MsgBody.MsgType=t.MSG_GRP_TIP),gl(e.Event)&&(e.MsgBody.MsgType=t.MSG_GRP_SYS_NOTICE)}_filterMessageItem(e){const{Event:t}=e;return Object.values(nl).includes(t)?(e=>e===nl.MESSAGE_REVOKED)(t)?(this._handleMessageRevoked(e),null):(e=>e===nl.LIVE_CUSTOM_DATA)(t)?(this._onLiveCustomData(e),null):(e=>e===nl.MESSAGE_REACTION)(t)?null:e:(console.warn(`${this._name}.onMessageReceived unknown event:${t}`),null)}_createMessage(e){const{message:{messageFactory:t},OuterConstant:s}=this._core;let n=s.CONV_GROUP;e.event===nl.GROUP_SYSTEM_MESSAGE&&(n=s.CONV_SYSTEM);const o=!!e.isSystemMessage,i=t.createMessage(Object.assign(Object.assign({},e),{conversationType:n,isSystemMessage:o,flow:"in"}));return i.setElement(e.elements),i}_filterDuplicateMessage(e){const{common:t}=this._core;if(!t.isUnlimitedAVChatRoom()){if(this._sequenceList.has(e.sequence))return null;this._sequenceList.set(e.sequence)}const s=this._messageIDList.has(e.ID);return s?(console.warn(`${this._name}_filterDuplicateMessageItem ID:${e.ID} has:${s}`),null):(this._messageIDList.set(e.ID),e)}_handleMessageRevoked(e){const{OuterConstant:t,OuterEvent:{MESSAGE_REVOKED:s}}=this._core,{ToGroupId:n,MsgBody:{RevokeMsgList:o},RevokerInfo:{Revoker_Account:i,Reason:r=""}}=e,a=[];o.forEach(e=>{const{TinyId:s,MsgClientTime:o,Random:c,MsgSeq:u}=e,l={conversationID:`${t.CONV_GROUP}${n}`,ID:`${s}-${o}-${c}`,revoker:i,revokeReason:r,revokerInfo:{userID:i,nick:"",avatar:""},sequence:u};a.push(l)}),0!==a.length&&this._emitEvent({name:s,data:a})}_onLiveCustomData(e){const{OuterEvent:{ROOM_CUSTOM_DATA_RECEIVED:t}}=this._core,{ToGroupId:s,MsgSeq:n,MsgTimeStamp:o,MsgBody:i}=e,r=(null==i?void 0:i.Content)||(null==i?void 0:i.MsgContent)||"";this._emitEvent({name:t,data:r}),console.log(`${this._name}._onLiveCustomData groupID:${s} sequence:${n} time:${o} data:${r}`)}_onGroupDismissed(e){this._avChatRoomHandler.reset(e)}_checkMessageStacked(e){const{length:t}=e;if(t>=100&&this._reportMessageStackedCount<5){const e=this._avChatRoomHandler.getJoinedGroups();this._core.ssoLog.info("MessageStacked",`count:${t} groupID:${e.join(",")}`),this._reportMessageStackedCount+=1}}_emitEvent(e){this._core.notificationCenter.emitOuterEvent(e.name,e)}onBroadcastMessageReceived(e){const{message:{messageHelper:t},OuterEvent:{MESSAGE_RECEIVED:s}}=this._core,n=this._avChatRoomHandler.isPollingSimplifiedMessage(),o=[],i=e.length;for(let s=0;s<i;s++){let i=e[s];n&&(i=pl(i));const r=t.parseServerGroupMessage(i);if(!Object.values(nl).includes(i.Event)){console.warn(`${this._name}.onBroadcastMessageReceived unknown event:${i.Event}`);continue}const a=this._createMessage(r);a.isBroadcastMessage=!0,this._broadcastMessageIDMap.has(a.ID)||(o.push(a),this._broadcastMessageIDMap.set(a.ID,1))}o.length>0&&this._emitEvent({name:s,data:o})}_updateLocalOnlineMemberCountFromTips(e){const{utils:{isEmpty:t}}=this._core,{ToGroupId:s,MsgBody:{OnlineMemberInfo:n}}=e;if(t(n))return;const{OnlineMemberNum:o=0,ExpireTime:i=il}=n,r=Date.now();let a=this._avChatRoomHandler.getLocalOnlineMemberCount(s);t(a)?a={lastReqTime:0,lastSyncTime:0,latestUpdateTime:r,memberCount:o,expireTime:i}:(a.latestUpdateTime=r,a.memberCount=o),this._avChatRoomHandler.updateLocalOnlineMemberCount(s,a)}reset(){this._reportMessageStackedCount=0,this._sequenceList.clear(),this._messageIDList.clear(),this._broadcastMessageIDMap.clear()}};const fl=e=>{const{core:{store:t}}=el;return(t.get("cloudConfig")||{})[e]},Il=e=>{const{core:{utils:{isUndefined:t}}}=el;return!t(e)},El=()=>{const e=fl("polling_interval");return Il(e)?parseInt(e,10):300},Sl=()=>{const e=fl("polling_simplified_msg");return Il(e)?parseInt(e,10):0};var Cl=new class{constructor(){this._name="AVChatRoomHandler",this._joinedGroupMap=new Map,this._pollingRequestInfoMap=new Map,this._pollingInstanceMap=new Map,this._onlineMemberCountMap=new Map,this._pollingIntervalMap=new Map,this._pollingNoMessageCountMap=new Map,this._membersReqInfoMap=new Map,this._startBroadcastSequence=1}init(e,t){this._core=e,this._parentPlugin=t,vl.init(e,this),e.ssoLog.debug("AVChatRoomHandler.init")}onAVChatRoomSystemNotification(e){const{OuterConstant:{GRP_AVCHATROOM:t}}=this._core,{GroupTips:s=[]}=e;for(let e=0;e<s.length;e++){const{MsgBody:n,GroupInfo:{GroupId:o,GroupType:i}}=s[e],r=Object.values(ol).includes(n.ReportType);i===t&&r&&this.reset(o)}}getCurrentPollingInterval(e){return this._pollingIntervalMap.get(e)||El()}isPollingSimplifiedMessage(){return 0!==Sl()}isGroupAttributesUpdated(e){return!!this._parentPlugin.groupAttribute.isGroupAttributesUpdated(e)&&(this._parentPlugin.groupAttribute.handleGroupAttributesUpdated(e),!0)}updateLocalOnlineMemberCount(e,t){this._onlineMemberCountMap.set(e,t)}getLocalOnlineMemberCount(e){return this._onlineMemberCountMap.get(e)||{}}hasPollingInstance(e){return this._pollingInstanceMap.has(e)}getJoinedLiveList(){const{OuterConstant:{GRP_LIVE:e}}=this._core;let t=[];return this._joinedGroupMap.size>0&&(t=[...this._joinedGroupMap.values()].filter(t=>t.type===e)),t}handleJoinGroupResult(e){return de(this,void 0,void 0,function*(){const{utils:{isUndefined:t},OuterConstant:{CONV_GROUP:s},apiMap:{getConversationProfile:n},OuterConstant:o}=this._core,{longPollingKey:i,group:r,historyMessageList:a=[]}=e,{groupID:c}=r;if(yield this._preCheck(r),this._joinedGroupMap.set(c,r),this._parentPlugin.groupDataHandler.updateLocalGroup([r]),this._parentPlugin.groupDataHandler.emitGroupListUpdate(),n(`${s}${c}`),a.length>0&&vl.onMessageReceived(c,a,!0),!t(i)){return{code:0,data:this.startMessageLongPolling(e)}}return{code:0,data:{status:o.JOIN_STATUS_SUCCESS,group:r}}})}_preCheck(e){return de(this,void 0,void 0,function*(){const{common:t,OuterConstant:s,helper:n,apiMap:{quitGroup:o},ssoLog:i}=this._core;if(t.isUnlimitedAVChatRoom()){if(this._pollingInstanceMap.size>(()=>{const e=fl("polling_count_limit");return Il(e)&&e>0?parseInt(e,10):20})())throw new n.ChatError({code:cl,message:"the count of longPolling exceeds the max limit"});return}if(0===this._joinedAVChatRoomCount())return;if(e.type===s.GRP_LIVE)return;const[r,a]=this._joinedGroupMap.entries().next().value;if(a.selfInfo.role===s.GRP_MBR_ROLE_OWNER)this._parentPlugin.groupDataHandler.deleteLocalGroup(r);else try{yield o(r)}catch(e){i.debug("quitGroup",`${this._name}._preCheck quitGroup failed, groupID:${r} info:`,e)}this.reset(r)})}startMessageLongPolling(e){const{OuterConstant:t}=this._core,{longPollingKey:s,startSequence:n=1,group:o}=e,{groupID:i}=o;return this._pollingRequestInfoMap.set(i,{longPollingKey:s,startSequence:n}),this._pollingIntervalMap.set(i,El()),this._startPolling(i),this._reportLongPollingCount(),{status:t.JOIN_STATUS_SUCCESS,group:o}}_startPolling(e){if(this._core.ssoLog.debug("_startPolling",`${this._name}._startPolling groupID:${e}`),this._pollingInstanceMap.has(e)){const t=this._pollingInstanceMap.get(e);return void((null==t?void 0:t.isRunning())||null==t||t.start())}const t=new ll({core:this._core,manager:this,groupID:e,getRequestParams:this._handleRequestParams.bind(this),onSuccess:this._handleSuccess.bind(this),onFail:this._handleFailure.bind(this)});t.start(),this._pollingInstanceMap.set(e,t)}_handleRequestParams(e){const{longPollingKey:t,startSequence:s}=this._pollingRequestInfoMap.get(e)||{};return e===[...this._pollingInstanceMap.keys()][0]?{longPollingKey:t,startSequence:s,startBroadcastSeq:this._startBroadcastSequence,simplifiedMessage:Sl()}:{longPollingKey:t,startSequence:s,simplifiedMessage:Sl()}}_handleSuccess(e,t){const{ErrorCode:s}=t;if(0!==s){const{longPollingKey:t,startSequence:n}=this._pollingRequestInfoMap.get(e)||{};return void console.warn(`${this._name}._handleSuccess groupID:${e} key:${t} startSeq:${n} errorCode:${s}`)}this._hasJoinedAVChatRoom(e)&&this._handleResponseData(e,t)}_handleResponseData(e,t){const{Key:s,NextSeq:n,NextBroadcastSeq:o,RspMsgList:i=[],RspBroadcastMsgList:r=[]}=t;if(s&&n&&this._pollingRequestInfoMap.set(e,{longPollingKey:s,startSequence:n}),o&&o>this._startBroadcastSequence&&(this._startBroadcastSequence=o),i.length>0)0!==this._getPollingNoMessageCount(e)&&(this._updatePollingNoMessageCount(e,0),this._pollingIntervalMap.set(e,El())),vl.onMessageReceived(e,i);else{let t=this._getPollingNoMessageCount(e);if(t+=1,this._updatePollingNoMessageCount(e,t),t===(()=>{const e=fl("polling_no_msg_count");return Il(e)?parseInt(e,10):20})()){const t=El()+(()=>{const e=fl("polling_interval_plus");return Il(e)?parseInt(e,10):2e3})();this._pollingIntervalMap.set(e,t)}}r.length>0&&vl.onBroadcastMessageReceived(r)}_handleFailure(e,t){const{ssoLog:s,utils:{safeStringify:n}}=this._core;s.warn("polling",`${this._name}._handleFailure groupID:${e} error: ${n(t)}`)}_joinedAVChatRoomCount(){const{OuterConstant:e}=this._core;let t=[];return this._joinedGroupMap.size>0&&(t=this.getJoinedGroups().filter(t=>t.type===e.GRP_AVCHATROOM)),t.length}_hasJoinedAVChatRoom(e){return this._joinedGroupMap.has(e)}getJoinedGroups(){return[...this._joinedGroupMap.values()]}updateLocalLiveGroup(e,t){this._joinedGroupMap.set(e,t),this._parentPlugin.groupDataHandler.updateLocalGroup([t])}handleLiveHistoryMessages(e,t){vl.onMessageReceived(e,t,!0)}isOverFrequencyLimit(e){if(!this._membersReqInfoMap.has(e))return this._membersReqInfoMap.set(e,{startTime:Date.now(),requestCount:1}),!1;let{startTime:t,requestCount:s}=this._membersReqInfoMap.get(e);const{interval:n,count:o}=(()=>{const e=fl("av_members_freq_limit");if(Il(e)){const{interval:t,count:s}=JSON.parse(e);if(s>0&&t>0)return{interval:t,count:s}}return{interval:30,count:4}})();return Date.now()-t>1e3*n?(this._membersReqInfoMap.set(e,{startTime:Date.now(),requestCount:1}),!1):(s+=1,this._membersReqInfoMap.set(e,{startTime:t,requestCount:s}),s>o)}_stopPolling(e){if(this._core.ssoLog.debug("_stopPolling",`${this._name}._stopPolling groupID:${e}`),e){const{appStore:{conversationStore:t},OuterConstant:{CONV_GROUP:s}}=this._core;t.deleteConversation(`${s}${e}`);const n=this._pollingInstanceMap.get(e);return null==n||n.stop(),this._parentPlugin.groupDataHandler.deleteLocalGroup(e),this._pollingInstanceMap.delete(e),this._pollingRequestInfoMap.delete(e),this._joinedGroupMap.delete(e),this._onlineMemberCountMap.delete(e),this._pollingIntervalMap.delete(e),this._pollingNoMessageCountMap.delete(e),void this._membersReqInfoMap.delete(e)}for(const e of this._pollingInstanceMap.values())null==e||e.stop();this._pollingInstanceMap.clear(),this._pollingRequestInfoMap.clear(),this._joinedGroupMap.clear(),this._onlineMemberCountMap.clear(),this._pollingIntervalMap.clear(),this._pollingNoMessageCountMap.clear(),this._membersReqInfoMap.clear()}_updatePollingNoMessageCount(e,t){this._pollingNoMessageCountMap.set(e,t)}_getPollingNoMessageCount(e){return this._pollingNoMessageCountMap.get(e)||0}_reportLongPollingCount(){const e=this._joinedGroupMap.size;if(e>1){const{common:t,OuterConstant:s,ssoLog:n}=this._core,o=t.isUnlimitedAVChatRoom()?1:0,i=[],r=[];this._joinedGroupMap.values().forEach(({groupID:e,type:t})=>{t===s.GRP_LIVE?r.push(e):i.push(e)}),n.info("longPollingCount",String(e),{moreMessage:`av:${i.join(",")} live:${r.join(",")} code: ${o}`,eventType:29})}}reset(e){this._stopPolling(e),this._startBroadcastSequence=1,vl.reset()}};var Ml=new class{init(e,t){this._core=e,this._parentPlugin=t;const{helper:s}=e;s.registerApi({apiName:"joinGroup",context:this,matcher:()=>t.getInstalledSubPlugins().length>0})}joinGroup(e){return de(this,void 0,void 0,function*(){const{OuterConstant:t}=this._core,s=yield this._parentPlugin.groupAction.joinGroup(e),{data:{status:n,group:{type:o}}}=s;return o===t.GRP_AVCHATROOM?n===t.JOIN_STATUS_ALREADY_IN_GROUP?s:Cl.handleJoinGroupResult(s.data):s})}};var yl=new class{init(e,t){this._core=e,this._parentPlugin=t;const{helper:s}=e;s.registerApi({apiName:"quitGroup",context:this,matcher:()=>t.getInstalledSubPlugins().length>0})}quitGroup(e){return de(this,void 0,void 0,function*(){const{OuterConstant:t}=this._core,s=yield this._parentPlugin.groupAction.quitGroup(e),{data:{type:n}}=s;return n===t.GRP_AVCHATROOM&&Cl.reset(e),s})}};var Ol=new class{init(e,t){this._core=e,this._parentPlugin=t;const{helper:s}=e;s.registerApi({apiName:"dismissGroup",context:this,matcher:()=>t.getInstalledSubPlugins().length>0})}dismissGroup(e){return de(this,void 0,void 0,function*(){const{OuterConstant:t}=this._core,s=yield this._parentPlugin.groupAction.dismissGroup(e),{data:{type:n}}=s;return n===t.GRP_AVCHATROOM&&Cl.reset(e),s})}};var Al=new class{constructor(){this._name="GetAVChatRoomMemberList"}init(e,t){this._core=e,this._parentPlugin=t;const{helper:s}=e;s.registerApi({apiName:"getGroupMemberList",context:this,matcher:()=>t.getInstalledSubPlugins().length>0})}getGroupMemberList(e){return de(this,void 0,void 0,function*(){const{appStore:{groupStore:t},helper:s,OuterConstant:n}=this._core,{groupID:o}=e,i=t.getGroup(o);if((null==i?void 0:i.type)===n.GRP_AVCHATROOM){if(s.checkBusinessCapabilityBits(tl)){if(Cl.isOverFrequencyLimit(o)){throw{code:2996,message:`Over frequency limit: get_members-${o}`}}return this._getGroupMemberList(e)}}return this._parentPlugin.groupMember.getGroupMemberList(e)})}_getGroupMemberList(e){return de(this,void 0,void 0,function*(){const t="_getGroupMemberList",{helper:s}=this._core;try{const s=yield function(e,t){return de(this,void 0,void 0,function*(){const{groupID:s,offset:n=0}=e,o={GroupId:s,Timestamp:n};return t.common.buildAndSendPacket({servcmd:"group_open_avchatroom_http_svc.get_members",data:o})})}(e,this._core),{MemberList:n=[],NextTimestamp:o=0}=s||{},i=this._handleMemberList(n);return console.log(`${this._name}.${t} ok, groupID:${e.groupID} count:${i.length} nextOffset:${o}`),{code:0,data:{memberList:i,offset:o}}}catch(e){const n=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:`,n),n}})}_handleMemberList(e){return e.map(e=>{const{Member_Account:t,NickName:s="",Avatar:n="",Remark:o="",JoinTime:i=0,Marks:r=[]}=e;return{userID:t,nick:s,avatar:n,remark:o,joinTime:i,marks:r,isOnline:!0}})}};var Tl=new class{constructor(){this._name="GetAVChatRoomOnlineMemberCount"}init(e,t){this._core=e,this._parentPlugin=t;const{helper:s}=e;s.registerApi({apiName:"getGroupOnlineMemberCount",context:this,matcher:()=>t.getInstalledSubPlugins().length>0})}getGroupOnlineMemberCount(e){return de(this,void 0,void 0,function*(){const{appStore:{groupStore:t},OuterConstant:s}=this._core,n=t.getGroup(e);return n?n.type===s.GRP_AVCHATROOM?this._getOnlineMemberCount(e):this._parentPlugin.groupAction.getGroupOnlineMemberCount(e):{code:0,data:{memberCount:0}}})}_getOnlineMemberCount(e){return de(this,void 0,void 0,function*(){const t="_getOnlineMemberCount",{utils:{isEmpty:s}}=this._core,n=Cl.getLocalOnlineMemberCount(e);if(s(n)||this._isExpired(e)){const{memberCount:s=0}=yield this._getOnlineMemberCountFromServer(e);return console.log(`${this._name}.${t} ok, groupID:${e} memberCount:${s} from server.`),{code:0,data:{memberCount:s}}}return console.log(`${this._name}.${t} ok, groupID:${e} memberCount:${n.memberCount} from local.`),{code:0,data:{memberCount:n.memberCount}}})}_isExpired(e){const t=Cl.getLocalOnlineMemberCount(e),s=Date.now(),n=s-t.lastSyncTime>1e3*t.expireTime,o=s-t.latestUpdateTime>1e4,i=s-t.lastReqTime>3e3;return n&&o&&i}_getOnlineMemberCountFromServer(e){return de(this,void 0,void 0,function*(){const t="_getOnlineMemberCountFromServer";try{const t=yield function(e,t){return de(this,void 0,void 0,function*(){const s={GroupId:e};return t.common.buildAndSendPacket({servcmd:"group_open_http_svc.get_online_member_num",data:s})})}(e,this._core),{OnlineMemberNum:s=0,ExpireTime:n=il}=t||{},o=Date.now(),i={lastSyncTime:o,latestUpdateTime:o,lastReqTime:o,memberCount:s,expireTime:n};return Cl.updateLocalOnlineMemberCount(e,i),{memberCount:s}}catch(e){const s=new this._core.helper.ChatError({functionName:t,code:null==e?void 0:e.errorCode,message:null==e?void 0:e.errorInfo});throw console.error(`${this._name}.${t} fail:`,s),s}})}};var Rl=new class{constructor(){this._name="DeleteAVChatRoomMember"}init(e,t){this._core=e,this._parentPlugin=t;const{helper:s}=e;s.registerApi({apiName:"deleteGroupMember",context:this,matcher:()=>t.getInstalledSubPlugins().length>0})}deleteGroupMember(e){return de(this,void 0,void 0,function*(){const t="deleteGroupMember",{appStore:{groupStore:s},utils:{isUndefined:n},helper:o,OuterConstant:i}=this._core,{groupID:r}=e,a=s.getGroup(r);if(n(a))throw new o.ChatError({functionName:t,code:rl});if(a.type===i.GRP_AVCHATROOM){if(o.checkBusinessCapabilityBits(sl))return this._deleteGroupMember(e);throw new o.ChatError({functionName:t,code:ul})}return this._parentPlugin.groupMember.deleteGroupMember(e)})}_deleteGroupMember(e){return de(this,void 0,void 0,function*(){const t="_deleteGroupMember",{appStore:{groupStore:s},helper:n,ssoLog:o}=this._core,{groupID:i,duration:r=0,userIDList:a}=e;if(0===r)throw new n.ChatError({functionName:t,code:al});try{yield function(e,t){return de(this,void 0,void 0,function*(){const{groupID:s,userIDList:n,duration:o,reason:i}=e,r={GroupId:s,Members_Account:n,Duration:o,Description:i};return t.common.buildAndSendPacket({servcmd:"group_open_http_svc.ban_group_member",data:r})})}(e,this._core),o.debug(t,`${this._name}.${t} ok, groupID:${i}`);return{code:0,data:{group:s.getGroup(i),userIDList:a}}}catch(e){throw new n.ChatError({functionName:t,code:null==e?void 0:e.errorCode,message:null==e?void 0:e.errorInfo})}})}};var Dl=new class{constructor(){this._name="MarkAVChatRoomMember"}init(e){this._core=e;const{helper:t}=e;t.registerApi({apiName:"markGroupMemberList",context:this})}markGroupMemberList(e){return de(this,void 0,void 0,function*(){const t="markGroupMemberList",{groupID:s,markType:n,enableMark:o,userIDList:i=[]}=e,r=this._generateRequestData(e);try{const e=yield function(e,t){return de(this,void 0,void 0,function*(){const{groupID:s,operationType:n,memberList:o}=e,i={GroupId:s,CommandType:n,MemberList:o};return t.common.buildAndSendPacket({servcmd:"group_open_avchatroom_http_svc.modify_user_info",data:i})})}(r,this._core),{MemberList:a=[]}=e||{},{successUserIDList:c,failureUserIDList:u}=this._handleResult(a,i);return{code:0,data:{successUserIDList:c,failureUserIDList:u},successLog:{message:`${this._name}.${t} ok, groupID:${s} markType:${n} enableMark:${o} success:${c.length} fail:${u.length}`}}}catch(e){throw new this._core.helper.ChatError({functionName:t,code:null==e?void 0:e.errorCode,message:null==e?void 0:e.errorInfo})}})}_generateRequestData(e){const{groupID:t,markType:s,enableMark:n,userIDList:o=[]}=e,i=!0===n?1:2,r=[...o];r.length>500&&console.warn(`${this._name}._generateRequestData, the length of userIDList cannot exceed 500`);return{groupID:t,operationType:i,memberList:r.map(e=>({Member_Account:e,Marks:[s]}))}}_handleResult(e,t){const s=[],n=[];return e.length===t.length?(s.push(...t),{successUserIDList:s,failureUserIDList:n}):(t.forEach(t=>{e.find(e=>e.Member_Account===t)?s.push(t):n.push(t)}),{successUserIDList:s,failureUserIDList:n})}};var bl=new class{init(e,t){e.ssoLog.debug("AVChatRoomAction.init"),Ml.init(e,t),yl.init(e,t),Ol.init(e,t),Al.init(e,t),Tl.init(e,t),Rl.init(e,t),Dl.init(e)}};var Nl=new class{constructor(){this._name="LiveHandler"}init(e){this._core=e;const{helper:t,ssoLog:s}=e;t.registerExperimentalAPI("startMessageLongPolling",this),t.registerExperimentalAPI("stopMessageLongPolling",this),s.debug("LiveHandler.init")}startMessageLongPolling(e){const{common:t,utils:{isEmpty:s},OuterConstant:n,ssoLog:o}=this._core,{groupID:i,longPollingKey:r,longPollingSequence:a=1}=e;if(s(r))return o.warn("startMessageLongPolling",`${this._name}.startMessageLongPolling longPollingKey is empty.`),Promise.resolve({});Cl.hasPollingInstance(i)&&this.stopMessageLongPolling({groupID:i});const c=Cl.getJoinedLiveList(),u=t.isUnlimitedAVChatRoom();!u&&c.length>0&&this.stopMessageLongPolling({groupID:c[0].groupID}),o.debug("startMessageLongPolling",`${this._name}.startMessageLongPolling isUnlimited:${u} groupID:${i} longPollingKey:${r} longPollingSequence:${a}`);const l={groupID:i,type:n.GRP_LIVE};return Cl.updateLocalLiveGroup(i,l),this._getLiveHistoryMessages({groupID:i,longPollingKey:r,startSequence:a}),Cl.startMessageLongPolling({group:l,longPollingKey:r,startSequence:a})}stopMessageLongPolling(e){const{groupID:t}=e;return Cl.reset(t),this._core.ssoLog.debug("stopMessageLongPolling",`${this._name}.stopMessageLongPolling ok, groupID:${t}`),Promise.resolve({groupID:t})}_getLiveHistoryMessages(e){return de(this,void 0,void 0,function*(){const{ssoLog:t}=this._core,{groupID:s}=e;try{const n=yield function(e,t){return de(this,void 0,void 0,function*(){const{groupID:s,longPollingKey:n,startSequence:o}=e,i={GroupId:s,LongPollingKey:n,PullPreSeq:o};return t.common.buildAndSendPacket({servcmd:"group_open_http_svc.get_huge_group_msg",data:i})})}(e,this._core),{RspMsgList:o=[]}=n||{};t.debug("_getLiveHistoryMessages",`${this._name}._getLiveHistoryMessages ok, groupID:${s} count:${o.length}`),o.length>0&&Cl.handleLiveHistoryMessages(s,o)}catch(e){t.debug("_getLiveHistoryMessages",`${this._name}._getLiveHistoryMessages failed, groupID:${s} info:${e.message}`)}})}};var Ll=new class{constructor(){this.name="AVChatRoom"}install(e,t){this._core=e,el.init(e),Cl.init(e,t),bl.init(e,t),Nl.init(e);const{notificationCenter:s,InnerEvent:n}=e,{InnerEventSubType:o}=s;s.subscribeInnerEvent(n.MESSAGE_PUSH,o.GROUP_SYSTEM_NOTIFICATION,this._onAVChatRoomSystemNotification,this),s.subscribeInnerEvent(n.LOGOUT,this._reset,this),s.subscribeInnerEvent(n.DESTROY,this._dispose,this)}_onAVChatRoomSystemNotification(e){Cl.onAVChatRoomSystemNotification(e)}_reset(){Cl.reset()}_dispose(){this._reset();const{notificationCenter:e,InnerEvent:t}=this._core,{InnerEventSubType:s}=e;e.unSubscribeInnerEvent(t.MESSAGE_PUSH,s.GROUP_SYSTEM_NOTIFICATION,this._onAVChatRoomSystemNotification,this),e.unSubscribeInnerEvent(t.LOGOUT,this._reset,this),e.unSubscribeInnerEvent(t.DESTROY,this._dispose,this)}};const Pl=new class{init(e){this.core=e}};const wl="message",Gl="user",Ul={OR:"or",AND:"and"},kl=20,Fl=20,$l=20,ql={required:!1,rules:["array"],allowEmpty:!0,customValidator:e=>!e||(!!(Array.isArray(e)&&e.length<=5)||"keywordList should be an array and length <= 5")},xl={required:!1,rules:["string"],allowEmpty:!0,customValidator:e=>!e||(!![Ul.OR,Ul.AND].includes(e)||"keywordListMatchType should be OR or AND")},Vl={required:!1,rules:["number"],allowEmpty:!0,customValidator:e=>"number"==typeof e&&e>=1&&e<=100||"count must be a number between 1 and 100"},Bl={required:!1,rules:["string"],allowEmpty:!0},jl={required:!1,rules:["array"],allowEmpty:!0,customValidator:e=>{const{OuterConstant:t}=Pl.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 n=!1;for(let t=0;t<e.length;t++)if(-1===s.indexOf(e[t])){n=!0;break}return!n||"groupTypeList should be supported group type"}},Kl={required:!1,rules:["array"],allowEmpty:!0,customValidator:e=>{const{OuterConstant:t}=Pl.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 n=!1;for(let t=0;t<e.length;t++)if(-1===s.indexOf(e[t])){n=!0;break}return!n||"messageTypeList should be supported message type"}},Hl={required:!1,rules:["string"],allowEmpty:!0,customValidator:e=>{const{OuterConstant:t}=Pl.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"}},Wl=e=>({required:!1,rules:["number"],allowEmpty:!0,customValidator:t=>"number"==typeof t&&t>=0||`${e} should be a number >= 0';`}),Yl={required:!1,rules:["string"],allowEmpty:!0,customValidator:e=>{const{OuterConstant:t}=Pl.core;return!![t.GENDER_FEMALE,t.GENDER_MALE].includes(e)||"gender is invalid"}},zl={searchCloudMessages:{keywordList:ql,keywordListMatchType:xl,cursor:Bl,senderUserIDList:{required:!1,rules:["array"],allowEmpty:!0,customValidator:e=>!!(Array.isArray(e)&&e.length<=5)||"senderUserIDList should be an array and length <= 5"},messageTypeList:Kl,conversationID:Hl,timePosition:Wl("timePosition"),timePeriod:Wl("timePeriod")},searchCloudUsers:{keywordList:ql,keywordListMatchType:xl,cursor:Bl,count:Vl,miniBirthday:Wl("miniBirthday"),maxBirthday:Wl("maxBirthday"),gender:Yl},searchCloudGroupMembers:{keywordList:ql,keywordListMatchType:xl,cursor:Bl,count:Vl,groupTypeList:jl,groupIDList:{required:!1,rules:["array"],allowEmpty:!0}},searchCloudGroups:{keywordList:ql,keywordListMatchType:xl,cursor:Bl,count:Vl,groupTypeList:jl}},Jl={searchCloudMessages:!0,searchCloudUsers:!0,searchCloudGroupMembers:!0,searchCloudGroups:!0};var Ql=new class{constructor(){this.name="CloudSearch"}install(e){this._core=e,Pl.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:Jl,params:zl})}searchCloudMessages(e){return de(this,void 0,void 0,function*(){try{const{OuterConstant:t,helper:s}=this._core,{conversationID:n,timePeriod:o,timePosition:i}=e,r=le(e,["conversationID","timePeriod","timePosition"]),a=Object.assign({count:100},r);n&&(n.startsWith(t.CONV_C2C)?a.account=n.replace(t.CONV_C2C,""):n.startsWith(t.CONV_GROUP)&&(a.groupID=n.replace(t.CONV_GROUP,""))),this._setTimeRangeParams(a,{timePeriod:o,timePosition:i});const c=yield function(e){return de(this,void 0,void 0,function*(){const{count:t,keywordList:s,keywordListMatchType:n,senderUserIDList:o,messageTypeList:i,endTime:r,startTime:a,cursor:c,account:u,groupID:l}=e,d={Count:t,KeywordList:s,MatchType:n,SendUserIDList:o,MsgTypeList:i,EndTime:r,StartTime:a,Cursor:c,PeerAccount:u,GroupID:l};return Pl.core.common.buildAndSendPacket({servcmd:"message_search.query",data:d})})}(a);if(!c)return{code:0,data:{}};const{ErrorCode:u,ErrorInfo:l,TotalCount:d,Cursor:h="",ConversationMsgs:g=[]}=c;if(0!==u)throw{errorCode:u,errorInfo:l};const p=`keywordList:${e.keywordList} keywordListMatchType:${e.keywordListMatchType} cursor:${e.cursor} res: totalCount:${d}`,_=g.map(n=>{const{MsgList:o,Count:i,GroupID:r,UserID:a}=n,c=r?`${t.CONV_GROUP}${r}`:`${t.CONV_C2C}${a}`;if(this._isSearchingAllConversations(e)&&i>1)return{conversationID:c,messageCount:i,messageList:[]};const u=o.map(e=>s.isEmpty(r)?function(e,t){const s=t.OuterConstant.CONV_C2C,n=t.message.messageHelper.parseServerPushMessage(e),o=t.message.messageFactory.createMessage(Object.assign(Object.assign({},n),{conversationType:s,flow:"in"}));return o.setElement(n.elements),o}(e,this._core):function(e,t){const s=t.OuterConstant.CONV_GROUP,n=t.message.messageHelper.parseServerGroupMessage(e),o=t.message.messageFactory.createMessage(Object.assign(Object.assign({},n),{conversationType:s,flow:"in"}));return o.setElement(n.elements),o}(e,this._core));return{conversationID:c,messageCount:i,messageList:u}});return{code:0,data:{searchResultList:_,cursor:h,totalCount:d},successLog:{message:p}}}catch(e){const{errorCode:t,errorInfo:s}=e||{};this._handleError({errorCode:t,errorInfo:s,searchType:wl,functionName:"searchCloudMessages"})}})}searchCloudUsers(e){return de(this,void 0,void 0,function*(){var t;try{const{keywordListMatchType:s,count:n=Fl}=e,o=le(e,["keywordListMatchType","count"]),i=Object.assign({count:n,keywordListMatchType:s===Ul.AND?1:0},o);this._setBirthdayRangeParams(i,e);const r=yield function(e){return de(this,void 0,void 0,function*(){const{count:t,keywordList:s,keywordListMatchType:n,miniBirthday:o,maxBirthday:i,cursor:r,gender:a}=e,c={Count:t,Keywords:s,KeywordMatchType:n,Cursor:r,UserBirthStart:o,UserBirthEnd:i,Gender:a};return Pl.core.common.buildAndSendPacket({servcmd:"user_search.query",data:c})})}(i);if(!r)return{error:0,data:{}};const{ErrorCode:a,ErrorInfo:c,TotalCount:u,Cursor:l="",Users:d=[]}=r;if(0!==a)throw{errorCode:a,errorInfo:c};const h=`keywordList:${e.keywordList} keywordListMatchType:${e.keywordListMatchType} cursor:${e.cursor} count:${e.count} res: totalCount:${u}`,g=[];for(let e=0,s=d.length;e<s;e++){const{UserID:s,ProfileItems:n}=d[e];if(s===this._core.OuterConstant.USER_NOT_FOUND||""===s)continue;const o=n.map(e=>({tag:e.Tag,value:e.StrValue})),i=null===(t=this._core.user.userProfile)||void 0===t?void 0:t.createProfile(s,o);g.push(i)}return{code:0,data:{searchResultList:g,cursor:l,totalCount:u},successLog:{message:h}}}catch(e){const{errorCode:t,errorInfo:s}=e||{};this._handleError({errorCode:t,errorInfo:s,searchType:Gl,functionName:"searchCloudUsers"})}})}searchCloudGroupMembers(e){return de(this,void 0,void 0,function*(){try{const{count:t=$l,keywordListMatchType:s}=e,n=le(e,["count","keywordListMatchType"]),o=Object.assign({count:t,keywordListMatchType:s===Ul.AND?1:0},n),i=yield function(e){return de(this,void 0,void 0,function*(){const{count:t,keywordList:s,keywordListMatchType:n,groupTypeList:o,cursor:i,groupIDList:r}=e,a={Count:t,Keywords:s,KeywordMatchType:n,Cursor:i,GroupType:o,GroupIdList:r};return Pl.core.common.buildAndSendPacket({servcmd:"group_member_search.query",data:a})})}(o);if(!i)return{code:0,data:{}};const{ErrorCode:r,ErrorInfo:a,GroupMembers:c=[],Cursor:u,TotalCount:l}=i;if(0!==r)throw{errorCode:r,errorInfo:a};const d=`keywordList:${e.keywordList} keywordListMatchType:${e.keywordListMatchType} cursor:${e.cursor} count:${e.count} res: totalCount:${l}`,h=new Map;return c.forEach(e=>{const{GroupID:t,GroupName:s,GroupType:n,GroupFaceUrl:o,GroupMemberUserName:i,GroupMemberUserID:r,GroupMemberNameCard:a,GroupMemberAvatar:c=""}=e,u={groupID:t,name:s,type:n,avatar:o},l={userID:r,nick:i,nameCard:a,avatar:c};if(h.has(t)){const e=h.get(t);e.memberList.push(l),h.set(t,e)}else h.set(t,{groupInfo:u,memberList:[l]})}),{code:0,data:{searchResultList:[...h.values()],cursor:u,totalCount:l},successLog:{message:d}}}catch(e){const{errorCode:t,errorInfo:s}=e||{};this._handleError({errorCode:t,errorInfo:s,searchType:Gl,functionName:"searchCloudGroupMembers"})}})}searchCloudGroups(e){return de(this,void 0,void 0,function*(){try{const{count:t=kl,keywordListMatchType:s}=e,n=le(e,["count","keywordListMatchType"]),o=Object.assign({count:t,keywordListMatchType:s===Ul.AND?1:0},n),i=yield function(e){return de(this,void 0,void 0,function*(){const{count:t,keywordList:s,keywordListMatchType:n,groupTypeList:o,cursor:i}=e,r={Count:t,Keywords:s,KeywordMatchType:n,Cursor:i,GroupType:o};return Pl.core.common.buildAndSendPacket({servcmd:"group_search.query",data:r})})}(o);if(!i)return{code:0,data:{}};const{ErrorCode:r,ErrorInfo:a,Groups:c,Cursor:u,TotalCount:l}=i;if(0!==r)throw{errorCode:r,errorInfo:a};const d=`keywordList:${e.keywordList} keywordListMatchType:${e.keywordListMatchType} cursor:${e.cursor} count:${e.count} res: totalCount:${l}`;return{code:0,data:{searchResultList:(null==c?void 0:c.map(e=>function(e){const{GroupFaceUrl:t,GroupID:s,GroupIntroduction:n,GroupMemberNum:o,GroupName:i,GroupOwnerTinyID:r,GroupOwnerUserID:a,GroupOwnerUserName:c,GroupType:u,GroupAddOption:l,GroupInviteOption:d}=e;return{avatar:t,groupID:s,introduction:n,memberCount:o,name:i,ownerTinyID:r,ownerID:a,ownerNick:c,type:u,joinOption:l,inviteOption:d}}(e)))||[],cursor:u,totalCount:l},successLog:{message:d}}}catch(e){const{errorCode:t,errorInfo:s}=e||{};this._handleError({errorCode:t,errorInfo:s,searchType:Gl,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}){const{helper:n}=this._core;let o=e;60020===e?o="SearchUnable":s!==wl&&27003===e?o="SearchParamsError":s!==wl&&60018===e&&(o="SearchOverLimit");throw new n.ChatError({code:o,message:t})}_isSearchingAllConversations(e){return this._core.helper.isEmpty(e.conversationID)}_setBirthdayRangeParams(e,t){const{miniBirthday:s,maxBirthday:n}=t;void 0!==s&&(e.miniBirthday=s,void 0===n&&(e.maxBirthday=4294967295)),void 0!==n&&(e.maxBirthday=n)}};function Xl(e,t){return Math.round(Number(e)*Math.pow(10,t))/Math.pow(10,t)}const Zl="qualityStat",ed="im-ssolog-quality-stat";var td;!function(e){e[e.ONLINE=8]="ONLINE"}(td||(td={}));const sd="networkRTT",nd="messageE2EDelay",od="sendMessageC2C",id="sendMessageGroup",rd="sendMessageGroupAV",ad="sendMessageRichMedia",cd="cosUpload",ud="messageReceivedGroup",ld="messageReceivedGroupAVPush",dd="messageReceivedGroupAVPull",hd={[sd]:2,[nd]:3,[od]:4,[id]:5,[rd]:6,[ad]:7,[ud]:8,[ld]:9,[dd]:10,[cd]:11},gd=[od,id,rd,ad,cd],pd=[ud,ld,dd],_d=[sd,nd,od,id,rd,ad,cd,ud,ld,dd],md={ERR_SVR_COMM_SENSITIVE_TEXT:80001,ERR_SVR_COMM_BODY_SIZE_LIMIT:80002,OPEN_SERVICE_OVERLOAD_ERROR:60022,ERR_SVR_MSG_PKG_PARSE_FAILED:20001,ERR_SVR_MSG_INTERNAL_AUTH_FAILED:20002,ERR_SVR_MSG_INVALID_ID:20003,ERR_SVR_MSG_PUSH_DENY:20006,ERR_SVR_MSG_IN_PEER_BLACKLIST:20007,ERR_SVR_MSG_BOTH_NOT_FRIEND:20009,ERR_SVR_MSG_NOT_PEER_FRIEND:20010,ERR_SVR_MSG_NOT_SELF_FRIEND:20011,ERR_SVR_MSG_SHUTUP_DENY:20012,ERR_SVR_GROUP_INVALID_PARAMETERS:10004,ERR_SVR_GROUP_PERMISSION_DENY:10007,ERR_SVR_GROUP_NOT_FOUND:10010,ERR_SVR_GROUP_INVALID_GROUPID:10015,ERR_SVR_GROUP_REJECT_FROM_THIRDPARTY:10016,ERR_SVR_GROUP_SHUTUP_DENY:10017,MSG_SEND_FAIL:2100,OVER_FREQUENCY_LIMIT:2996},vd="quality_stat";var fd=new class{constructor(){this._messageStatsMap=new Map,this._userSideErrorCodes=new Set(Object.values(md))}init(e){this._core=e,Object.values(gd).forEach(e=>{this._messageStatsMap.set(e,{totalCount:0,successCount:0,failedCountOfUserSide:0,costSum:0,costCount:0,fileSizeSum:0})})}dispatchSendStats(e){const{name:t,message:s,error:n,startTs:o}=e,{SEND_MESSAGE_STAT:i}=this._core.constants;switch(t){case i.TOTAL_COUNT:this._handleTotalCount(s);break;case i.SUCCESS_COUNT:this._handleSuccessCount(s);break;case i.FAILED_COUNT:this._handleFailedCount(s,n);break;case i.SEND_COST:this._handleSendCost(s,o)}}getStatResult(e){const t=this._messageStatsMap.get(e);if(!t||0===t.totalCount)return null;const{totalCount:s,successCount:n,failedCountOfUserSide:o}=t,i=Xl(n/s*100,2),r=n+o,a=Xl(r/s*100,2),c=this._calcAverageValue(t,e);return this._resetStat(e),{total_count:s,success_count_business:n,percent_business:i,success_count_platform:r,percent_platform:a,average_value:c}}_handleTotalCount(e){const t=this._getSendMessageSpecifiedKey(e),s=t&&this._messageStatsMap.get(t);s&&s.totalCount++}_handleSuccessCount(e){const t=this._getSendMessageSpecifiedKey(e),s=t&&this._messageStatsMap.get(t);s&&s.successCount++}_handleFailedCount(e,t){var s;const n=null!==(s=null==t?void 0:t.code)&&void 0!==s?s:null==t?void 0:t.errorCode;if(this._isUserSideError(n)){const t=this._getSendMessageSpecifiedKey(e),s=t&&this._messageStatsMap.get(t);s&&s.failedCountOfUserSide++}}_handleSendCost(e,t){const s=this._getSendMessageSpecifiedKey(e),n=s&&this._messageStatsMap.get(s);n&&(n.costSum+=Date.now()-t,n.costCount++)}_isUserSideError(e){return this._userSideErrorCodes.has(e)||e>=120001&&e<=13e4||e>=10100&&e<=10200}_getSendMessageSpecifiedKey(e){const{MSG_IMAGE:t,MSG_AUDIO:s,MSG_VIDEO:n,MSG_FILE:o,CONV_C2C:i,CONV_GROUP:r,GRP_AVCHATROOM:a}=this._core.OuterConstant;if([t,s,n,o].includes(e.type))return ad;if(e.conversationType===i)return od;if(e.conversationType===r){const{groupStore:t}=this._core.appStore,s=t.getGroup(e.to);if(!s)return;const{type:n}=s;return n===a?rd:id}}_calcAverageValue(e,t){return 0===e.costCount?0:t===cd?Math.round(1e3*e.fileSizeSum/e.costSum):Math.round(e.costSum/e.costCount)}_resetStat(e){const t=this._messageStatsMap.get(e);t&&(t.totalCount=0,t.successCount=0,t.failedCountOfUserSide=0,t.costSum=0,t.costCount=0,t.fileSizeSum=0)}};var Id=new class{constructor(){this._lastCycleStats=new Map,this._currentCycleStats=new Map}init(e){this._core=e;const{OuterEvent:t,notificationCenter:s}=e;this._initStatsMap(),s.subscribeOuterEvent(t.MESSAGE_RECEIVED,this._onMessageReceived,this)}addMessageSequence(e){const t=this._getReceivedMessageSpecifiedKey(e),{utils:{isUndefined:s},OuterConstant:{CONV_GROUP:n},ssoLog:o}=this._core;if(s(t)||!this._currentCycleStats.has(t))return void o.warn("addMessageSequence",`${Zl}.addMessageSequence invalid key:${t}`);const{conversationID:i,sequence:r}=e,a=i.replace(n,""),c=this._lastCycleStats.get(t);if(0===c.size||!c.has(a))return void this._addToCurrentCycle(t,a,r);const u=c.get(a);r>u.minSeq&&r<u.maxSeq?this._insertToLastCycle(r,u):this._addToCurrentCycle(t,a,r)}getStatResult(e){const t=this._lastCycleStats.get(e);if(!t||0===t.size)return this._transferCycleDataOptimized(e),null;let s=0,n=0;return t.forEach(e=>{const{sortedSequences:t,minSeq:o,maxSeq:i}=e;t.length>0&&(n+=t.length,s+=i-o+1)}),0===s?null:(this._transferCycleDataOptimized(e),{total_count:s,success_count_business:n,percent_business:Xl(n/s*100,2)})}reset(){this._lastCycleStats.clear(),this._currentCycleStats.clear()}dispose(){const{notificationCenter:e,OuterEvent:{MESSAGE_RECEIVED:t}}=this._core;e.unSubscribeOuterEvent(t,this._onMessageReceived,this),this.reset()}_initStatsMap(){Object.values(pd).forEach(e=>{this._lastCycleStats.set(e,new Map),this._currentCycleStats.set(e,new Map)})}_onMessageReceived(e){const{data:t=[]}=e;t.forEach(e=>{this.addMessageSequence(e)})}_transferCycleDataOptimized(e){const t=this._currentCycleStats.get(e);if(!t)return;const s=new Map;t.forEach((e,t)=>{const n=e.dirty?[...e.sortedSequences].sort((e,t)=>e-t):e.sortedSequences;s.set(t,{sortedSequences:n,minSeq:e.minSeq,maxSeq:e.maxSeq,dirty:!1})}),this._lastCycleStats.set(e,s),this._currentCycleStats.set(e,new Map)}_getReceivedMessageSpecifiedKey(e){const{OuterConstant:{CONV_GROUP:t,GRP_AVCHATROOM:s}}=this._core;if(e.conversationType===t&&!0!==(null==e?void 0:e._onlineOnlyFlag)){const{groupStore:t}=this._core.appStore,n=t.getGroup(e.to);if(!n)return null;const{type:o}=n;return o===s?dd:ud}}_insertToLastCycle(e,t){t.dirty&&(t.sortedSequences.sort((e,t)=>e-t),t.dirty=!1);const s=this._findInsertPos(t.sortedSequences,e);t.sortedSequences.splice(s,0,e),t.minSeq=Math.min(t.minSeq,e),t.maxSeq=Math.max(t.maxSeq,e)}_findInsertPos(e,t){let s=0,n=e.length-1;for(;s<=n;){const o=Math.floor((s+n)/2);if(e[o]===t)return o;e[o]<t?s=o+1:n=o-1}return s}_addToCurrentCycle(e,t,s){let n=this._currentCycleStats.get(e).get(t);n?(n.sortedSequences.push(s),n.minSeq=Math.min(n.minSeq,s),n.maxSeq=Math.max(n.maxSeq,s),n.dirty=!0):(n={sortedSequences:[s],minSeq:s,maxSeq:s,dirty:!1},this._currentCycleStats.get(e).set(t,n))}};var Ed=new class{constructor(){this._totalDelay=0,this._totalCount=0,this._countLessThan1s=0,this._countLessThan3s=0}init(e){this._core=e;const{OuterEvent:{MESSAGE_RECEIVED:t},notificationCenter:s}=e;s.subscribeOuterEvent(t,this._onMessageReceived,this)}addMessageDelay(e){const{timeManager:t}=this._core.common,s=t.getServerTimeSeconds()-e;s>0&&(this._totalDelay+=s,this._totalCount++,s<=1?this._countLessThan1s++:s<=3&&this._countLessThan3s++)}getStatResult(){if(0===this._totalCount)return null;const e={total_count:this._totalCount,success_count_business:this._countLessThan1s,success_count_platform:this._countLessThan3s,percent_business:this._calculatePercentage(this._countLessThan1s,this._totalCount),percent_platform:this._calculatePercentage(this._countLessThan3s,this._totalCount),average_value:this._calculateAverageDelay(this._totalCount)};return this.reset(),e}reset(){this._totalDelay=0,this._totalCount=0,this._countLessThan1s=0,this._countLessThan3s=0}dispose(){const{notificationCenter:e,OuterEvent:{MESSAGE_RECEIVED:t}}=this._core;e.unSubscribeOuterEvent(t,this._onMessageReceived,this),this.reset()}_onMessageReceived(e){const{data:t=[]}=e,{OuterConstant:{MSG_GRP_TIP:s,MSG_GRP_SYS_NOTICE:n}}=this._core,o=[s,n];t.forEach(e=>{!o.includes(e.type)&&e.clientTime>0&&this.addMessageDelay(e.clientTime)})}_calculateAverageDelay(e){return 0===e?0:Xl(this._totalDelay/e,1)}_calculatePercentage(e,t){return Xl(e/t*100,2)}};var Sd=new class{init(e){this.core=e}};var Cd=new class{constructor(){this.name="MessageQualityStat",this._reportIndex=0,this._wholePeriod=!1,this._pendingReports=[],this._failedLogsCache=new Map}install(e){this._core=e;const{helper:t,notificationCenter:s,InnerEvent:{QUALITY_STAT:n,LOGOUT:o,DESTROY:i},constants:{WORKFLOW_NAME:r,WORKFLOW_STEP:a}}=e;Sd.init(e),fd.init(e),Id.init(e),Ed.init(e),t.registerWorkflowStep(r.SYNC_SERVER_INFO_AFTER_LOGIN,a.QUALITY_REPORT,this.handleLoginSuccess,this),s.subscribeInnerEvent(n,this._handleQualityStat,this),s.subscribeInnerEvent(o,this._reset,this),s.subscribeInnerEvent(i,this._dispose,this)}handleLoginSuccess(){const{store:e,helper:t,utils:{isUndefined:s}}=this._core,n=e.get("cloudConfig")||{},{q_rpt_interval:o}=n,i=s(o)?12e4:Number(o);t.taskScheduler.addTask({id:vd,intervalMs:i,callback:this.report,context:this})}report(){this._wholePeriod=!0;const e=[..._d.map(e=>{const t=this._buildQualityReportItem(e);return t?Object.assign(Object.assign({},t),{report_index:this._reportIndex,whole_period:this._wholePeriod}):null}).filter(Boolean),...this._pendingReports];this._pendingReports=[],this._needSkipReport()||this._uploadQualityReports(e)}_handleQualityStat(e){const{constants:{QUALITY_METRICS:t}}=this._core,{label:s,data:n}=e;s===t.MESSAGE_SEND_SUCCESS_RATE&&fd.dispatchSendStats(n)}_needSkipReport(){return this._isSDKAppIDInBlacklist()&&!this._isTinyIDInWhitelist()}_isSDKAppIDInBlacklist(){const{store:e,utils:t}=this._core,s=e.get("cloudConfig")||{},n=e.get("instance")||{},{sdkAppId:o}=n,{q_rpt_sdkappid_bl:i=[]}=s;if(t.isEmpty(i))return;return i.split(",").map(e=>Number(e)).includes(o)}_isTinyIDInWhitelist(){const{store:e,utils:t}=this._core,s=e.get("cloudConfig")||{},n=e.get("login")||{},o=Number(n.tinyID),{q_rpt_tinyid_wl:i=[]}=s;if(!t.isEmpty(i))return i.split(",").includes(o)}_buildQualityReportItem(e){const t=this._getStatResultByKey(e);if(null===t)return null;const s={quality_type:hd[e],timestamp:Date.now(),network_type:td.ONLINE,extension:""};return Object.assign(Object.assign({},s),t)}_getStatResultByKey(e){switch(e){case nd:return Ed.getStatResult();case od:case id:case rd:case ad:case cd:return fd.getStatResult(e);case ud:case ld:case dd:return Id.getStatResult(e);default:return null}}_uploadQualityReports(e){return de(this,void 0,void 0,function*(){try{const t={header:this._core.common.getCommonHead(),quality:e};yield function(e){const{common:t,channel:s}=Sd.core,n="imopenstat.tim_web_report_v2",o=t.generateSSOLogProtocolData({servcmd:n,data:e}),i=`${o.head.seq}${n}`;s.sendPacket(o,{requestId:i})}(t),this._reportIndex++,this._wholePeriod=!1}catch(t){console.warn("doReport failed. error:",t),this._pendingReports=this._pendingReports.concat(e),this._cacheFailedLogs()}})}_cacheFailedLogs(){const e=this._pendingReports,t=`${Zl}._cacheFailedLogs`;let s=[...this._failedLogsCache.get(ed)||[],...e];s.length>10&&(s=s.slice(s.length-10),console.log(`${t} logs overflow, keeping last 10 items`)),this._failedLogsCache.set(ed,s),console.log(`${t} count: ${s.length}`),this._pendingReports=[]}_reset(){const{helper:e}=this._core;e.taskScheduler.removeTask(vd)}_dispose(){const{notificationCenter:e,InnerEvent:{QUALITY_STAT:t,LOGOUT:s,DESTROY:n}}=this._core;e.unSubscribeInnerEvent(t,this._handleQualityStat,this),e.unSubscribeInnerEvent(s,this._reset,this),e.unSubscribeInnerEvent(n,this._dispose,this),this._reset(),Ed.dispose(),Id.dispose()}};const Md=1,yd=300;var Od=new class{constructor(){this.name="OfflineMessageSynchronizer",this._lastMessageSequenceMapOnDisconnect=new Map}install(e){this._core=e;const{common:{workflowManager:t},constants:{WORKFLOW_NAME:s,WORKFLOW_STEP:n,InnerEvent:o}}=e;t.registerWorkflowStep(s.SYNC_SERVER_INFO_AFTER_RE_ONLINE,n.HISTORY_MESSAGE_RECOVER,this._syncOfflineMessage,this),e.notificationCenter.subscribeInnerEvent(o.SOCKET_DISCONNECTED,this._updateLastMessageSequenceMapOnDisconnect,this)}_syncOfflineMessage(e){const{conversationList:t}=(null==e?void 0:e.result)||{},{OuterConstant:s,utils:{isArray:n}}=this._core;if(n(t)){const e=t.filter(e=>e.type===s.CONV_GROUP&&e.groupProfile.type!==s.GRP_AVCHATROOM);return this._recoverGroupHistoryMessage(e)}}_recoverGroupHistoryMessage(e){return de(this,void 0,void 0,function*(){const{OuterConstant:t}=this._core,s=[],n=[];return yield Promise.all(null==e?void 0:e.map(e=>de(this,void 0,void 0,function*(){const{groupProfile:{groupID:o}={},lastMessage:{lastSequence:i}={}}=e,r=`${t.CONV_GROUP}${o}`;let a=this._getLocalLastMessageSequence(r);this._shouldRecoverHistory({localLastMessageSequence:a,serverLastMessageSequence:i})&&(yield this._recoverHistoryForConversation({conversationID:r,localLastMessageSequence:a,serverLastMessageSequence:i,groupTipList:n})),s.push(r.replace(t.CONV_GROUP,""))}))),{recoverRevokeNoticeGroupIDList:s,groupTipList:n}})}_recoverHistoryForConversation(e){return de(this,arguments,void 0,function*({conversationID:e,localLastMessageSequence:t,serverLastMessageSequence:s,groupTipList:n}){try{const{utils:{isArray:o,isObject:i,isEmpty:r},OuterEvent:a,OuterConstant:c,notificationCenter:u,message:l,appStore:d,common:{getMessagePreviewText:h}}=this._core,g=s-t,p=Math.min(20,g),_={},m=yield l.messageHistory.getGroupRoamingMessagesByAnchor({conversationID:e,sequence:t+p,direction:c.Direction.FORWARD,count:p}),{nextReqMessageIDFromServer:v,hasNoMoreHistoryMessage:f,messageList:I,serverGroupTipList:E}=m;o(E)&&n.push(...E);const S=f&&v<0,C=[];if(o(I)&&(I.forEach(e=>{l.messageReceiver.groupMessageReceiver.updateMessageProfile(e),e.from===c.CONV_SYSTEM&&(e.isSystemMessage=!1);l.messageDataHandler.storeConversationMessage(e)&&!r(e.payload)&&(C.push(e),e._isExcludedFromLastMessage||(_.lastMessage=Object.assign({},e)))}),C.length>0&&u.emitOuterEvent(a.MESSAGE_RECEIVED,{name:a.MESSAGE_RECEIVED,data:C})),!S&&I.length>0){const t=I[I.length-1].sequence;yield this._recoverHistoryForConversation({conversationID:e,localLastMessageSequence:t,serverLastMessageSequence:s,groupTipList:n})}i(_.lastMessage)&&(_.lastMessage.messageForShow=h(_.lastMessage.type,_.lastMessage.payload),d.conversationStore.updateConversation(e,_))}catch(t){this._core.ssoLog.error("_recoverHistoryForConversation",`Recovery failed for conversation:${e}`,{error:t})}})}_updateLastMessageSequenceMapOnDisconnect(){const{message:e}=this._core,t=e.messageDataHandler.getContinuousMessagesByConversation();for(const[e,s]of t){if(e.startsWith("C2C"))continue;const t=Array.from(s.values());if((null==t?void 0:t.length)>0){const s=t[t.length-1].sequence;this._lastMessageSequenceMapOnDisconnect.set(e,s)}}}_getLocalLastMessageSequence(e){const{message:t}=this._core;if(this._lastMessageSequenceMapOnDisconnect.has(e))return this._lastMessageSequenceMapOnDisconnect.get(e);const s=t.messageDataHandler.getLocalMessageList(e),n=s[s.length-1];return null==n?void 0:n.sequence}_shouldRecoverHistory(e){const{localLastMessageSequence:t,serverLastMessageSequence:s}=e;if("number"!=typeof t||"number"!=typeof s)return!1;const n=s-t;return 0!==s&&t>0&&(n>=Md&&n<yd)}};var Ad=new class{init(e){this.core=e}};var Td=new class{constructor(){this._reportedAtomicStoreIDs=new Set}init(e){const{helper:{registerExperimentalAPI:t}}=e;this._core=e,t("reportModalView",this),t("reportTUIFeatureUsage",this)}reportModalView(e){const{ssoLog:t,utils:{safeStringify:s,isString:n}}=this._core;try{if(!n(e))throw new Error("reportModalView data is not a string");t.createSSOLogData({method:"reportModalView",message:e,eventType:30}).end(!0)}catch(e){t.debug(`reportModalView Report failed: ${s(e)}`)}}reportTUIFeatureUsage(e){const{ssoLog:t,utils:{safeStringify:s,isEmpty:n}}=this._core,{atomicStoreID:o}=e;try{n(o)||this._reportedAtomicStoreIDs.has(o)||(this._core.ssoLog.info("reportTUIFeatureUsage",`atomicStoreID: ${e.atomicStoreID}`,{method:"reportTUIFeatureUsage",eventType:31,code:o}),this._reportedAtomicStoreIDs.add(o))}catch(e){t.debug(`reportTUIFeatureUsage Report failed: ${s(e)}`)}}reset(){this._reportedAtomicStoreIDs.clear()}dispose(){this.reset()}};var Rd=new class{install(e){this._core=e;const{notificationCenter:t,InnerEvent:{LOGOUT:s,DESTROY:n}}=e;Ad.init(e),Td.init(e),t.subscribeInnerEvent(s,this._reset,this),t.subscribeInnerEvent(n,this._dispose,this)}_reset(){Td.reset()}_dispose(){const{notificationCenter:e,InnerEvent:{LOGOUT:t,DESTROY:s}}=this._core;e.unSubscribeInnerEvent(t,this._reset,this),e.unSubscribeInnerEvent(s,this._dispose,this),Td.dispose()}};let Dd=Rs.STANDARD,bd=[];Dd=Rs.STANDARD,bd=[$n,Fn,Bn,Xn,to,Cd,Od,Rd,qi,Zr,wa,Zu,Ll,Ql,bo];var Nd=Object.freeze({__proto__:null,ChatError:Xs,WorkflowManager:ln,buildAndSendPacket:mn,get builtInPlugins(){return bd},checkBusinessCapabilityBits:un,deepMerge:Cn,getCurrentUserID:En,getErrorMessage:Qs,getMessagePreviewText:Mn,isC2CConv:e=>t(e)&&e.slice(0,3)===Is.CONV_C2C,isCommunity:hn,isGroupConv:e=>t(e)&&e.slice(0,5)===Is.CONV_GROUP,isTopic:gn,isUnlimitedAVChatRoom:function(){var e;return!!(null===(e=ts.store.get("instance"))||void 0===e?void 0:e.unlimitedAVChatRoom)},liteChatInstanceMap:dn,registerInterceptor:an,registerValidateConfig:cn,requireAuth:Zs,get sdkEdition(){return Dd},updateGroupAtInfo:(e,t)=>{const{CONV_AT_ME:s,CONV_AT_ALL:n,CONV_AT_ALL_AT_ME:o}=As;if(function(e,t){const{CONV_AT_ME:s,CONV_AT_ALL:n,CONV_AT_ALL_AT_ME:o}=As,{groupID:i,sequence:r}=e;let a=!1;if(!hn({groupID:i}))return a;return t.forEach(t=>{t.messageSequence===r&&(t.atTypeArray.includes(s)&&e.groupAtType.includes(n)&&(t.atTypeArray=[o]),t.atTypeArray.includes(n)&&e.groupAtType.includes(s)&&(t.atTypeArray=[o],t.__random=e.__random,t.__sequence=e.__sequence),a=!0)}),a}(e,t))return;let i=[...e.groupAtType];i.includes(s)&&i.includes(n)&&(i=[o]);const r={from:e.from,groupID:e.groupID,topicID:e.topicID,messageSequence:e.sequence,atTypeArray:i,__random:e.__random,__sequence:e.__sequence};t.push(r)},validateAndExecute:rn,validateParameters:en});class Ld{constructor(){this._builtInPlugins=new Set,this._externalPlugins=new Set}static getInstance(){return Ld._instance||(Ld._instance=new Ld),Ld._instance}static setInstance(e){Ld._instance=e}installBuiltInPlugin(e){e&&this._installPlugin(e,this._builtInPlugins)}installExternalPlugin(e){e&&this._installPlugin(e,this._externalPlugins)}clear(){this._builtInPlugins=new Set,this._externalPlugins=new Set}_installPlugin(e,t){let s=[];s=n(e)?e:[e];const o=s.findIndex(e=>"AVChatRoom"===(null==e?void 0:e.name)),i=o>-1?s.splice(o,1):[];s.forEach(e=>{this._isPluginInstalled(e.name)||(e&&ss(e.install)?(t.add(e.name),ss(e.getInstalledSubPlugins)?e.install(Fd.getInstance().exposeApiForPlugin(),i):e.install(Fd.getInstance().exposeApiForPlugin()),ss(e.handleLoginSuccess)&&this._isLoggedIn()&&e.handleLoginSuccess()):ss(e)?(t.add(e.name),e(Fd.getInstance().exposeApiForPlugin()),ss(e.handleLoginSuccess)&&this._isLoggedIn()&&e.handleLoginSuccess()):console.warn('A plugin must either be a function or an object with an "install" function.'))})}_isPluginInstalled(e){return this._builtInPlugins.has(e)||this._externalPlugins.has(e)}_isLoggedIn(){var e;return!0===(null===(e=ts.store.get("login"))||void 0===e?void 0:e.isLoggedIn)}}var Pd=new class{constructor(){this._conversationMap=new Map}getConversationMap(){return this._conversationMap}getConversation(e){return this._conversationMap.get(e)}updateConversation(e,t,s={emit:!0,needSort:!1}){const{emit:n,needSort:o}=s,i=this._conversationMap.get(e);i&&!ve(t)&&(Object.keys(t).forEach(e=>{i[e]=t[e]}),n&&ts.notificationCenter.emitInnerEvent(cs.CONVERSATION_UPDATED,{needSort:o}))}deleteConversation(e){this._conversationMap.has(e)&&(this._conversationMap.delete(e),ts.notificationCenter.emitInnerEvent(cs.CONVERSATION_UPDATED))}};var wd=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&&!ve(t)&&Object.keys(t).forEach(e=>{s[e]=t[e]})}};var Gd=new class{constructor(){this._messagesByConversation=new Map}updateMessage(e,t,s){var n;const{operation:o,updateUnreadCount:i=!0}=s,r=le(s,["operation","updateUnreadCount"]),a=[];for(const s of t){const t=null===(n=this._messagesByConversation.get(e))||void 0===n?void 0:n.get(s);if(!t)return!1;Object.keys(r).forEach(e=>{t[e]=r[e]}),a.push(t)}return this._emitMessageStoreOperationEvent(o,{conversationID:e,messageList:a,updateUnreadCount:i}),a}getMessagesByConversation(e){var t;return[...(null===(t=this._messagesByConversation.get(e))||void 0===t?void 0:t.values())||[]]}getMessages(){return this._messagesByConversation}_emitMessageStoreOperationEvent(e,t){const{conversationID:s}=t;gn(s)?ts.notificationCenter.emitInnerEvent(ms[e],t):ts.notificationCenter.emitInnerEvent(e,t)}};var Ud=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)}},kd=Object.freeze({__proto__:null,conversationStore:Pd,groupStore:wd,messageStore:Gd,userStore:Ud});class Fd{static getInstance(){return Fd._instance||(Fd._instance=new Fd),Fd._instance}static setInstance(e){Fd._instance=e}constructor(){this._experimentalApiMap={statTUIKeyFeatures:this.statKeyFeatureUsage.bind(this),setApplicationID:this.setApplicationID.bind(this)},this._apiHandlersMap={},this._apiMap={on:ts.notificationCenter.subscribeOuterEvent.bind(ts.notificationCenter),off:ts.notificationCenter.unSubscribeOuterEvent.bind(ts.notificationCenter),destroy:this.destroy.bind(this),callExperimentalAPI:this.callExperimentalAPI.bind(this),use:Ld.getInstance().installExternalPlugin.bind(Ld.getInstance()),registerPlugin:this.registerPlugin.bind(this),setLogLevel:this.setLogLevel.bind(this)}}registerPlugin(e){ts.ssoLog.debug("registerPlugin",e)}statKeyFeatureUsage(e){ts.ssoLog.debug("statTUIKeyFeatures",e)}setLogLevel(e){ts.ssoLog.debug("setLogLevel",e),ts.ssoLog.setLogLevel(e)}setApplicationID(e){ts.store.set("instance",{applicationID:e})}getApiMap(){return this._apiMap}setApiMap(e){this._apiMap=e}registerApi(e){const{common:{timeManager:t},utils:{safeStringify:s}}=ts,{apiName:n,context:o,methodName:i=n,matcher:r}=e;this._apiHandlersMap[n]||(this._apiHandlersMap[n]=[]),this._apiHandlersMap[n].push({context:o,methodName:i,matcher:r}),this._apiMap[n]&&1!==this._apiHandlersMap[n].length||(this._apiMap[n]=(...e)=>{let o=t.getServerTimeMs(),r=0;"login"===n&&(r=4),ws.includes(n)&&ts.ssoLog.debug(n,`${n} start params: ${s(e)}`),rn(i,e);const a=this._apiHandlersMap[n];for(const s of a)if(!s.matcher||s.matcher(e))try{const t=s.context[s.methodName].bind(s.context)(...e);return this._isPromiseLike(t)?this._handleAsyncResult(t,n,r,o):(this._reportApiSuccessLog({result:t,apiName:n,eventType:r,startTime:o}),t)}catch(e){throw ts.ssoLog.error(n,`${n} fail ${(null==e?void 0:e.errorMessage)||(null==e?void 0:e.message)})`,{error:e,costTime:t.getServerTimeMs()-o,eventType:r,method:n}),e}})}registerExperimentalAPI(e,t,s){const n=s||e;this._experimentalApiMap[e]=t[n].bind(t)}destroy(){return de(this,void 0,void 0,function*(){var e,t;try{(null===(e=ts.store.get("login"))||void 0===e?void 0:e.isLogin)&&(yield this._apiMap.logout()),ts.notificationCenter.emitInnerEvent(cs.DESTROY)}catch(e){console.debug("destroy error: ",e)}finally{ts.notificationCenter.emitOuterEvent(rs.SDK_DESTROY,{SDKAppID:null===(t=ts.store.get("instance"))||void 0===t?void 0:t.sdkAppId}),dn.clear(),Ld.getInstance().clear(),ln.getInstance().destroy(),ts.destroy()}})}exposeApiForClient(){return this._apiMap}exposeApiForPlugin(){return Object.assign(Object.assign({InnerEvent:cs,InnerEventSubType:ts.notificationCenter.InnerEventSubType,OuterEvent:rs,OuterConstant:As,SignalingEvent:us,helper:Object.assign(Object.assign(Object.assign({},ts.utils),ts.common),{registerApi:this.registerApi.bind(this),registerExperimentalAPI:this.registerExperimentalAPI.bind(this),registerInterceptor:an,registerValidateConfig:cn,checkBusinessCapabilityBits:un,registerWorkflowStep:ln.getInstance().registerWorkflowStep.bind(ln.getInstance()),ChatError:Xs}),apiMap:this._apiMap},ts),{constants:Object.assign(Object.assign({},Gs),ts.constants),common:Object.assign(Object.assign(Object.assign({},Nd),ts.common),{workflowManager:ln.getInstance()}),utils:ts.utils,appStore:kd})}callExperimentalAPI(e,t){return ts.ssoLog.debug(`callExperimentalAPI.${e} start params: ${ts.utils.safeStringify(t)}`),this._experimentalApiMap[e]?this._experimentalApiMap[e](t):Promise.reject(new Xs({code:Ts.INVALID_OPERATION}))}_isPromiseLike(e){return null!==e&&"object"==typeof e&&"function"==typeof e.then}_handleAsyncResult(e,t,s,n){return e.then(e=>(this._reportApiSuccessLog({result:e,apiName:t,eventType:s,startTime:n}),e)).catch(e=>{throw ts.ssoLog.error(t,`${t} fail ${(null==e?void 0:e.errorMessage)||(null==e?void 0:e.message)})`,{error:e,costTime:ts.common.timeManager.getServerTimeMs()-n,eventType:s,method:t}),e})}_reportApiSuccessLog(e){let{result:t,apiName:s,startTime:n,eventType:o}=e;const{timeManager:i}=ts.common,{successLog:{message:r,moreMessage:a}={message:"",moreMessage:""}}=t||{},c=i.getServerTimeMs();"login"===s&&(n+=i.getTimeOffsetWithServer()),ws.includes(s)&&ts.ssoLog.info(s,`${s} success ${r} ${a}`,{costTime:c-n,eventType:o,message:r,moreMessage:a}),(null==t?void 0:t.successLog)&&delete t.successLog}}class $d{constructor(){this._latestLoginAt=0,this._latestSendOnlinePresenceRequestTime=0,this._helloInterval=120,this._customLoginInfo=""}init(){const{notificationCenter:e,store:t}=ts;t.set("login",{isReady:!1}),Fd.getInstance().registerApi({apiName:"login",context:this}),Fd.getInstance().registerApi({apiName:"logout",context:this}),Fd.getInstance().registerApi({apiName:"getLoginUser",context:this}),Fd.getInstance().registerApi({apiName:"isReady",context:this}),Fd.getInstance().registerExperimentalAPI("setCustomLoginInfo",this),e.subscribeInnerEvent(cs.RECONNECTED,this._reLogin,this),ts.notificationCenter.subscribeInnerEvent(cs.DESTROY,this._dispose,this)}login(e){return de(this,void 0,void 0,function*(){var t;const{sdkEdition:s}=ts.store.get("instance")||{};try{if(this._isLoginIn())return this._createRepeatLoginResponse();if(this._isLoginFrequencyExceeded())throw new Xs({functionName:"login",code:Ts.REPEAT_LOGIN});const n=yield this._performLogin(e);this._validateAfterLogin(n),this._handleLoginSuccess(n),yield this._ensureAsyncComplete(),this._updateAndEmitSDKReady(),this._latestLoginAt=0;const o=null===(t=ts.channel.getSocketAdapter())||void 0===t?void 0:t.getId(),{appId:i,href:r}=ts.store.get("instance")||{},{instanceID:a,customStatus:c}=n||{};return{code:0,data:n,successLog:{message:s,moreMessage:`socketID:${o} instanceID:${a} customStatus:${c} href: ${r} appId: ${i}`}}}catch(e){const{errorCode:t}=e;t!==Ts.REPEAT_LOGIN&&(this._latestLoginAt=0);const s=new Xs({functionName:"login",code:t});throw console.error(s),s}})}_reLogin(){return de(this,void 0,void 0,function*(){var e;try{if(!this._isLoginIn())return;const t=yield Js(this._customLoginInfo);if(t){const{instanceID:s,customStatus:n}=t;ts.store.set("login",{statusInstanceId:s}),ln.getInstance().executeWorkflow(Ds.SYNC_SERVER_INFO_AFTER_RE_ONLINE,{customStatus:n,statusType:vs.USER_STATUS_ONLINE});const o=null===(e=ts.channel.getSocketAdapter())||void 0===e?void 0:e.getId();ts.ssoLog.info("reLogin",`socketId:${o} instanceId:${s}`)}}catch(e){console.warn(e)}})}logout(){return de(this,arguments,void 0,function*(e=Us.USER_INITIATED){const{ssoLog:t}=ts;t.debug("logout",`logout start logoutReason: ${e}`);try{yield this._performLogout(e),t.info("logout","logout success"),ts.ssoLog.uploadSSOLogData()}catch(e){const{errorCode:t}=e;throw new Xs({functionName:"logout",code:t})}finally{this._handleLogoutCompleted()}return{code:0,data:{}}})}getLoginUser(){return this._isLoginIn()?En():""}isReady(){var e;return null===(e=ts.store.get("login"))||void 0===e?void 0:e.isReady}setCustomLoginInfo(e=""){this._customLoginInfo=e}_updateAndEmitSDKReady(){ts.store.set("login",{isReady:!0}),setTimeout(()=>{ts.notificationCenter.emitOuterEvent(rs.SDK_READY,{name:rs.SDK_READY})},1)}_updateAndEmitSDKNotReady(){ts.store.set("login",{isReady:!1}),ts.notificationCenter.emitOuterEvent(rs.SDK_NOT_READY,{name:rs.SDK_NOT_READY})}_validateAfterLogin(e){const t="login";if(!e)throw new Xs({functionName:t,message:"login response is empty"});const{tinyID:s,a2Key:n}=e||{};if(!s){throw new Xs({functionName:t,code:Ts.NO_TINYID})}if(!n){throw new Xs({functionName:t,code:Ts.NO_A2KEY})}}_createRepeatLoginResponse(){var e;return{code:0,data:{actionStatus:"OK",errorCode:0,errorInfo:Qs({code:"RepeatLogin",replacement1:null===(e=ts.store.get("login"))||void 0===e?void 0:e.userId}),repeatLogin:!0}}}_performLogin(e){return de(this,void 0,void 0,function*(){const{userID:t,userSig:s}=e;return ts.store.set("login",{userId:t,userSig:s}),this._latestLoginAt=Date.now(),Js(this._customLoginInfo)})}_ensureAsyncComplete(){return de(this,void 0,void 0,function*(){yield new Promise(e=>{setTimeout(()=>e(null),1)})})}_handleLoginSuccess(e){const{timeManager:t}=ts.common,{helloInterval:s,timeStamp:n,customStatus:o,purchaseBits:i}=e,r=1e3*n;t.calculateTimeOffsetWithServer(this._latestLoginAt,r),this._helloInterval=s||120,this._updateLoginStore(e),ts.user.userStatus.setCustomStatus(o),ln.getInstance().executeWorkflow(Ds.SYNC_SERVER_INFO_AFTER_LOGIN,{purchaseBits:i}),ts.common.taskScheduler.addTask({id:qs,intervalMs:1e3*this._helloInterval,callback:this._sendOnlinePresenceRequest,context:this})}_performLogout(e){return function(e){return de(this,void 0,void 0,function*(){const{logoutReason:t}=e,s="im_open_status.wslogout",n=ts.common.generateProtocolData({servcmd:s,data:{wslogout_type:t,isWebUniapp:0}}),o=`${n.head.seq}${s}`;return yield ts.channel.sendPacket(n,{requestId:o})})}({logoutReason:e})}_handleLogoutCompleted(){this._updateAndEmitSDKNotReady(),this._reset(),ln.getInstance().reset(),ts.notificationCenter.emitInnerEvent("logout")}_updateLoginStore(e){const{a2Key:t,tinyID:s,instanceID:n,authKey:o}=e;ts.store.set("login",{a2Key:t,tinyID:s,statusInstanceId:n,authKey:o,isLoggedIn:!0})}_sendOnlinePresenceRequest(){return de(this,void 0,void 0,function*(){this._latestSendOnlinePresenceRequestTime=Date.now();try{yield function(){const e="im_open_status.wshello",t=ts.common.generateProtocolData({servcmd:e,data:{isWebUniapp:0}}),s=`${t.head.seq}${e}`;return ts.channel.sendPacket(t,{requestId:s})}()}catch(e){ts.ssoLog.warn("_sendOnlinePresenceRequest",` error:${e.message}`)}})}_isLoginIn(){var e;return!0===(null===(e=ts.store.get("login"))||void 0===e?void 0:e.isLoggedIn)}_isLoginFrequencyExceeded(){return Date.now()-this._latestLoginAt<=15e3}_reset(){ts.common.taskScheduler.removeTask(qs),this._helloInterval=120,this._latestSendOnlinePresenceRequestTime=0,this._latestLoginAt=0,this._customLoginInfo="",ts.store.clear("login"),ts.store.set("login",{isReady:!1}),ts.store.set("instance",{applicationID:0})}_dispose(){this._reset();const{notificationCenter:e}=ts;e.unSubscribeInnerEvent(cs.RECONNECTED,this._reLogin,this),e.unSubscribeInnerEvent(cs.DESTROY,this._dispose,this)}}const qd={login:{userID:{required:!0,rules:["string"],allowEmpty:!1},userSig:{required:!0,rules:["string"],allowEmpty:!1}}},xd={logout:!0};class Vd{constructor(){this.loginAction=new $d,this.kickedOutHandler=new zs,this.loginAction.init(),this.kickedOutHandler.init(),cn({auth:xd,params:qd})}}var Bd,Kd,Hd;!function(e){e.CONV_C2C="C2C",e.CONV_GROUP="GROUP",e.CONV_TOPIC="TOPIC",e.CONV_SYSTEM="@TIM#SYSTEM"}(Bd||(Bd={})),function(e){e.MSG_PRIORITY_HIGH="High",e.MSG_PRIORITY_NORMAL="Normal",e.MSG_PRIORITY_LOW="Low",e.MSG_PRIORITY_LOWEST="Lowest"}(Kd||(Kd={})),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"}(Hd||(Hd={}));const Wd={1:Kd.MSG_PRIORITY_HIGH,2:Kd.MSG_PRIORITY_NORMAL,3:Kd.MSG_PRIORITY_LOW,4:Kd.MSG_PRIORITY_LOWEST},Yd=0,zd=1;var Jd;!function(e){e.IN="in",e.OUT="out"}(Jd||(Jd={}));const Qd=2,Xd={};function Zd(e){if(!e)return 0;if(void 0===Xd[e]){const t=new Date,s=`3${t.getHours()}`.slice(-2),n=`0${t.getMinutes()}`.slice(-2),o=`0${t.getSeconds()}`.slice(-2);Xd[e]=parseInt([s,n,o,"0001"].join(""),10),console.log(`autoIncrementIndex start index:${Xd[e]}`)}else Xd[e]+=1;return Xd[e]}class eh{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=Kd.MSG_PRIORITY_NORMAL,this._relayFlag=!1;const{clientTime:t=ts.common.timeManager.getServerTimeSeconds()||0,senderTinyID:s,currentUser:n,needReadReceipt:o,isSupportExtension:i,customModerationConfigurationId:r,to:a,from:c,nick:u="",avatar:l="",time:d,messageControlInfo:h,tinyID:g,cloudCustomData:p="",messageLifeTime:_,messageVersion:m=0,conversationType:v,sequence:f,checkResult:I=0,isPlaceMessage:E=0,messageFlagBits:S,receiverList:C,isSystemMessage:M=!1,status:y=hs.SUCCESS,revokeReason:O="",conversationSubType:A,clientSequence:T,protocol:R="JSON",revokerInfo:D={userID:"",nick:"",avatar:""},readReceiptInfo:b={readCount:void 0,unreadCount:void 0,isPeerRead:void 0,timestamp:0},random:N,groupProfile:L,atUserList:P,flow:w,isRead:G=!1}=e;var U;this.clientTime=t,this.senderTinyID=s||g,this.needReadReceipt=!0===o||1===o,this.isSupportExtension=!0===i||1===i,this._cmConfigID=r,this.to=a,this.nick=u,this.avatar=l,this.protocol=R,this.random=void 0===N?(U=U||99999999,Math.round(Math.random()*U)):N,this.time=d||Math.ceil(Date.now()/1e3),this._isExcludedFromLastMessage=!!(null==h?void 0:h.excludedFromLastMessage),this._isExcludedFromUnreadCount=!!(null==h?void 0:h.excludedFromUnreadCount),this.isModified=!!m,this.cloudCustomData=p,this.messageLifeTime=_,this.from=c||null,this.sequence=f||0,this.conversationType=v||Bd.CONV_C2C,this.hasRiskContent=I>1,this.version=m,this.isPlaceMessage=E,this.isRevoked=2===E||8===S,this.isSystemMessage=M,this.readReceiptInfo=b,this.revokeReason=O,this.revokerInfo=D,this._receiverList=C,this.conversationSubType=A,this.revoker=(null==D?void 0:D.revoker)||"",this.clientSequence=T||f||0,this.status=y,this.atUserList=P||[],this.flow=w,this.isRead=G,this.reInitialize(n),this._initC2CReadReceiptInfo(e),this._extractGroupInfo(L)}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===Bd.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:n}=e,{NameCard:o}=n||{};"string"==typeof t&&(this.nick=t),"string"==typeof s&&(this.avatar=s),"string"==typeof o&&(this.nameCard=o)}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!==Bd.CONV_SYSTEM?(t=s===Bd.CONV_C2C?e===this.from?this.to:this.from:this.to,this.conversationID=t?`${s}${t}`:null):this.conversationID=Bd.CONV_SYSTEM}_initSequence(e){0===this.clientSequence&&e&&(this.clientSequence=Zd(e)),0===this.sequence&&this.conversationType===Bd.CONV_C2C&&(this.sequence=this.clientSequence)}generateMessageID(){this.from===Bd.CONV_SYSTEM&&(this.senderTinyID="144115198244471703"),this.ID=`${this.senderTinyID}-${this.clientTime}-${this.random}`}setIsRead(e){this.isRead=e}}class th{static parseServerPushElement(e){const{MsgContent:t={}}=e,{Data:s,Ext:n,Desc:o}=t;return new th({data:s,description:o,extension:n})}constructor(e){this.type=Hd.MSG_CUSTOM;const{data:t="",description:s="",extension:n=""}=e;this.content={data:t,description:s,extension:n}}transformToServerFormat(e){const{isMergerMessage:t=!1}=e||{},s=t?this.payload:this.content,{data:n,description:o,extension:i}=s;return{MsgType:this.type,MsgContent:{Data:n,Ext:i,Desc:o}}}validateBeforeSend(){const{isEmpty:e}=ts.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 sh{static parseServerPushElement(e){const{MsgContent:t={Text:""}}=e,{Text:s}=t;return new sh({text:s})}constructor(e){this.type=ds.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:n}=s;return{MsgType:this.type,MsgContent:{Text:n}}}}var nh=new class{constructor(){this._elementClassMap={[Hd.MSG_CUSTOM]:th,[Hd.MSG_TEXT]:sh}}init(){Fd.getInstance().registerApi({apiName:"createCustomMessage",context:this}),Fd.getInstance().registerApi({apiName:"createTextMessage",context:this})}registerElementClass(e,t){var s;void 0!==(s=t).prototype&&"constructor"in s.prototype&&(this._elementClassMap[e]=t)}getElementClass(e){return this._elementClassMap[e]}createMessage(e){const{from:t,flow:s=Jd.OUT}=e,{userId:n}=ts.store.get("login")||{};this._isSendByCurrentInstance({from:t,flow:s,currentUser:n})?this._updateWithSenderInfo(e):this._isMultiEndpointSyncMessage({from:t,flow:s,currentUser:n})&&(e.flow=Jd.OUT);const o=Object.assign(Object.assign({},e),{currentUser:n});return new eh(o)}createCustomMessage(e){const t=En(),s=this.createMessage(Object.assign(Object.assign({},e),{from:t})),n=this._elementClassMap[Hd.MSG_CUSTOM];if(!s)return null;if(n){const t=new n(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)||"",n=new sh({text:s}),o=En(),i=ts.message.messageFactory.createMessage(Object.assign(Object.assign({},e),{from:o}));return i.setElement(n),i}_updateWithSenderInfo(e){const{nick:t,avatar:s}=e,{userId:n,tinyID:o}=ts.store.get("login")||{},i=Ud.getUserProfile(n);return e.nick=t||(null==i?void 0:i.nick)||"",e.avatar=s||(null==i?void 0:i.avatar)||"",e.tinyID=e.tinyID||o||"",e.from=n,e.status=hs.UNSENT,e.flow=Jd.OUT,e}_isMultiEndpointSyncMessage(e){const{from:t,flow:s,currentUser:n}=e;return t===n&&s===Jd.IN}_isSendByCurrentInstance(e){const{from:t,flow:s,currentUser:n}=e;return t===n&&s===Jd.OUT}};const oh={PushFlag:0,Title:"",Desc:"",Ext:"",ApnsInfo:{Sound:"",BadgeMode:0,IsVoipPush:void 0,Image:"",InterruptionLevel:"active",ContentAvailable:0},AndroidInfo:{Sound:"",XiaoMiChannelID:"",OPPOChannelID:"",GoogleChannelID:"",VIVOClassification:1,VIVOCategory:"",HuaWeiCategory:"",OPPOCategory:"",HuaWeiImage:"",HonorImage:"",GoogleImage:"",HonorImportance:"",MeizuNotifyType:void 0}},ih={HonorImportance:{range:["LOW","NORMAL"],defaultValue:void 0},MeizuNotifyType:{range:[0,1],defaultValue:void 0}},rh={enableIOSBackgroundNotification:{range:[!0,!1],defaultValue:!1},interruptionLevel:{range:["passive","active","time-sensitive","critical"],defaultValue:"active"}};function ah(e,t){return Object.keys(t).forEach(s=>{const{range:n,defaultValue:o}=t[s];e[s]=n.includes(e[s])?e[s]:o}),e}function ch(e){const t=e.lastIndexOf(".");return-1===t?e:e.slice(0,t)}function uh(e){const{androidInfo:t={},androidOPPOChannelID:s=""}=e,n=t.OPPOChannelID||s,o=ah(t,ih),{sound:i="",FCMChannelID:r=""}=o,a=le(o,["sound","FCMChannelID"]);return Object.assign(Object.assign({},a),{Sound:ch(i),OPPOChannelID:n,GoogleChannelID:r})}function lh(t){const{apnsInfo:s={},ignoreIOSBadge:n=!1,disableVoipPush:o}=t,i=ah(s,rh),{ignoreIOSBadge:r,disableVoipPush:a,enableIOSBackgroundNotification:c}=i,u=le(i,["ignoreIOSBadge","disableVoipPush","enableIOSBackgroundNotification"]),l=!0===r||!0===n?1:0;let d;return e(o)||(d=!1===o?1:0),e(a)||(d=!1===a?1:0),Object.assign(Object.assign({},u),{BadgeMode:l,IsVoipPush:d,ContentAvailable:c?1:0})}function dh(e){return ts.utils.isPlainObject(e)?{PushFlag:!0===e.disablePush?1:0,Title:e.title||"",Desc:e.description||"",Ext:e.extension||"",ApnsInfo:lh(e),AndroidInfo:uh(e)}:oh}function hh(e){const{From_AccountHeadurl:t,From_AccountNick:s,IsNeedReadReceipt:n,IsPeerRead:o,IsSyncMsg:i,MsgBody:r,MsgClientTime:a,MsgLifeTime:c,MsgRandom:u,MsgSeq:l,MsgTimeStamp:d,SendMsgControl:h,SupportMessageExtension:g,TinyId:p,MsgCheckResult:_,CloudCustomData:m,MsgVersion:v,MsgFlagBits:f,RevokerInfo:I}=e;let E,{From_Account:S,To_Account:C}=e;if(1===i){const e=C;C=S,S=e}if(I){const{Reason:e,Revoker_Account:t,Revoker_FromUin:s}=I;E={reason:e,revoker:t,revokerFromUin:s,userID:t}}return{from:S,avatar:t,nick:s,needReadReceipt:1===n,isSyncMessage:i,clientTime:a,messageLifeTime:c,random:u,sequence:l,time:d,messageControlInfo:{excludedFromLastMessage:1===(null==h?void 0:h.NoLastMsg),excludedFromUnreadCount:1===(null==h?void 0:h.NoUnread)},isSupportExtension:g,to:C,tinyID:p,checkResult:_,cloudCustomData:m,revokerInfo:E,messageVersion:v,messageFlagBits:f,readReceiptSentByPeer:o,elements:mh(r)}}function gh(e){const{From_Account:t,MsgBody:s,MsgClientTime:n,MsgRandom:o,MsgSeq:i,MsgTimeStamp:r,To_Account:a,MsgVersion:c,CloudCustomData:u}=e;return{from:t,clientTime:n,random:o,sequence:i,time:r,to:a,elements:mh(s),messageVersion:c,cloudCustomData:u}}function ph(e){const{ClientSeq:t,From_Account:s,GroupInfo:n,MsgBody:o,MsgClientTime:i,MsgRandom:r,MsgSeq:a,MsgTimeStamp:c,SendMsgControl:u,SupportMessageExtension:l,TinyId:d,CloudCustomData:h,MsgVersion:g,MsgCheckResult:p,NeedReadReceipt:_,IsPlaceMsg:m,RevokerInfo:v,GroupAtInfo:f}=e;let I,E=Kd.MSG_PRIORITY_NORMAL;if(Object.keys(Wd).includes(String(e.MsgPriority))&&(E=Wd[e.MsgPriority]),v){const{Reason:e,Revoker_Account:t,Revoker_FromUin:s}=v;I={reason:e,revoker:t,revokerFromUin:s,userID:t}}const S=function(e){const t=[];Array.isArray(e)&&e.forEach(e=>{e.GroupAtAllFlag===Yd?t.push(e.GroupAt_Account):e.GroupAtAllFlag===zd&&t.push(As.MSG_AT_ALL)});return t}(f);return{clientSequence:t,from:s,groupProfile:n,clientTime:i,priority:E,random:r,sequence:a,time:c,messageControlInfo:{excludedFromLastMessage:1===(null==u?void 0:u.NoLastMsg),excludedFromUnreadCount:1===(null==u?void 0:u.NoUnread)},isSupportExtension:l,tinyID:d,cloudCustomData:h,messageVersion:g,messageCheckResult:p,needReadReceipt:_,isPlaceMessage:m,revokerInfo:I,atUserList:S,elements:mh(o),to:_h(e)}}function _h(e){const{utils:{isEmpty:t},constants:{IS_TOPIC_MESSAGE:s}}=ts,{ToGroupId:n,GroupInfo:{MillionGroupFlag:o=0,TopicId:i}={}}=e;return o!==s||t(i)?n:i}function mh(e){if(!e)return null;if(Array.isArray(e))return e.map(e=>{const t=ts.message.messageFactory.getElementClass(e.MsgType);return null==t?void 0:t.parseServerPushElement(e)});const t=ts.message.messageFactory.getElementClass(e.MsgType);return null==t?void 0:t.parseServerPushElement(e)}function vh(e){const{From_Account:t,MsgBody:s,MsgClientTime:n,MsgRandom:o,MsgSeq:i,MsgTimeStamp:r,GroupId:a,TopicId:c,MsgVersion:u,CloudCustomData:l}=e;return{from:t,clientTime:n,random:o,sequence:i,time:r,groupID:a,topicID:c,elements:mh(s),messageVersion:u,cloudCustomData:l}}function fh({conversationUpdateFields:e,message:t}){const{conversationID:s,conversationType:n,conversationSubType:o,flow:i,_isExcludedFromUnreadCount:r,_isExcludedFromLastMessage:a}=t,c=a?"":t,u=!r&&i===Jd.IN;e.has(s)?(e.get(s).lastMessage=c,u&&e.get(s).unreadCount++):e.set(s,{conversationID:s,type:n,subType:o,unreadCount:u?1:0,lastMessage:c})}function Ih(e){return e.filter(e=>{const t=!ve(null==e?void 0:e.getElements()),s=1===(null==e?void 0:e.isPlaceMessage);return t||ts.ssoLog.error("emptyMessageBody",`from:${e.from} to:${e.to} sequence:${e.sequence}`),t&&!s})}function Eh(e){const{messageDataHandler:t}=ts.message;return!t.isInMessageList(e)&&!t.isMessageSentByCurrentInstance(e)}var Sh=Object.freeze({__proto__:null,autoIncrementIndex:Zd,filterValidMessages:Ih,parseServerGroupMessage:ph,parseServerPushC2CModifyMessage:gh,parseServerPushGroupModifyMessage:vh,parseServerPushMessage:hh,parseServerPushMessageElement:mh,shouldStoreMessage:Eh,updateConversationFields:fh});const{isPlainObject:Ch}=ts.utils;function Mh(e,t={}){const{onlineUserOnly:s,messageControlInfo:n}=t;let{offlinePushInfo:o}=t;e.conversationType===Bd.CONV_C2C&&!0===s&&(o?o.disablePush=!0:o={disablePush:!0});let i="";"string"==typeof e.cloudCustomData&&e.cloudCustomData.length>0&&(i=e.cloudCustomData);const r=[];if(n&&Ch(n)){const{excludedFromUnreadCount:e,excludedFromLastMessage:t,excludedFromContentModeration:s}=n;!0===e&&r.push("NoUnread"),!0===t&&r.push("NoLastMsg"),!0===s&&r.push("NoMsgCheck")}return{onlineUserOnly:s,cloudCustomData:i,messageControlInfo:r,offlinePushInfo:o}}function yh(e){const{webhookInfo:{disableCloudMessagePreHook:t=!1,disableCloudMessagePostHook:s=!1}={}}=e||{};if(!t&&!s)return;const n=[];return t&&n.push("ForbidBeforeSendMsgCallback"),s&&n.push("ForbidAfterSendMsgCallback"),n}function Oh(e,t){return de(this,void 0,void 0,function*(){const s=e.conversationType===Bd.CONV_GROUP?function(e,t){var s;const o=Mh(e,t),{onlineUserOnly:i,cloudCustomData:r,messageControlInfo:a,offlinePushInfo:c}=o,u=JSON.parse(JSON.stringify(e.transformElementsToServerFormat()));let l;return n(e._receiverList)&&e._receiverList.length>0&&(l=e._receiverList,e._receiverList.length>50&&(l=e._receiverList.slice(0,50),console.warn("ReceiverListLimit"))),{servcmd:"group_open_http_svc.send_group_msg",data:{From_Account:null===(s=ts.store.get("login"))||void 0===s?void 0:s.userId,GroupId:e.to,MsgBody:u,CloudCustomData:r,Random:e.random,MsgPriority:e.priority,ClientSeq:e.clientSequence,GroupAtInfo:e._groupAtInfoList,OnlineOnlyFlag:i?1:0,MsgClientTime:e.clientTime,OfflinePushInfo:dh(c),SendMsgControl:i?void 0:a,NeedReadReceipt:!0===e.needReadReceipt?1:0,To_Account:l,SupportMessageExtension:!0===e.isSupportExtension?1:0,IsRelayMsg:!0===e._relayFlag?1:0,CustomModerationConfigID:e._cmConfigID,ForbidCallbackControl:yh(t)}}}(e,t):function(e,t){var s;const n=Mh(e,t),{onlineUserOnly:o,cloudCustomData:i,messageControlInfo:r,offlinePushInfo:a}=n,c=!0===o?0:void 0,u=JSON.parse(JSON.stringify(e.transformElementsToServerFormat()));return{servcmd:"openim.sendmsg",data:{From_Account:null===(s=ts.store.get("login"))||void 0===s?void 0:s.userId,To_Account:e.to,MsgBody:u,CloudCustomData:i,MsgSeq:e.sequence,MsgRandom:e.random,MsgLifeTime:c,From_AccountNick:e.nick,From_AccountHeadurl:e.avatar,SendMsgControl:0!==c?r:void 0,MsgClientTime:e.clientTime,IsNeedReadReceipt:!0===e.needReadReceipt?1:0,SupportMessageExtension:!0===e.isSupportExtension?1:0,IsRelayMsg:!0===e._relayFlag?1:0,CustomModerationConfigID:e._cmConfigID,OfflinePushInfo:dh(a),ForbidCallbackControl:yh(t)}}}(e,t),o=yield mn(s);return o?{time:o.MsgTime,messageDropReason:o.MsgDropReason,sequence:o.MsgSeq}:null})}const{isPlainObject:Ah}=ts.utils,{MSG_AUDIO:Th,MSG_FILE:Rh,MSG_IMAGE:Dh,MSG_VIDEO:bh,MSG_MERGER:Nh}=As;class Lh{init(){Fd.getInstance().registerApi({apiName:"sendMessage",context:this,matcher:e=>![Th,Rh,Dh,bh,Nh].includes(e[0].type)})}sendMessage(e,t){return de(this,void 0,void 0,function*(){const{TOTAL_COUNT:s,SEND_COST:n,SUCCESS_COUNT:o,FAILED_COUNT:i}=Ps;if(!(e instanceof eh))throw new Xs({code:Ts.MSG_INSTANCE_REQUIRED});const r=e.validateBeforeSend();if(!r.isValid){const{code:e,message:t=""}=r.error||{};throw new Xs({code:e,message:t})}this._reportMessageSendQuality({name:s,message:e});let a=!1;const{messageDataHandler:c}=ts.message||{};try{const{messageControlInfo:s}=t||{};let i=null;c.addRandomOfSentMessage(e.random);const r=Date.now();if(e.conversationType===Bd.CONV_C2C?(a=!0===(null==t?void 0:t.onlineUserOnly),i=yield Oh(e,t)):e.conversationType===Bd.CONV_GROUP&&(yield this._validateBeforeSendGroupMessage(e),i=yield Oh(e,t)),i){const{messageDropReason:t,sequence:u,time:l}=i;if(this._updateNickAndAvatarOfSentMessageByMe(e),t&&this._logRateLimitInfo(e,u,t),this._reportMessageSendQuality({name:o,message:e}),this._reportMessageSendQuality({name:n,message:e,startTs:r}),!0===e.isResend){const t=c.findMessage(e.ID);t&&(ts.ssoLog.debug("sendMessage",`sendMessage resend ok. ID:${t.ID}`),c.deleteConversationMessage(t))}return e.status=hs.SUCCESS,e.time=l,e.conversationType===Bd.CONV_GROUP&&(e.sequence=u),a?e._onlineOnlyFlag=!0:(c.storeConversationMessage(e),this._applySentMessageControlInfo(e,s),this._emitOnlineMessageSent(e)),{code:0,data:{message:e}}}}catch(t){e.status=hs.FAIL,c.removeRandomOfSentMessage(e.random);let{errorCode:s}=t||{},n=(null==t?void 0:t.errorInfo)||(null==t?void 0:t.message)||"";this._hasRiskContent(s)&&(e.hasRiskContent=!0),a||this._isRejectedByRestApi(s)||c.storeConversationMessage(e),this._reportMessageSendQuality({name:i,message:e,error:t});throw new Xs({code:s,message:n,data:{message:e},moreMessage:`type:${e.type} from:${e.from} to:${e.to}`})}})}_hasRiskContent(e){return 80001===e||80004===e}_isRejectedByRestApi(e){return e>=10100&&e<=10200||e>=120001&&e<=13e4}_emitOnlineMessageSent(e){const t=e._isExcludedFromLastMessage?"":e,{conversationID:s,conversationType:n}=e,o=gn(s)?cs.TOPIC_NEW_MESSAGE:cs.NEW_MESSAGE;ts.notificationCenter.emitInnerEvent(o,{result:{conversationUpdateFieldList:[{conversationID:s,type:n,message:e,lastMessage:t,unreadCount:0}]}})}_applySentMessageControlInfo(e,t){t&&Ah(t)&&(!0===t.excludedFromLastMessage&&(e._isExcludedFromLastMessage=!0),!0===t.excludedFromUnreadCount&&(e._isExcludedFromUnreadCount=!0))}_logRateLimitInfo(e,t,s){const n=`from:${e.from} to:${e.to} sequence:${t} messageDropReason:${s}`;ts.ssoLog.warn("messageDropReason",n)}_updateNickAndAvatarOfSentMessageByMe(e){const{messageDataHandler:t}=ts.message||{};let s=!1;const{conversationID:n}=e,o=t.getLatestMsgSentByMe(n);if(o){const{nick:i,avatar:r}=o;i===e.nick&&r===e.avatar||(s=!0),s&&t.updateNickAndAvatarOfSentMessage({conversationID:n,latestNick:e.nick,latestAvatar:e.avatar,isSentByMe:!0})}}_validateBeforeSendGroupMessage(e){return de(this,void 0,void 0,function*(){var t,s,n;const{to:o,from:i}=e;let r=o,a=wd.getGroup(r);if(hn({groupID:r})&&(null==a?void 0:a.isSupportTopic))throw new Xs({code:Ts.MSG_SEND_GRP_WITH_TOPIC_FAIL});if(gn(o)&&([r]=o.split(Ms.TOPIC),a=wd.getGroup(r)),!a&&"function"==typeof(null===(t=Fd.getInstance().getApiMap())||void 0===t?void 0:t.getGroupProfile)){const e=yield Fd.getInstance().getApiMap().getGroupProfile({groupID:r});if((null===(n=null===(s=null==e?void 0:e.data)||void 0===s?void 0:s.group)||void 0===n?void 0:n.type)===As.GRP_AVCHATROOM){const e=Qs({code:Ts.MSG_SEND_FAIL_NOT_IN_AV,replacement1:i,replacement2:r});throw new Xs({code:Ts.MSG_SEND_FAIL_NOT_IN_AV,message:e})}}return!0})}_reportMessageSendQuality(e){ts.notificationCenter.emitInnerEvent(cs.QUALITY_STAT,{label:Ls.MESSAGE_SEND_SUCCESS_RATE,data:e})}}var Ph=new class{constructor(){this._sparseMessagesByConversation=new Map,this._latestMessageSentByPeerMap=new Map,this._latestMessageSentByMeMap=new Map,this._randomOfSentMessageList=new Set}init(){ts.notificationCenter.subscribeInnerEvent(cs.LOGOUT,this._reset,this),ts.notificationCenter.subscribeInnerEvent(cs.DESTROY,this._dispose,this)}get _messagesByConversation(){return Gd.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 n=this._getUniqueIdOfMessage(e);return this._messagesByConversation.get(s).set(n,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),n=this._messagesByConversation.get(e.conversationID);if(null==n?void 0:n.has(s)){const e=null==n?void 0:n.get(s);if(!t||!0===(null==e?void 0:e.isModified))return!0}return!1}deleteConversationMessage(e){var t;const{conversationID:s=""}=e,n=this._getUniqueIdOfMessage(e);this._messagesByConversation.has(s)&&(null===(t=this._messagesByConversation.get(s))||void 0===t||t.delete(n))}modifyConversationMessage(e,t){var s;if(!this._messagesByConversation.has(e)&&!this._sparseMessagesByConversation.has(e))return{isUpdated:!1,message:null};const n=this._getUniqueIdOfMessage(t),o=this._getMessageFromLocalMessage(e,n);if(o){const{messageVersion:n,elements:i,cloudCustomData:r,checkResult:a=0}=t,c=a>1;if(console.log(`conversationToMessageMap modifyConversationMessage localVersion:${o.version} remoteVersion:${n}`),o.version<n){const t=this._getUniqueIdOfMessage(o),a=fe(i);return(null===(s=this._messagesByConversation.get(e))||void 0===s?void 0:s.has(t))?Gd.updateMessage(e,[t],{isModified:!0,version:n,_elements:a,payload:a[0].content,type:a[0].type,cloudCustomData:r,hasRiskContent:c,operation:gs.modify}):(o.version=n,o._elements=a,o.payload=o._elements[0].content,o.type=o._elements[0].type,o.cloudCustomData=r,o.isModified=!0,o.hasRiskContent=c),{isUpdated:!0,message:o}}return{isUpdated:!1,message:o}}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 n of s){if(t=Array.from(n.values()).find(t=>t.ID===e)||null,t)break}if(!t){const s=Array.from(this._sparseMessagesByConversation.values());for(const n of s)if(t=n.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:n}){const o=this._messagesByConversation.get(e);let i=null;if(o){const r=Array.from(o.values());if(i=this._findMessageBySequenceAndRandom({messageList:r,random:s,sequence:t}),i){const t=this._getUniqueIdOfMessage(i);return Gd.updateMessage(e,[t],{isRevoked:!0,revoker:n,operation:gs.revoke}),i}}if(this._sparseMessagesByConversation.has(e)){const o=Array.from(this._sparseMessagesByConversation.get(e).values());if(i=this._findMessageBySequenceAndRandom({messageList:o,random:s,sequence:t}),i)return i.isRevoked=!0,i.revoker=n,i}}_findMessageBySequenceAndRandom({messageList:t,sequence:s,random:n}){for(let o=0;o<t.length;o+=1){const i=t[o];if(i.sequence===s&&(e(n)||i.random===n))return i}return null}prependLocalMessageList(e){const{messageList:t,conversationID:s}=e;if(0===t.length)return[];const n=[],o=[],i=this._messagesByConversation.get(s)||new Map;for(const e of t){const t=this._getUniqueIdOfMessage(e);i.has(t)||(n.push(e),o.push([t,e]))}if(o.length>0){const e=new Map([...o,...i.entries()]);this._messagesByConversation.set(s,e),this._updateLatestMessageSentByMe(s),this._updateLatestMessageSentByPeer(s)}return n}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 n=this._sparseMessagesByConversation.get(t);for(let t=0;t<s;t++){const s=e[t];n.has(s.ID)||n.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:n,sequence:o,time:i}=e;return`${t}-${s}-${n}-${o}-${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.add(e)}removeRandomOfSentMessage(e){this._randomOfSentMessageList.delete(e)}updateNickAndAvatarOfSentMessage(e){const{conversationID:t="",latestAvatar:s,latestNick:n,isSentByMe:o=!0}=e,i=this._messagesByConversation.get(t);if(!i)return;const r=Array.from(i.values()),a=o?"out":"in";r.forEach(e=>{const{nick:t,avatar:o,flow:i}=e;i===a&&(t!==n&&(e.nick=n),o!==s&&(e.avatar=s))})}isInMessageList(e){var t;const{conversationID:s}=e;if(!s)return!1;if(!this._messagesByConversation.has(s))return!1;const n=this._getUniqueIdOfMessage(e);return null===(t=this._messagesByConversation.get(s))||void 0===t?void 0:t.has(n)}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(),ts.notificationCenter.unSubscribeInnerEvent(cs.LOGOUT,this._reset,this),ts.notificationCenter.unSubscribeInnerEvent(cs.DESTROY,this._dispose,this)}};function wh(e,t){const s=Pd.getConversation(e);if(null==s?void 0:s.lastMessage){const{lastMessage:n}=s,{lastTime:o,lastSequence:i,version:r}=n,{time:a,sequence:c,messageVersion:u,elements:l,cloudCustomData:d}=t;o===a&&i===c&&r!==u&&(n.type=l[0].type,n.payload=l[0].content,n.messageForShow=Mn(n.type,n.payload),n.cloudCustomData=d,n.version=u,Pd.updateConversation(e,{lastMessage:n}))}}class Gh{init(){Fd.getInstance().registerApi({apiName:"modifyMessage",context:this})}modifyMessage(e){return de(this,void 0,void 0,function*(){const{to:t,payload:s,sequence:n,conversationType:o,random:i,time:r,from:a,type:c}=e;if(this._canModifyMessageElement(c)){const t=e.getElements();t.length>1&&(t[0].type=c,t[0].content=s)}try{let s=null,c=null;if(o===Bd.CONV_C2C?s=yield function(e){return de(this,void 0,void 0,function*(){const{from:t,to:s,version:n=0,sequence:o,random:i,time:r,type:a,cloudCustomData:c}=e,u={From_Account:t,To_Account:s,MsgVersion:n,MsgSeq:o,MsgRandom:i,MsgTime:r,MsgType:a,MsgBody:e.transformElementsToServerFormat(),CloudCustomData:c},l=yield mn({servcmd:"openim.modify_c2c_msg",data:u});if(l){const{MsgBody:e,MsgVersion:t,CloudCustomData:s}=l;return{elements:mh(e),messageVersion:t,cloudCustomData:s}}})}(e):o===Bd.CONV_GROUP&&(s=yield function(e){return de(this,void 0,void 0,function*(){const{to:t,version:s=0,sequence:n,cloudCustomData:o}=e,i={GroupId:t,MsgVersion:s,MsgSeq:n,MsgBody:e.transformElementsToServerFormat(),CloudCustomData:o},r=yield mn({servcmd:"openim.modify_group_msg",data:i});if(r){const{MsgBody:e,MsgVersion:t,CloudCustomData:s}=r;return{elements:mh(e),messageVersion:t,cloudCustomData:s}}})}(e)),s){let u=`${o}${t}`;return t===En()&&o===Bd.CONV_C2C&&(u=`${o}${a}`),c={conversationType:o,from:a,to:t,time:r,random:i,sequence:n,elements:null==s?void 0:s.elements,cloudCustomData:null==s?void 0:s.cloudCustomData,messageVersion:null==s?void 0:s.messageVersion,conversationID:u},this._handleModifyMessageSuccess(c),{code:0,data:{message:e},successLog:{message:`to:${t}`}}}}catch(e){const{errorCode:t}=e||{};throw new Xs({functionName:"modifyMessage",code:t})}})}_handleModifyMessageSuccess(e){const{conversationID:t}=e,{isUpdated:s,message:n}=ts.message.messageDataHandler.modifyConversationMessage(t,e);!0===s&&ts.notificationCenter.emitOuterEvent(rs.MESSAGE_MODIFIED,{name:rs.MESSAGE_MODIFIED,data:[n]}),ts.notificationCenter.emitInnerEvent(cs.MESSAGE_MODIFIED,{conversationID:t,message:n}),wh(t,e)}_canModifyMessageElement(e){return[Hd.MSG_TEXT,Hd.MSG_CUSTOM,Hd.MSG_LOCATION,Hd.MSG_FACE].includes(e)}}class Uh{init(){const{notificationCenter:e}=ts,{InnerEventSubType:t}=e;ln.getInstance().registerWorkflowStep(Ds.RECEIVE_C2C_NEW_MESSAGE,bs.HANDLE_C2C_NEW_MESSAGE,this._handleC2CMessagePush,this),ln.getInstance().registerWorkflowStep(Ds.RECEIVE_C2C_NEW_MESSAGE,bs.EMIT_C2C_MESSAGE_EVENT,this._emitMessageEventsAfterReceiveNewMessage,this),ln.getInstance().registerWorkflowStep(Ds.SYNC_SERVER_INFO_AFTER_RE_ONLINE,bs.EMIT_C2C_MESSAGE_EVENT,this._emitMessageEventsAfterSyncUnreadMessage,this),e.subscribeInnerEvent(cs.MESSAGE_PUSH,t.C2C_REALTIME_MESSAGE,this._executeReceiverNewMessageWorkFlow,this),e.subscribeInnerEvent(cs.MESSAGE_PUSH,t.C2C_MESSAGE_MODIFIED,this._handleC2CMessageModify,this),e.subscribeInnerEvent(cs.DESTROY,this._dispose,this)}_executeReceiverNewMessageWorkFlow(e){ln.getInstance().executeWorkflow(Ds.RECEIVE_C2C_NEW_MESSAGE,e)}_handleC2CMessagePush(e){const t=e.data||{},{messageDataHandler:s}=ts.message||{},n=[],o=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)||n.push(t);else if(Eh(t)){s.storeConversationMessage(t)&&fh({conversationUpdateFields:o,message:t}),s.isMessageSentByCurrentInstance(t)&&!i||n.push(t)}}),{conversationUpdateFieldList:[...o.values()],messages:n}}_emitMessageEventsAfterReceiveNewMessage(e){var t;const{messages:s=[]}=(null===(t=e.result)||void 0===t?void 0:t[bs.HANDLE_C2C_NEW_MESSAGE])||{};this._emitMessageEvents(s)}_emitMessageEventsAfterSyncUnreadMessage(e){var t;const{messages:s=[]}=(null===(t=e.result)||void 0===t?void 0:t[bs.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&&ts.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&&ts.notificationCenter.emitOuterEvent("onMessageReceived",{name:"onMessageReceived",data:s})}_generateC2CMessage(e){const t=Bd.CONV_C2C,s=hh(e),n=ts.message.messageFactory.createMessage(Object.assign(Object.assign({},s),{conversationType:t,flow:Jd.IN})),{elements:o}=s;return n.setElement(o),n}_updateMessageProfile(s){var n;const{messageDataHandler:o}=ts.message||{},i=null===(n=ts.store.get("login"))||void 0===n?void 0:n.userId,{from:r,nick:a,avatar:c,conversationID:u=""}=s;if(r!==i){const n=o.getLatestMsgSentByPeer(u);if(n){const{nick:i,avatar:r}=n;e(a)||e(c)?(s.nick=t(i)?i:s.nick,s.avatar=t(r)?r:s.avatar):a===i&&c===r||(o.updateNickAndAvatarOfSentMessage({conversationID:u,latestNick:a,latestAvatar:c,isSentByMe:!1}),this._updateConversationUserProfile({conversationID:u,nick:a,avatar:c}))}}else{const e=o.getLatestMsgSentByMe(u);!e||a===e.nick&&c===e.avatar||o.updateNickAndAvatarOfSentMessage({conversationID:u,latestNick:a,latestAvatar:c,isSentByMe:!0})}}_updateConversationUserProfile(e){const{conversationID:t,nick:s,avatar:n}=e,o=Pd.getConversation(t),{userProfile:i={}}=o||{};i.avatar===n&&i.nick===s||Pd.updateConversation(t,{userProfile:Object.assign(Object.assign({},i),{nick:s,avatar:n})})}_updateMessageListDueToModify(e){const{conversationID:t}=e,{isUpdated:s,message:n}=ts.message.messageDataHandler.modifyConversationMessage(t,e);!0===s&&ts.notificationCenter.emitOuterEvent("onMessageModified",{name:"onMessageModified",data:[n]}),ts.notificationCenter.emitInnerEvent("ModifyMessageSuccess",e),wh(t,e)}_handleC2CMessageModify(e){e.C2cMsgModNotifys.forEach(e=>{var t;const s=Bd.CONV_C2C;let n=gh(e);const{to:o,from:i}=n;let r=`${s}${o}`;o===(null===(t=ts.store.get("login"))||void 0===t?void 0:t.userId)&&(r=`${s}${i}`),n=Object.assign({conversationType:s,conversationID:r},n),this._updateMessageListDueToModify(n)})}_dispose(){const{notificationCenter:e}=ts,{InnerEventSubType:t}=e;ts.notificationCenter.unSubscribeInnerEvent(cs.MESSAGE_PUSH,t.C2C_REALTIME_MESSAGE,this._handleC2CMessagePush,this),ts.notificationCenter.unSubscribeInnerEvent(cs.MESSAGE_PUSH,t.C2C_MESSAGE_MODIFIED,this._handleC2CMessageModify,this),ts.notificationCenter.unSubscribeInnerEvent(cs.DESTROY,this._dispose,this)}}class kh{init(){const{notificationCenter:e}=ts,{InnerEventSubType:t}=e;ln.getInstance().registerWorkflowStep(Ds.RECEIVE_GROUP_NEW_MESSAGE,bs.HANDLE_GROUP_NEW_MESSAGE,this._handleGroupMessagePush,this),ln.getInstance().registerWorkflowStep(Ds.RECEIVE_GROUP_NEW_MESSAGE,bs.EMIT_GROUP_MESSAGE_EVENT,this._emitMessageEvents,this),e.subscribeInnerEvent(cs.MESSAGE_PUSH,t.GROUP_REALTIME_MESSAGE,this._executeReceiverNewMessageWorkFlow,this),e.subscribeInnerEvent(cs.MESSAGE_PUSH,t.GROUP_MESSAGE_MODIFIED,this._handleGroupMessageModify,this),e.subscribeInnerEvent(cs.DESTROY,this._dispose,this)}_executeReceiverNewMessageWorkFlow(e){this._canExecuteReceiverNewMessageWorkFlow(e)&&ln.getInstance().executeWorkflow(Ds.RECEIVE_GROUP_NEW_MESSAGE,e)}_handleGroupMessagePush(e){const t=e.data||{},{messageDataHandler:s}=ts.message,n=[],o=new Map,i=null==t?void 0:t.GroupMsgArray;return null==i||i.forEach(e=>{if(1===e.GroupInfo.NotVisible)return;const t=this._generateGroupMessage(e);this.updateMessageProfile(t);let i=1===t.isModified;if(s.isMessageSentByCurrentInstance(t)?t.isModified=i:i=!1,t.isOnlineMessage())t._onlineOnlyFlag=!0,s.isMessageSentByCurrentInstance(t)||n.push(t);else if(Eh(t)){s.storeConversationMessage(t)&&(n.push(t),fh({conversationUpdateFields:o,message:t}))}}),{conversationUpdateFieldList:[...o.values()],messages:n}}_emitMessageEvents(e){var t;const{messages:s}=(null===(t=e.result)||void 0===t?void 0:t[bs.HANDLE_GROUP_NEW_MESSAGE])||{},n=(null==s?void 0:s.filter(e=>!0===(null==e?void 0:e.isModified)))||[];n.length>0&&ts.notificationCenter.emitOuterEvent("onMessageModified",{name:"onMessageModified",data:n});const o=(null==s?void 0:s.filter(e=>!(null==e?void 0:e.isModified)))||[];o.length>0&&ts.notificationCenter.emitOuterEvent("onMessageReceived",{name:"onMessageReceived",data:o})}_generateGroupMessage(e){const t=Bd.CONV_GROUP,s=ph(e),n=ts.message.messageFactory.createMessage(Object.assign(Object.assign({},s),{conversationType:t,flow:Jd.IN})),{elements:o}=s;return n.setElement(o),n}updateMessageProfile(e){var t;const{messageDataHandler:s}=ts.message||{},n=null===(t=ts.store.get("login"))||void 0===t?void 0:t.userId,{from:o,nick:i,avatar:r,conversationID:a="",_elements:c}=e;if(o===n){const e=s.getLatestMsgSentByMe(a);!e||i===e.nick&&r===e.avatar||s.updateNickAndAvatarOfSentMessage({conversationID:a,latestNick:i,latestAvatar:r,isSentByMe:!0})}else if(o===As.CONV_SYSTEM){const{operationType:t,memberInfoList:s,operatorInfo:n}=c;let o={};if(ve(s)?ve(n)||(o=n):[ys.JOINED,ys.KICKED,ys.ADMIN_SET,ys.ADMIN_CANCELED].includes(t)&&(o=Object.assign({},s[0])),!ve(o)){const{nick:t="",avatar:s=""}=o;e.nick=t,e.avatar=s}}}_updateMessageListDueToModify(e){const{conversationID:t}=e,{isUpdated:s,message:n}=ts.message.messageDataHandler.modifyConversationMessage(t,e);!0===s&&ts.notificationCenter.emitOuterEvent("onMessageModified",{name:"onMessageModified",data:[n]}),wh(t,e)}_handleGroupMessageModify(e){e.GroupMsgModNotifys.forEach(e=>{const t=Bd.CONV_GROUP;let s=vh(e);const{topicID:n,groupID:o}=s,i=n||o,r=`${t}${i}`;s=Object.assign({conversationType:t,conversationID:r,to:i},s),this._updateMessageListDueToModify(s)})}_dispose(){const{notificationCenter:e}=ts,{InnerEventSubType:{GROUP_REALTIME_MESSAGE:t,GROUP_MESSAGE_MODIFIED:s}}=e;e.unSubscribeInnerEvent(cs.MESSAGE_PUSH,t,this._handleGroupMessagePush,this),e.unSubscribeInnerEvent(cs.MESSAGE_PUSH,s,this._handleGroupMessageModify,this),e.unSubscribeInnerEvent(cs.DESTROY,this._dispose,this)}_canExecuteReceiverNewMessageWorkFlow(e){var t,s;const{GroupId:n,GroupType:o}=(null===(s=null===(t=null==e?void 0:e.GroupMsgArray)||void 0===t?void 0:t[0])||void 0===s?void 0:s.GroupInfo)||{},i=o===Cs.GRP_AVCHATROOM;return!(!wd.getGroup(n)&&i)}}var Fh=new class{constructor(){this.c2cMessageReceiver=new Uh,this.groupMessageReceiver=new kh}init(){this.c2cMessageReceiver.init(),this.groupMessageReceiver.init()}};const $h={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 must be a string";return!0}(e)}}};const qh={createCustomMessage:!0,sendMessage:!0,modifyMessage:!0};var xh=new class{getGroupRoamingMessagesByAnchor(e){return de(this,void 0,void 0,function*(){try{const{conversationID:t,count:s,direction:o,sequence:i,messageSequenceList:r,getType:a}=e,c=t.replace(Is.CONV_GROUP,""),u=[];let l=i;if(o===ps.BACKWARD){if("number"!=typeof i)return{messageList:[],hasNoMoreHistoryMessage:!1,nextReqMessageIDFromServer:""};l=i+s-1}const d=yield function(e){return de(this,void 0,void 0,function*(){const{groupID:t,count:s,messageSequence:o,messageSequenceList:i,getType:r}=e,a={GroupId:t,ReqMsgNumber:s,WithRecalledMsg:1,Version:1,GetType:r};return o&&(a.ReqMsgSeq=o),n(i)&&i.length>0&&(a.ReqMsgSeqList=i),yield mn({servcmd:"group_open_http_svc.group_msg_get",data:a})})}({groupID:c,count:s,messageSequence:l,messageSequenceList:r,getType:a});if(d){const{RspMsgList:e=[],NextReqMsgSeq:t=0,IsFinished:s,InvisibleMsgSeq:n}=d,r=`groupID:${c} sequence:${i} reqSeq:${l} direction:${o} complete:${s} nextSequence:${t} remoteMsgCount:${e.length} invisibleSequenceList:${n}`,a=[];for(let t=0;t<e.length;t++){const s=e[t];s.From_Account===As.CONV_SYSTEM&&u.push(s);const n=this._parseMessage(s);a.push(n)}a.reverse();let h=s===Qd;o===ps.BACKWARD&&(h=a[a.length-1].sequence>=i);const g=Ih(a);return ts.ssoLog.info("getGroupRoamingMessagesByAnchor",r),{messageList:g,invisibleSequenceList:n,nextReqMessageIDFromServer:t,hasNoMoreHistoryMessage:h,serverGroupTipList:u}}}catch(e){const{errorCode:t,errorInfo:s}=e||{};throw new Xs({code:t,message:s})}})}_parseMessage(e){const t=Is.CONV_GROUP;4===e.Event&&(e.MsgBody.MsgType=As.MSG_GRP_TIP);const s=ph(e),n=nh.createMessage(Object.assign(Object.assign({},s),{conversationType:t,flow:"in"}));return n.setElement(s.elements),n}};class Vh{constructor(){this.messageHelper=Sh,this.messageFactory=nh,this.messageSender=new Lh,this.messageAction=new Gh,this.messageReceiver=Fh,this.messageDataHandler=Ph,this.messageHistory=xh,this.messageSender.init(),this.messageFactory.init(),this.messageAction.init(),this.messageReceiver.init(),this.messageDataHandler.init(),cn({auth:qh,params:$h})}}const Bh="Tag_Profile_IM_",jh={NICK:`${Bh}Nick`,GENDER:`${Bh}Gender`,BIRTHDAY:`${Bh}BirthDay`,LOCATION:`${Bh}Location`,SELFSIGNATURE:`${Bh}SelfSignature`,ALLOWTYPE:`${Bh}AllowType`,LANGUAGE:`${Bh}Language`,AVATAR:`${Bh}Image`,MESSAGESETTINGS:`${Bh}MsgSettings`,ADMINFORBIDTYPE:`${Bh}AdminForbidType`,LEVEL:`${Bh}Level`,ROLE:`${Bh}Role`},Kh="Tag_Profile_Custom",Hh="profileCustomField",Wh="USER_STATUS",Yh=1,zh=1e3,Jh={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:[]},Qh=new Map([[jh.NICK,"nick"],[jh.GENDER,"gender"],[jh.BIRTHDAY,"birthday"],[jh.LOCATION,"location"],[jh.SELFSIGNATURE,"selfSignature"],[jh.ALLOWTYPE,"allowType"],[jh.LANGUAGE,"language"],[jh.AVATAR,"avatar"],[jh.MESSAGESETTINGS,"messageSettings"],[jh.ADMINFORBIDTYPE,"adminForbidType"],[jh.LEVEL,"level"],[jh.ROLE,"role"]]);var Xh=new class{createProfile(e,t){const s={userID:e,profileCustomField:[]};return t.forEach(e=>{const{tag:t,value:n}=e;t&&t.indexOf(Kh)>-1?s.profileCustomField.push({key:t,value:n}):Qh.has(t)&&(s[Qh.get(t)]=n)}),Object.assign(Object.assign({},Jh),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=>{s!==Hh&&t.push({tag:jh[s.toUpperCase()],value:e[s]})}),e.profileCustomField&&n(e.profileCustomField)&&e.profileCustomField.forEach(e=>{t.push({tag:e.key,value:e.value})}),t}normalizeProfileFields(e){const t={},s=[];return e.forEach(e=>{const{tag:n,value:o}=e;if(n&&n.indexOf(Kh)>-1&&s.push({key:n,value:o}),Qh.has(n)&&void 0!==o){const e=Qh.get(n);t[e]=o}}),s.length>0&&(t.profileCustomField=s),t}};const{generateProtocolData:Zh}=ts.common;function eg(e){return de(this,void 0,void 0,function*(){const t="profile.portrait_get_all",s={From_Account:En(),UserItem:[]};e.forEach(e=>{s.UserItem.push({CustomSequence:0,StandardSequence:0,To_Account:e})});const n=Zh({servcmd:t,data:s}),o=`${n.head.seq}${t}`,i=yield ts.channel.sendPacket(n,{requestId:o});if(i)return function(e){const{ActionStatus:t,ErrorCode:s,ErrorDisplay:n,ErrorInfo:o,UserProfileItem:i}=e,r=[];return i.map(e=>{const{To_Account:t,CustomSequence:s,ResultCode:n,ResultInfo:o,StandardSequence:i,ProfileItem:a}=e,c=Xh.parseProfileItem(a);r.push({userId:t,customSequence:s,resultCode:n,resultInfo:o,standardSequence:i,profileItem:c})}),{actionStatus:t,errorCode:s,errorDisplay:n,errorInfo:o,userProfile:r}}(i)})}function tg(e){return Ud.getFriendMap().has(e)}const{isEmpty:sg}=ts.utils;class ng{constructor(){this._strangerProfileMap=new Map}init(){Fd.getInstance().registerApi({apiName:"getMyProfile",context:this}),Fd.getInstance().registerApi({apiName:"getUserProfile",context:this}),Fd.getInstance().registerApi({apiName:"updateMyProfile",context:this}),this.createProfile=Xh.createProfile.bind(Xh);const{notificationCenter:e}=ts;ln.getInstance().registerWorkflowStep(Ds.SYNC_SERVER_INFO_AFTER_LOGIN,bs.USER_PROFILE_SYNC,this.getMyProfileCacheThenServer,this),e.subscribeInnerEvent(cs.MESSAGE_PUSH,e.InnerEventSubType.PROFILE_MODIFIED,this._onProfileDataModify,this),e.subscribeInnerEvent(cs.LOGOUT,this._reset,this),e.subscribeInnerEvent(cs.DESTROY,this._dispose,this)}getMyProfile(){return de(this,void 0,void 0,function*(){try{const e=En(),t=yield eg([e]);if(t){const s=this._handleProfileFormResponse(t)[0];return Ud.getUserProfileMap().set(e,s),{code:0,data:s}}}catch(e){const{errorCode:t,errorInfo:s}=e;throw new Xs({functionName:"getMyProfile",code:t,message:s})}})}getUserProfile(e){return de(this,void 0,void 0,function*(){try{let{userIDList:t}=e;const{userIdListToRequest:s,profileFromCache:o}=this._filterRequestAndCacheUsers(t);if(0===s.length)return{code:0,data:o,successLog:{message:`userIDList.length:${t.length}`}};s.length>zh&&(ts.ssoLog.warn("getUserProfile","userIdListToRequest.length > 1000"),s.length=zh);const{data:i,error:r}=yield this._batchFetchUserProfiles(s),a=s.length,c=i.length,u=a-c;if(0===o.length&&a===u&&!sg(r))throw r;if(n(i)){i.forEach(e=>{tg(e.userID)?Ud.getUserProfileMap().set(e.userID,e):this._strangerProfileMap.set(e.userID,e)});const e=i.concat(o);return{code:0,data:e,successLog:{message:`getUserProfile query:${a} success:${c} fail:${u} from cache:${o.length}`}}}}catch(e){const{errorCode:t}=e;throw new Xs({functionName:"getUserProfile",code:t})}})}getMyProfileCacheThenServer(){return de(this,void 0,void 0,function*(){const e=En(),t=Ud.getUserProfileMap().has(e);return t?{code:0,data:t}:this.getMyProfile()})}updateMyProfile(e){return de(this,void 0,void 0,function*(){const t=En(),s={};for(const t in e)void 0!==e[t]&&(s[t]=e[t]);const n=Xh.convertParamsToProfile(s);try{const e={From_Account:t,ProfileItem:n};yield function(e){return de(this,void 0,void 0,function*(){const t="profile.portrait_set",s=Zh({servcmd:t,data:e}),n=`${s.head.seq}${t}`,o=yield ts.channel.sendPacket(s,{requestId:n});if(o){const{ActionStatus:e,ErrorCode:t,ErrorDisplay:s,ErrorInfo:n}=o;return{actionStatus:e,errorCode:t,errorDisplay:s,errorInfo:n}}})}(e);const o=Ud.getUserProfile(t);let i;i=o?Object.assign(Object.assign({},o),s):Xh.createProfile(t,n);const r=!ns(o,i,["lastUpdatedTime"]);return i.lastUpdatedTime=Date.now(),Ud.getUserProfileMap().set(t,i),r&&this._emitProfileUpdated(i),{code:0,data:i,successLog:{message:`profileArray: ${ts.utils.safeStringify(n)}`}}}catch(e){const{errorCode:t,errorInfo:s}=e;throw new Xs({functionName:"updateMyProfile",code:t,message:s})}})}updateMyNickAndAvatar(e){return de(this,void 0,void 0,function*(){const t=En(),s=Date.now(),n=Ud.getUserProfile(t);let o={};o=n?Object.assign(n,e):Xh.createProfile(t,e),o.lastUpdatedTime=s,Ud.getUserProfileMap().set(t,o)})}_onProfileDataModify(e){const t=function(e){const{Profile_Account:t,PushType:s,ProfileList:n}=e;return{userId:t,pushType:s,profileList:Xh.parseProfileList(n)}}(e.ProfileDataMod[0]);if(sg(t))return;const{isProfileUpdated:s,profile:n}=this._handleProfileModified(t);s&&this._emitProfileUpdated(n)}_emitProfileUpdated(e){ts.notificationCenter.emitInnerEvent(cs.PROFILE_UPDATE,{name:cs.PROFILE_UPDATE,data:[e]}),ts.notificationCenter.emitOuterEvent(rs.PROFILE_UPDATED,{name:rs.PROFILE_UPDATED,data:[e]}),Pd.updateConversation(`C2C${null==e?void 0:e.userID}`,{userProfile:e})}_dispose(){const{notificationCenter:e}=ts;e.unSubscribeInnerEvent(cs.LOGOUT,this._reset,this),e.unSubscribeInnerEvent(cs.MESSAGE_PUSH,e.InnerEventSubType.PROFILE_MODIFIED,this._onProfileDataModify,this),e.unSubscribeInnerEvent(cs.DESTROY,this._dispose,this),this._reset()}_handleProfileModified(e){const{userId:t,profileList:s}=e,n=Ud.getUserProfile(t);if(!(En()===t||tg(t)&&n))return{isProfileUpdated:!1,profile:null};const o=Xh.normalizeProfileFields(s),i=Object.keys(o).some(e=>e===Hh?!ns(n.profileCustomField,o.profileCustomField):n[e]!==o[e]);if(!i)return{isProfileUpdated:!1,profile:n};const r=Date.now(),a=Object.assign(Object.assign(Object.assign({},n),o),{lastUpdatedTime:r});return Ud.getUserProfileMap().set(t,a),{isProfileUpdated:i,profile:a}}_filterRequestAndCacheUsers(e){const t=[],s=[];return e.forEach(e=>{const n=Ud.getUserProfileMap().has(e);tg(e)&&n?s.push(Ud.getUserProfile(e)):this._isStrangerAndProfileValid(e)?s.push(this._strangerProfileMap.get(e)):t.push(e)}),{userIdListToRequest:t,profileFromCache:s}}_handleProfileFormResponse(e){const{userProfile:t}=e;if(!Array.isArray(t))return[];const s=t.filter(e=>"@TLS#NOT_FOUND"!==e.userId&&""!==e.userId&&!sg(e.profileItem)),n=Date.now();return s.map(e=>{const t=Xh.createProfile(e.userId,e.profileItem);return t.lastUpdatedTime=n,t})}_isStrangerAndProfileValid(e){var t;if(!tg(e)){const{lastUpdatedTime:s=0}=this._strangerProfileMap.get(e)||{},n=(null===(t=ts.store.get("cloudConfig"))||void 0===t?void 0:t.stranger_profile_expiration_time)||6e5;return Date.now()-s<=n}return!1}_chunkUserIDList(e,t){return Array.from({length:Math.ceil(e.length/t)},(s,n)=>e.slice(n*t,(n+1)*t))}_batchFetchUserProfiles(e){return de(this,void 0,void 0,function*(){const t=[],s=[];let o={};this._chunkUserIDList(e,100).forEach(e=>{t.push(eg(e))});return(yield Promise.allSettled(t)).forEach(e=>{if("fulfilled"===e.status){const t=e.value,o=this._handleProfileFormResponse(t);n(o)&&s.push(...o)}else if("rejected"===e.status){const{code:t,message:s}=e.reason||{};o={errorCode:t,message:s}}}),{data:s,error:o}})}_reset(){Ud.getUserProfileMap().clear(),this._strangerProfileMap.clear()}}const og=new Map,ig=["0","1","2","3","4","5","6","7","8","9","A","B","C","D","E","F"];for(let e=0,t=ig.length;e<t;e++)og.set(e,ig[e]);function rg(e){if(!e)return"";const t=String(e).replace(/[=]+$/,"");let s="";if(t.length%4==1)return"";for(let e,n,o=0,i=0;n=t.charAt(i++);~n&&(e=o%4?64*e+n:n,o++%4)?s+=String.fromCharCode(255&e>>(-2*o&6)):0)n="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=".indexOf(n);try{return decodeURIComponent(escape(s))}catch(e){return console.warn(e),""}}const{isEmpty:ag}=ts.utils,{generateProtocolData:cg}=ts.common;function ug(e){return de(this,void 0,void 0,function*(){const t="im_open_status.ws_get_user_status",s=cg({servcmd:t,data:{To_Account:e}}),n=`${s.head.seq}${t}`,o=yield ts.channel.sendPacket(s,{requestId:n});if(o)return function(e){const{ErrorCode:t,ErrorInfo:s,ErrorList:n=[],UserStatusList:o=[]}=e,i=o.map(e=>{const{To_Account:t,Status:s,CustomStatus:n}=e;return{userID:t,statusType:s,customStatus:rg(n)}}),r=n.map(e=>{const{To_Account:t,Invalid_Account:s,ErrorCode:n,ErrorInfo:o}=e;return{userID:ag(s)?t:s,code:n,message:o}});return{errorCode:t,errorInfo:s,successUserList:i,failureUserList:r}}(o)})}class lg{constructor(){this._customStatus=""}init(){const{notificationCenter:e}=ts;Fd.getInstance().registerApi({apiName:"getUserStatus",context:this}),Fd.getInstance().registerApi({apiName:"setSelfStatus",context:this}),Fd.getInstance().registerApi({apiName:"subscribeUserStatus",context:this}),Fd.getInstance().registerApi({apiName:"unsubscribeUserStatus",context:this}),ln.getInstance().registerWorkflowStep(Ds.SYNC_SERVER_INFO_AFTER_RE_ONLINE,bs.USER_STATUS_UPDATE,this._onReOnline,this),e.subscribeInnerEvent(cs.MESSAGE_PUSH,e.InnerEventSubType.USER_STATUS_UPDATE,this._onUserStatusUpdate,this),e.subscribeInnerEvent(cs.LOGOUT,this._reset,this),e.subscribeInnerEvent(cs.DESTROY,this._dispose,this)}setSelfStatus(e){return de(this,void 0,void 0,function*(){const t=En(),{customStatus:s}=e;try{return yield function(e){return de(this,void 0,void 0,function*(){const t="im_open_status.ws_set_custom_status",s=cg({servcmd:t,data:{CustomStatus:e}}),n=`${s.head.seq}${t}`,o=yield ts.channel.sendPacket(s,{requestId:n});if(o){const{ErrorCode:e,ErrorInfo:t}=o;return{errorCode:e,errorInfo:t}}})}(s),this._customStatus=s,{code:0,data:{userID:t,statusType:Yh,customStatus:s},successLog:{message:`customStatus: ${s}`}}}catch(e){const{errorCode:t,errorInfo:s}=e;throw new Xs({functionName:"setSelfStatus",code:t,message:s})}})}getUserStatus(e){return de(this,void 0,void 0,function*(){const{userIDList:t=[]}=e;let s={};return this._isOnlyMeInArray(t)&&(s=this._getMyStatus()),s=yield this._getUserStatus(t),Object.assign(Object.assign({},s),{successLog:{message:`userIDList length: ${t.length}`}})})}setCustomStatus(e){const t=rg(e);this._customStatus=t}subscribeUserStatus(e){return de(this,void 0,void 0,function*(){try{const{userIDList:t=[]}=e;this._checkBusinessCapabilityBits("subscribeUserStatus");const s=this._getMaxUserCount("subscribe"),n=this._sliceUserIDList(t,s),o=yield function(e){return de(this,void 0,void 0,function*(){const{channel:t}=ts,s="im_open_status.ws_status_subscribe",n=cg({servcmd:s,data:{To_Account:e}}),o=`${n.head.seq}${s}`;return yield t.sendPacket(n,{requestId:o})})}(n),i=this._parseResponse(o);return{code:0,data:{failureUserList:i},successLog:{message:`userID length:${t.length} failCount: ${i.length}`}}}catch(e){const{errorCode:t}=e;throw new Xs({functionName:"subscribeUserStatus",code:t})}})}unsubscribeUserStatus(e){return de(this,void 0,void 0,function*(){try{this._checkBusinessCapabilityBits("unsubscribeUserStatus");const{userIDList:t=[]}=e,s=this._getMaxUserCount("unsubscribe"),n=this._sliceUserIDList(t,s),o=yield function(e){return de(this,void 0,void 0,function*(){const{channel:t}=ts,s="im_open_status.ws_status_unsubscribe";let n={};n=0===e.length?{UnsubscribeAll:1}:{To_Account:e};const o=cg({servcmd:s,data:n}),i=`${o.head.seq}${s}`;return yield t.sendPacket(o,{requestId:i})})}(n),i=this._parseResponse(o);return{code:0,data:{failureUserList:i},successLog:{message:`userID length:${t.length} failCount: ${i.length}`}}}catch(e){const{errorCode:t}=e;throw new Xs({functionName:"unsubscribeUserStatus",code:t})}})}_onUserStatusUpdate(e){const{UserStatusList:t=[]}=e||{},s=t.map(e=>{const{To_Account:t,Status:s,CustomStatus:n}=e;return{userID:t,statusType:s,customStatus:rg(n)}});this._emitUserStatusUpdatedEvent(s)}_onReOnline(e){const t=rg(e.data.customStatus);if(this._customStatus===t)return;this._customStatus=t;const s={userID:En(),statusType:Yh,customStatus:t};this._emitUserStatusUpdatedEvent(s)}_emitUserStatusUpdatedEvent(e){ts.notificationCenter.emitOuterEvent(rs.USER_STATUS_UPDATED,{name:rs.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:n,ErrorInfo:o}=e;return{userID:ts.utils.isEmpty(s)?t:s,code:n,message:o}})}_checkBusinessCapabilityBits(e){if(!ts.store.get("commercialConfig").get(Wh))throw new Xs({functionName:e,code:Ts.NO_USE,replacement1:e})}_getMaxUserCount(e){const t=ts.store.get("cloudConfig")||{},s={query:{key:"status_query_count",default:500},subscribe:{key:"status_sub_count",default:100},unsubscribe:{key:"status_unsub_count",default:100}},{key:n,default:o}=s[e],i=t[n]||o;return parseInt(i,10)}_getMyStatus(){return{code:0,data:{successUserList:[{userID:En(),statusType:Yh,customStatus:this._customStatus}],failureUserList:[]}}}_getUserStatus(e){return de(this,void 0,void 0,function*(){try{this._checkBusinessCapabilityBits("getUserStatus");const t=this._getMaxUserCount("query"),s=this._sliceUserIDList(e,t),n=yield ug(s),{successUserList:o,failureUserList:i}=n||{};return{code:0,data:{successUserList:o,failureUserList:i}}}catch(e){const{errorCode:t}=e;throw new Xs({functionName:"getUserStatus",code:t})}})}_isOnlyMeInArray(e){const t=En();return 1===e.length&&e.indexOf(t)>-1}_dispose(){const{notificationCenter:e}=ts;e.unSubscribeInnerEvent(cs.MESSAGE_PUSH,e.InnerEventSubType.USER_STATUS_UPDATE,this._onUserStatusUpdate,this),e.unSubscribeInnerEvent(cs.DESTROY,this._dispose,this),e.unSubscribeInnerEvent(cs.LOGOUT,this._reset,this),this._reset()}_reset(){this._customStatus=""}}const dg={getUserProfile:{userIDList:{required:!0,rules:["array"],allowEmpty:!1}},updateMyProfile:{nick:{required:!1,rules:["string"],allowEmpty:!0},avatar:{required:!1,rules:["string"],allowEmpty:!0},gender:{required:!1,rules:["string"],allowEmpty:!0},selfSignature:{required:!1,rules:["string"],allowEmpty:!0},allowType:{required:!1,rules:["string"],allowEmpty:!0},birthday:{required:!1,rules:["number"],allowEmpty:!1},language:{required:!1,rules:["string"],allowEmpty:!0},messageSettings:{required:!1,rules:["string"],allowEmpty:!0},adminForbidType:{required:!1,rules:["string"],allowEmpty:!0},level:{required:!1,rules:["number"],allowEmpty:!1},role:{required:!1,rules:["number"],allowEmpty:!0},profileCustomField:{required:!1,rules:["array"],allowEmpty:!0,customValidator:function(e){for(const t of e){if("object"!=typeof t)return"Each item in profileCustomField must be an object";if("string"!=typeof(null==t?void 0:t.key))return"Each item.key in profileCustomField must be a string";if(!(null==t?void 0:t.key.startsWith(Kh)))return'Each item.key in profileCustomField must start with "Tag_Profile_Custom"'}return!0}}},setSelfStatus:{customStatus:{required:!0,rules:["string"],allowEmpty:!0}},getUserStatus:{userIDList:{required:!0,rules:["array"],allowEmpty:!1}},subscribeUserStatus:{userIDList:{required:!0,rules:["array"],allowEmpty:!1}},unsubscribeUserStatus:{userIDList:{required:!1,rules:["array"],allowEmpty:!0}}},hg={getMyProfile:!0,getUserProfile:!0,updateMyProfile:!0,setSelfStatus:!0,getUserStatus:!0,subscribeUserStatus:!0,unsubscribeUserStatus:!0};class gg{constructor(){this.userProfile=new ng,this.userStatus=new lg,this.userProfile.init(),this.userStatus.init(),cn({auth:hg,params:dg})}}function pg(e){const s=[];if(!t(e))return s;const n=e.length;if(0===n)return s;for(let t=n-1;t>=0;t--)"1"===e[t]&&s.push(2**(n-t-1));return s}var _g,mg,vg;!function(e){e.NOT_START="notStart",e.PENDING="pending",e.RESOLVED="resolved",e.REJECTED="rejected"}(_g||(_g={})),function(e){e[e.C2C=1]="C2C",e[e.GROUP=2]="GROUP"}(mg||(mg={})),function(e){e[e.C2C=8]="C2C",e[e.GROUP=2]="GROUP"}(vg||(vg={}));class fg{constructor(){this._name="SyncConversationHandler",this._pagingStatus=_g.NOT_START,this._pagingTimeStamp=0,this._pagingStartIndex=0,this._pagingPinnedTimeStamp=0,this._pagingPinnedStartIndex=0}init(){const{notificationCenter:e}=ts;ln.getInstance().registerWorkflowStep(Ds.SYNC_SERVER_INFO_AFTER_RE_ONLINE,bs.CONVERSATION_RECOVER,this._syncConversationList,this),ln.getInstance().registerWorkflowStep(Ds.SYNC_SERVER_INFO_AFTER_LOGIN,bs.CONVERSATION_LIST_SYNC,this._syncConversationListAfterLogin,this),e.subscribeInnerEvent(cs.LOGOUT,this._reset,this),e.subscribeInnerEvent(cs.DESTROY,this._dispose,this),ts.ssoLog.debug(`${this._name}.init`)}isSyncCompleted(){return this._pagingStatus===_g.RESOLVED}_syncConversationListAfterLogin(){return de(this,void 0,void 0,function*(){return this._pagingStatus=_g.NOT_START,this._pagingTimeStamp=0,this._pagingStartIndex=0,this._pagingPinnedTimeStamp=0,this._pagingPinnedStartIndex=0,this._syncConversationList()})}_syncConversationList(){return de(this,void 0,void 0,function*(){const{ssoLog:e,utils:{safeStringify:t}}=ts;e.debug("_syncConversationList","start");try{const t=yield this._pagingGetConversationList(!0);this._pagingStatus=_g.RESOLVED;const{conversationList:s=[]}=t||{};return e.info("_syncConversationList",`success count:${s.length}`),t}catch(s){const{errorCode:n,errorInfo:o}=s,i=new Xs({code:n,message:o});e.error("_syncConversationList",`fail ${t(s)}`,{error:i})}})}_pagingGetConversationList(e){return de(this,void 0,void 0,function*(){try{const t=[];this._pagingStatus=_g.PENDING;const s=yield function(e){return de(this,void 0,void 0,function*(){const{fromAccount:t,pagingTimeStamp:s,pagingStartIndex:n,pagingPinnedTimeStamp:o,pagingPinnedStartIndex:i}=e;return mn({servcmd:"recentcontact.page_get",data:{AssistFlags:31,MsgAssistFlags:15,OrderType:1,From_Account:t,StartIndex:n,TimeStamp:s,TopStartIndex:i,TopTimeStamp:o}})})}({fromAccount:En(),pagingTimeStamp:e?this._pagingTimeStamp:0,pagingStartIndex:e?this._pagingStartIndex:0,pagingPinnedTimeStamp:e?this._pagingPinnedTimeStamp:0,pagingPinnedStartIndex:e?this._pagingPinnedStartIndex:0}),{CompleteFlag:n,SessionItem:o=[],TimeStamp:i,StartIndex:r,TopTimeStamp:a,TopStartIndex:c}=s||{};if(o.length>0){const e=this._getConversationOptions(o);t.push(...e);const{notificationCenter:s}=ts;s.emitInnerEvent(cs.SYNC_CONVERSATION_LIST,{conversationUpdateFieldList:e})}if(this._pagingTimeStamp=i,this._pagingStartIndex=r,this._pagingPinnedTimeStamp=a,this._pagingPinnedStartIndex=c,1!==n){const{conversationList:s}=yield this._pagingGetConversationList(e);t.push(...s)}return{conversationList:t}}catch(e){throw e}})}_getConversationOptions(e){const{utils:{isUndefined:t}}=ts,s=this._convertConversationKey(e);return this._filterValidConversations(s).map(e=>(t(e.lastMsg)&&(e.lastMsg={elements:[]}),e.type===mg.C2C?this._assembleC2COption(e):this._assembleGroupOption(e)))}_filterValidConversations(e){return e.filter(({type:e,userID:t})=>e===mg.C2C&&!function(e){let t;return e.startsWith(As.CONV_C2C)&&(t=e.replace(As.CONV_C2C,"")),"@TLS#ERROR"===t||"@TLS#NOT_FOUND"===t}(t)||2===e)}_assembleC2COption(e){var t,s,n,o,i,r;const a=this._createUserprofile(e);return{conversationID:`${As.CONV_C2C}${e.userID}`,type:As.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===(n=e.lastMsg)||void 0===n?void 0:n.elements[0])?this._amendLayersOverLimitProp(e.lastMsg.elements[0].content):null,cloudCustomData:(null===(o=e.lastMsg)||void 0===o?void 0:o.cloudCustomData)||"",isRevoked:e.lastMessageFlag===vg.C2C,onlineOnlyFlag:!1,nick:"",nameCard:"",version:0,isPeerRead:this._computeIsPeerRead(e),revoker:(null===(r=null===(i=e.lastMsg)||void 0===i?void 0:i.revokerInfo)||void 0===r?void 0:r.revoker)||null},unreadCount:0,userProfile:a,peerReadTime:e.peerReadTime,isPinned:1===e.isPinned,customData:e.customMark||"",markList:pg(e.standardMark),conversationGroupList:[],remark:e.friendRemark||"",messageRemindType:this._transMsgRemindType(e.messageRemindType)}}_createUserprofile(e){var t;const{userID:s,nick:n,peerAvatar:o}=e,i=[{tag:"Tag_Profile_IM_Nick",value:n},{tag:"Tag_Profile_IM_Image",value:o}];return null===(t=ts.user.userProfile)||void 0===t?void 0:t.createProfile(s,i)}_computeIsPeerRead(e){const t=En(),{lastC2CMsgFromAccount:s,time:n,c2cPeerReadTime:o}=e;return s===t&&n<=o}_assembleGroupOption(e){var t,s,n;return{conversationID:`${As.CONV_GROUP}${e.groupID}`,type:As.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===vg.GROUP,onlineOnlyFlag:!1,nick:e.msgGroupFromNickName||"",nameCard:e.msgGroupFromCardName||"",revoker:(null===(n=null===(s=e.lastMsg)||void 0===s?void 0:s.revokerInfo)||void 0===n?void 0:n.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:pg(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.C2cPeerReadTime,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,n;const{utils:{isEmpty:o}}=ts;if(o(e))return null;let i="",r=null;if(!o(e.GroupTips)){const{From_Account:s,GroupName:n}=(null===(t=e.GroupTips)||void 0===t?void 0:t.GroupInfo)||{};i=As.MSG_GRP_TIP,r=Object.assign(Object.assign({},this._parseContent(i,e.GroupTips.MsgBody)),{groupProfile:{from:s,groupName:n}})}return e.MsgBody&&(i=null===(s=e.MsgBody[0])||void 0===s?void 0:s.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_Account}}}_parseContent(e,t){var s;if(!t)return t;const n=ts.message.messageFactory.getElementClass(e);return n?null===(s=n.parseServerPushElement(t))||void 0===s?void 0:s.content:t}_amendLayersOverLimitProp(e){const{LayersOverLimit:t}=e;return le(e,["LayersOverLimit"]).layersOverLimit=1===t,e}_transMsgRemindType(e){let t="";return 0===e?t=As.MSG_REMIND_ACPT_AND_NOTE:1===e?t=As.MSG_REMIND_DISCARD:2===e?t=As.MSG_REMIND_ACPT_NOT_NOTE:3===e&&(t=As.NOT_RECEIVE_OFFLINE_PUSH_EXCEPT_AT),t}_patchTypeAndPayload(e){var t;const{utils:{isUndefined:s}}=ts,{event:n,elements:o=[]}=e.lastMsg||{};return s(n)?{type:o[0]?o[0].type:null,payload:o[0]?this._amendLayersOverLimitProp(o[0].content):null}:{type:As.MSG_GRP_TIP,payload:(null===(t=null==o?void 0:o[0])||void 0===t?void 0:t.content)||{}}}_computeGroupUnreadCount(e){const{unreadCount:t=0,noUnreadCount:s=0}=e,n=t-s;return n>0?n:0}_reset(){this._pagingStatus=_g.NOT_START,this._pagingTimeStamp=0,this._pagingStartIndex=0,this._pagingPinnedTimeStamp=0,this._pagingPinnedStartIndex=0}_dispose(){this._reset();const{notificationCenter:e}=ts;e.unSubscribeInnerEvent(cs.LOGOUT,this._reset,this),e.unSubscribeInnerEvent(cs.DESTROY,this._dispose,this)}}class Ig{constructor(){this.syncConversationHandler=new fg,this.syncConversationHandler.init()}}ts.ssoLog.debug(`TencentCloudLiteChat.VERSION:${it}`);var Eg={create:function(e){var t,s;const{SDKAppID:n,testEnv:o=!1,devMode:i=!1,unlimitedAVChatRoom:r=!1,scene:a="",oversea:c=!1,instance:u,disableIndependentDomain:l=!1}=e;let d=n;if(!function(e){if("number"==typeof e)return!0;const t=Number(e);return!Number.isNaN(t)}(d))return console.error("Create SDK instance failed. Failed to parse the SDKAppID, please check the arguments"),null;if(d=Number(d),dn.has(d))return dn.get(d);let h=null;if(u)h=u,h._workflowManager&&ln.setInstance(h._workflowManager),h._pluginManager&&h._pluginManager.installBuiltInPlugin(bd),u.isReady()&&(null===(s=(t=ln.getInstance()).executeWorkflow)||void 0===s||s.call(t,Ds.SYNC_SERVER_INFO_AFTER_LOGIN));else{const e=function(){function e(){return(65536*(1+Math.random())|0).toString(16).substring(1)}return`${e()+e()}${e()}${e()}${e()}${e()}${e()}${e()}`}();ts.init({sdkAppId:d,instanceId:e,testEnv:o,devMode:i,unlimitedAVChatRoom:r,disableIndependentDomain:l,scene:a,oversea:c,sdkEdition:Dd}),ln.getInstance().init(),ts.message=new Vh,ts.user=new gg,ts.login=new Vd,ts.conversation=new Ig,Ld.getInstance().installBuiltInPlugin(bd),h=Fd.getInstance().exposeApiForClient(),h._workflowManager=ln.getInstance(),h._pluginManager=Ld.getInstance()}return dn.set(d,h),h},TSignaling:us,EVENT:rs,VERSION:it,TYPES:As};return Eg});
|