UNPKG

@rongcloud/imkit-store

Version:

RongCloud IM UIKit Store

1 lines 55.6 kB
import{ConversationType as e,BaseMessage as t,sendMessage as s,getFileToken as i,getFileUrl as o,MessageType as n,addEventListener as a,Events as r,getHistoryMessages as c,ErrorCode as h,recallMessage as _,SentStatus as u,sendReadReceiptResponseV5 as d,getMessageReadReceiptInfoV5 as l,clearMessagesUnreadStatus as g,removeEventListener as S,getMessagesReadReceiptUsersByPageV5 as p,sendTypingStatusMessage as E,getAppSettings as m,getMessageReadReceiptInfoV5ByIdentifiers as T,getConversationList as f,NotificationLevel as I,sendSyncReadStatusMessage as O,requestSpeechToTextForMessage as C,removeMonitor as R,addMonitor as y,removeConversation as M,setConversationNotificationLevel as N,setConversationToTop as v,disconnect as A,__addSDKVersion as U,GroupReadReceiptVersion as P,installPlugin as D,createLogDBProxy as G}from"@rongcloud/imlib-next";import{isObject as w,ErrorCode as L,MAX_UPLOAD_FILE_SIZE as $,fixUrlProtocol as V,UploadMethod as b,FileType as x,MessageDirection as F,ConversationType as k,RCConnectionStatus as q}from"@rongcloud/engine";import{makeAutoObservable as Q,observable as K,runInAction as B,reaction as H,comparer as z}from"mobx";const Y=e=>`[${e.targetId}][${e.conversationType}][${e.channelId||""}]`,J=e=>{const[t,s,i]=e.split("][");return{targetId:t.replace("[",""),conversationType:~~s,channelId:i.replace("]","")}},X=(e,t)=>e.targetId===t.targetId&&e.conversationType===t.conversationType&&(e.channelId===t.channelId||!t.channelId);e.PRIVATE,e.GROUP,e.SYSTEM;const W=(e,t)=>{const s=e.messageUId&&t.messageUId?"messageUId":"messageId";return e[s]===t[s]},j=e=>JSON.parse(JSON.stringify(e)),Z=(e,t=new WeakMap)=>{if(null===e||"object"!=typeof e||!e)return e;if(t.has(e))return t.get(e);let s;if(e instanceof Date)s=new Date(e.getTime());else if(e instanceof RegExp)s=new RegExp(e);else if(e instanceof Map)s=new Map,t.set(e,s),e.forEach((e,i)=>{s.set(i,Z(e,t))});else if(e instanceof Set)s=new Set,t.set(e,s),e.forEach(e=>{s.add(Z(e,t))});else if(Array.isArray(e)){s=[],t.set(e,s);for(let i=0;i<e.length;i++)s[i]=Z(e[i],t)}else{s=Object.create(Object.getPrototypeOf(e)),t.set(e,s);for(const i in e)Object.prototype.hasOwnProperty.call(e,i)&&(s[i]=Z(e[i],t))}return s},ee=()=>"undefined"!=typeof uni&&"function"==typeof uni.getSystemInfoSync;var te;!function(e){e.android="android",e.ios="ios"}(te||(te={}));const se=(t,s)=>{const i=uni.$RongKitStore.enableReadV5&&[e.PRIVATE,e.GROUP].includes(t),o=t===e.GROUP&&s&&s.directionalUserIdList&&s.directionalUserIdList.length>0;return!(!i||o)};class ie{queue=[];maxSize;constructor(e){this.maxSize=e,Q(this)}push(e,t){this.queue.push(Z(e)),t&&this._trimExcess(!0)}pop(){return this.queue.pop()}unshift(e,t){this.queue.unshift(...Z(e)),t&&this._trimExcess(!1)}shift(){return this.queue.shift()}clear(){this.queue=[]}set(e,t=!0){this.queue=Z(e),t&&this._trimExcess()}get(){return Z(this.queue)}resetExcess(){this._trimExcess()}splice(e,t,...s){this.queue.splice(e,t,...Z(s))}_trimExcess(e=!0){0!==this.maxSize&&(this.queue.length<this.maxSize||(e?this.queue.splice(0,this.queue.length-this.maxSize):this.queue.splice(this.maxSize,this.queue.length-this.maxSize)))}get length(){return this.queue.length}}class oe{maxKeySize;map=new Map;activeMap=new Map;constructor(e=30){this.maxKeySize=e,Q(this,{map:K,activeMap:!1})}get(e){const t=this.map.get(e);if(t)return this.activeMap.set(e,Date.now()),t.get()}getQueue(e){const t=this.map.get(e);if(t)return this.activeMap.set(e,Date.now()),t}set(e,t,s=!0,i=30){const o=new ie(i);o.set(t,s),this.map.set(e,o),this.activeMap.set(e,Date.now()),this.removeOverdueKey()}removeOverdueKey(){if(this.map.size<=this.maxKeySize)return;const e=Array.from(this.activeMap.entries());e.sort((e,t)=>t[1]-e[1]);e.slice(this.maxKeySize).forEach(e=>{this.delete(e[0])})}delete(e){this.map.get(e)?.clear(),this.map.delete(e),this.activeMap.delete(e)}resetAllExcess(){this.map.forEach(e=>{e.resetExcess()})}resetExcess(e){this.map.get(e)?.resetExcess()}clear(){this.map.forEach(e=>{e.clear()}),this.map.clear(),this.activeMap.clear()}retain(e){this.map.forEach(t=>{this.map.get(e)||t.clear()});const t=this.activeMap.get(e);this.activeMap.clear(),t&&this.activeMap.set(e,t),console.warn("retain activeMap",this.activeMap),console.warn("retain map",this.map)}}var ne,ae,re;!function(e){e.K_INIT_O="K_INIT_O",e.K_NOTIFY_GET_CONVERSATIONS_O="K_NOTIFY-GET-CONVERSATIONS_O",e.K_REMOVE_CONVERSATION_O="K_REMOVE-CONVERSATION_O",e.K_OPEN_CONVERSATION_O="K_OPEN-CONVERSATION_O",e.K_USER_PROFILE_NOT_FOUND_O="K_USER-PROFILE-NOT-FOUND_O",e.K_GROUP_PROFILE_NOT_FOUND_O="K_GROUP-PROFILE-NOT-FOUND_O",e.K_SYSTEM_PROFILE_NOT_FOUND_O="K_SYSTEM-PROFILE-NOT-FOUND_O",e.K_CREATE_CACHED_CONVERSATION_O="K_CREATE-CACHED-CONVERSATION_O",e.S_UPDATE_CACHE_O="S_UPDATE-CACHE_O",e.S_GET_CONVERSATION_E="S_GET-CONVERSATION_E",e.S_GET_CONVERSATION_T="S_GET-CONVERSATION_T",e.S_GET_CONVERSATION_R="S_GET-CONVERSATION_R",e.S_PUSH_2_QUEUE_O="S_PUSH-2-QUEUE_O",e.S_TASK_QUEUE_EXECUTE_O="S_PICK-ITEM-FROM-QUEUE_O",e.S_SEND_MSG_T="S_SEND-MSG_T",e.S_SEND_MSG_R="S_SEND-MSG_R",e.S_SEND_MSG_E="S_SEND-MSG_E",e.L_PARSE_CONVERSATION_E="L_PARSE_CONVERSATION_E",e.S_GET_GROUP_MEMBERS_HOOK_T="S_GET-GROUP-MEMBERS-HOOK_T",e.S_GET_GROUP_MEMBERS_HOOK_R="S_GET-GROUP-MEMBERS-HOOK_R",e.S_GET_GROUP_MEMBERS_HOOK_E="S_GET-GROUP-MEMBERS-HOOK_E",e.S_PARSE_CONVERSATION_E="S_PARSE-CONVERSATION_E",e.S_REMOVE_CONVERSATION_O="S_REMOVE-CONVERSATION_O",e.S_UPDATE_CONVERSATION_O="S_UPDATE-CONVERSATION_O",e.S_INSERT_MESSAGE_O="S_INSERT-MESSAGE_O",e.S_UPDATE_MESSAGE_O="S_UPDATE-MESSAGE_O",e.S_REMOVE_MESSAGE_O="S_REMOVE-MESSAGE_O",e.S_RECALL_MESSAGE_O="S_RECALL-MESSAGE_O",e.S_GET_HISTORY_MESSAGE_O="S_GET-HISTORY-MESSAGE_O",e.S_SEND_MESSAGE_O="S_SEND-MESSAGE_O",e.S_FORWARD_MESSAGE_O="S_FORWARD-MESSAGE_O",e.S_CANCEL_SEND_MEDIA_MESSAGE_O="S_CANCEL-SEND-MEDIA-MESSAGE_O",e.S_GET_SELECTED_MESSAGES_O="S_GET-SELECTED-MESSAGES_O",e.S_SET_SELECTED_MESSAGES_O="S_SET-SELECTED-MESSAGES_O",e.S_ON_SEND_BEFORE_S="S_ON-SEND-BEFORE_S",e.S_CLEAR_UNREAD_COUNT_O="S_CLEAR-UNREAD-COUNT_O",e.S_CLEAR_MESSAGES_UNREAD_STATUS_T="S_CLEAR-MESSAGES-UNREAD-STATUS_T",e.S_CLEAR_MESSAGES_UNREAD_STATUS_R="S_CLEAR-MESSAGES-UNREAD-STATUS_R",e.S_REMOVE_CONVERSATION_T="S_REMOVE-CONVERSATION_T",e.S_REMOVE_CONVERSATION_R="S_REMOVE-CONVERSATION_R",e.S_SET_CONVERSATION_NOTIFICATION_LEVEL_T="S_SET-CONVERSATION-NOTIFICATION-LEVEL_T",e.S_SET_CONVERSATION_NOTIFICATION_LEVEL_R="S_SET-CONVERSATION-NOTIFICATION-LEVEL_R",e.S_SET_CONVERSATION_TO_TOP_T="S_SET-CONVERSATION-TO-TOP_T",e.S_SET_CONVERSATION_TO_TOP_R="S_SET-CONVERSATION-TO-TOP_R",e.S_RECALL_MESSAGE_T="S_RECALL-MESSAGE_T",e.S_RECALL_MESSAGE_R="S_RECALL-MESSAGE_R",e.S_RECEIVE_DISCONNECT_NOTIFICATION_O="S_RECEIVE-DISCONNECT-NOTIFICATION_O",e.S_STT_RESPONSE_O="S_STT-RESPONSE_O",e.S_STT_RESPONSE_E="S_STT-RESPONSE_E",e.S_STT_RESPONSE_R="S_STT-RESPONSE_R",e.S_STT_REQUEST_T="S_STT-REQUEST_T",e.S_STT_REQUEST_R="S_STT-REQUEST_R",e.S_STT_REQUEST_E="S_STT-REQUEST_E",e.S_STT_TIMEOUT_E="S_STT-TIMEOUT_E",e.S_SENF_V5_RECEIPT_T="S_SENF-V5-RECEIPT_T",e.S_SENF_V5_RECEIPT_R="S_SENF-V5-RECEIPT_R",e.S_SENF_V5_RECEIPT_O="S_SENF-V5-RECEIPT_O"}(ne||(ne={})),function(e){e[e.TASK_CANCEL=39001]="TASK_CANCEL"}(ae||(ae={}));class ce{_parallel;_fps;_logger;_timestamps=[];_queue=[];_executing=[];_timer=-1;constructor(e=5,t=5,s){this._parallel=e,this._fps=t,this._logger=s}destroy(){clearTimeout(this._timer),this._timer=-1}async push(e){return new Promise(t=>{this._queue.push({params:e,resolve:t}),this._logger.info(ne.S_PUSH_2_QUEUE_O,`${this._tag}: queue length: ${this._queue.length}`),this._execute()})}async _execute(){if(this._paused||0===this._queue.length||this._executing.length>=this._parallel)return;if(this._timestamps.length>=this._fps)return void this._logger.warn(ne.S_TASK_QUEUE_EXECUTE_O,`${this._tag}: trigger limiting`);-1===this._timer&&(this._timer=setTimeout(()=>{this._timestamps.length=0,this._timer=-1,this._execute()},1e3));const e=this._queue.shift();this._executing.push(e),this._timestamps.push(Date.now()),this._logger.info(ne.S_TASK_QUEUE_EXECUTE_O,`${this._tag}: queue length: ${this._queue.length}, executing length: ${this._executing.length}`);const t=this._handle(e.params);this._execute();const{code:s,data:i}=await t;e.code=s,e.result=i,this._checkResolve()}_checkResolve(){for(;this._executing.length&&void 0!==this._executing[0].code;){const{resolve:e,code:t,result:s}=this._executing.shift();e({code:t,data:s})}this._execute()}_paused=!1}class he extends ce{_logger;_tag="MessageSendQueue";constructor(e){super(10,5,e),this._logger=e}async _handle(e){const{conversation:i,message:o,options:n}=e,{conversationType:a,targetId:r,channelId:c}=i,h=this._logger.createTraceId();this._logger.info(ne.S_SEND_MSG_T,`type: ${o.messageType}, conversationType: ${a}, targetId: ${r}, channelId: ${c||""}`,h);const{isCounted:_,isPersited:u,content:d,messageType:l}=o,g=new t(l,d,u,_);if(w(g.content))try{g.content=j(g.content)}catch(e){this._logger.warn(ne.S_SEND_MSG_E,e.message)}const S={...n,needReceipt:se(a,n||{})},{code:p,data:E}=await s(i,g,{...S,onSendBefore(e){o.messageId=e.messageId,n?.onSendBefore?.(e)}});return p!==L.SUCCESS?this._logger.warn(ne.S_SEND_MSG_R,`code: ${p}`,h):this._logger.info(ne.S_SEND_MSG_R,"success",h),{code:p,data:E}}}!function(e){e.ALIYUN="aliyun",e.S3="s3",e.STC="stc",e.MINIO="minio",e.QINIU="qiniu",e.BAIDU="baidu",e.RCX="rcx"}(re||(re={}));class _e{_url;_getFileToken;_serverType=0;constructor(e,t,s){this._url=e,this._getFileToken=t,this._serverType=s}async safeExecute(e,t,s,i=L.UPLOAD_FAIL){try{return await e.execute(t)}catch(e){return console.error(`${s} request.execute error`,e),{code:i,msg:e instanceof Error?e.message:String(e)}}}upload(e,t){return e.fileSize>$?Promise.resolve({code:L.UPLOAD_FAIL,msg:"the file size is over 5GB!"}):this.commonUpload(e,t)}}function ue(e){switch(e){case x.IMAGE:return"image/jpeg";case x.AUDIO:return"audio/amr";case x.VIDEO:return"video/mpeg4";case x.FILE:return"application/octet-stream";case x.SIGHT:return"video/mpeg4";case x.COMBINE_HTML:return"text/html";default:return"multipart/form-data"}}class de{uploadInfo;_abortStatus=!1;constructor(e){this.uploadInfo=e}abort(){this._abortStatus=!0}isAbort(){return this._abortStatus}}const le={[re.QINIU]:class extends _e{async commonUpload(e,t){const{fileType:s}=e;try{const{code:e,data:i,msg:o}=await this._getFileToken(s,void 0,void 0,void 0);if(e!==L.SUCCESS)return{code:e,msg:o};const n=i,a={token:n.token,key:n.fileName},r={url:V(this._url),headers:{},body:a,method:"POST"},c=await this.safeExecute(t,r,re.QINIU);return 200===c.code||204===c.code?{code:L.SUCCESS,data:{uniqueName:n.fileName,uploadMethod:b.QINIU}}:{code:L.UPLOAD_FAIL,msg:c.msg}}catch(e){return console.error("QINIU prepareUploadData error",e),{code:e}}}},[re.ALIYUN]:class extends _e{async commonUpload(e,t){const{fileType:s}=e;try{const{code:e,data:i,msg:o}=await this._getFileToken(s,void 0,void 0,void 0);if(e!==L.SUCCESS||!i)return{code:e,msg:o};const n=i,a=V(`${i.ossBucketName}.${this._url}`),r={url:a,headers:{},body:{token:n.token,OSSAccessKeyId:n.osskeyId,policy:n.ossPolicy,Signature:n.ossSign,success_action_status:"200",key:n.fileName},method:"POST"},c=await this.safeExecute(t,r,re.ALIYUN);return 200===c.code||204===c.code?{code:L.SUCCESS,data:{uniqueName:n.fileName,uploadMethod:b.ALI}}:{code:L.UPLOAD_FAIL,msg:c.msg}}catch(e){return console.error("ALIYUN commonUpload error",e),{code:e}}}},[re.S3]:class extends _e{async commonUpload(e,t){const{fileType:s}=e;try{const{code:e,data:i,msg:o}=await this._getFileToken(s,void 0,void 0,void 0);if(e!==L.SUCCESS||!i)return{code:e,msg:o};const n=i,a=V(`${n.s3BucketName}.${this._url}`),r={url:a,headers:{},body:{"Content-Type":ue(s),"Content-Disposition":s===x.COMBINE_HTML?"inline":"attachment","x-amz-credential":n.s3Credential,"x-amz-algorithm":n.s3Algorithm,"x-amz-date":n.s3Date,policy:n.s3Policy,"x-amz-signature":n.s3Signature,key:n.fileName},method:"POST"},c=await this.safeExecute(t,r,re.S3);return 200===c.code||204===c.code?{code:L.SUCCESS,data:{uniqueName:n.fileName,uploadMethod:b.AWS}}:{code:L.UPLOAD_FAIL,msg:c.msg}}catch(e){return console.error("S3 commonUpload error",e),{code:e}}}},[re.MINIO]:class extends _e{async commonUpload(e,t){const{fileName:s,fileType:i,buffer:o}=e;try{const{code:o,data:n,msg:a}=await this._getFileToken(i,void 0,"PUT",void 0);if(o!==L.SUCCESS||!n)return{code:o,msg:a};const r=n,c=V(`${this._url}/${r.minioBucketName}/${r.fileName}`),h=i===x.COMBINE_HTML?"inline":"attachment",_={url:c,headers:{"Content-Disposition":`${h}; filename=${encodeURIComponent(s||r.fileName)};`,Authorization:r.minioAuthorization,"x-amz-content-sha256":r.minioContentSha256,"x-amz-date":r.minioDate,"Content-Type":ue(i)||"text/plain"},body:{},method:"PUT",filePath:e.path},u=await this.safeExecute(t,_,re.MINIO);return 200===u.code||204===u.code?{code:L.SUCCESS,data:{uniqueName:r.fileName,uploadMethod:b.MINIO}}:{code:L.UPLOAD_FAIL,msg:u.msg}}catch(e){return console.error("MINIO commonUpload error",e),{code:e}}}}};async function ge(e,t,s){const{serverType:n,customDomain:a,ossConfig:r,uploadServer:c,bosAddr:h}=t;if(!r||0===r.length)return{code:L.INVALID_PARAMETER_MEDIA_URL,msg:"ossConfig is empty"};const _=function(e,t,s,i,o){if(s)return[{type:re.RCX,url:s,p:"1"}];if(e)return JSON.parse(e).map(e=>{const t={type:re.QINIU,url:"",p:""};return Object.keys(e).forEach(s=>{"p"===s?t.p=e[s]:(t.type=s,t.url=e[s])}),t}).sort((e,t)=>e.p-t.p);const n=[];return i&&n.push({type:re.QINIU,url:i,p:"1"}),o&&n.push({type:re.BAIDU,url:o,p:"2"}),n}(r,0,a,c,h);if(0===_.length)return{code:L.INVALID_PARAMETER_MEDIA_URL,msg:"uploadUrlList is empty"};const u=[];for(let t=0;t<_.length;t++){const a=_[t];if(!(a.type in le))continue;const r=new le[a.type](a.url,i,n),{code:c,data:h,msg:d}=await r.upload(e,s);try{if(c===L.RC_FILE_SIZE_EXCEED_LIMIT)return{code:c,msg:"File size exceeds the limit"};if(c===L.INVALID_PARAMETER_SIZE_NOT_FOUND)return{code:c,msg:"File size not found"};if(s.isAbort())return{code:c,msg:d};if(c===L.SUCCESS&&h){let{downloadUrl:t,uploadMethod:s,uniqueName:i}=h;if(!t){const n=await o(e.fileType,i||"",i,void 0,s);n.code===L.SUCCESS&&n.data&&(t=n.data.downloadUrl)}return t?{code:L.SUCCESS,data:{downloadUrl:t}}:{code:L.UPLOAD_FAIL,msg:"Get download url fail"}}u.push({type:a.type,url:a.url,code:c,msg:d})}catch(e){u.push({type:a.type,url:a.url,code:L.UPLOAD_FAIL,msg:e instanceof Error?e.message:String(e)})}}return{code:L.UPLOAD_FAIL,data:{downloadUrl:"",msg:`Failed to upload through all channels, msg: ${JSON.stringify(u)}`}}}class Se extends ce{_logger;constructor(e){super(2,5,e),this._logger=e}_tag="UploadQueue";_handle(e){const{info:t,config:s,request:i}=e;return ge(t,s,i)}}class pe{_logger;rootStore;_context;#e=new oe(10);#t;#s;#i=new Map;#o={[n.IMAGE]:"imageUri",[n.SIGHT]:"sightUrl",[n.HQ_VOICE]:"remoteUrl",[n.GIF]:"remoteUrl",[n.FILE]:"fileUrl"};#n=new Set;#a=[];constructor(e,t,s){this._logger=e,this.rootStore=t,this._context=s,Q(this),a(r.MESSAGES,this.#r.bind(this)),a(r.MESSAGE_RECEIPT_RESPONSE_V5,this.#c),this.#t=new he(this._logger),this.#s=new Se(this._logger)}getMessages(t){const s=this.#e.get(t);if(!s||0===s.length)return[];const{conversationType:i}=J(t);switch(i){case e.GROUP:return this.#h(s);case e.SYSTEM:return this.#_(s);default:return this.#u(s)}}getMessageByUid(t,s){if(!t||!s)return;const i=Y(t),{conversationType:o}=J(i),n=(this.#e.get(i)||[]).find(e=>e.messageUId===s);if(!n)return;let a;switch(o){case e.GROUP:[a]=this.#h([n]);break;case e.SYSTEM:[a]=this.#_([n]);break;default:[a]=this.#u([n])}return a}#h(e){if(0===e.length)return[];const t=this.rootStore.appData.groupMembersCache.getGroupMemberMap(e[0].targetId);return e.map(e=>({...e,user:{nickname:t.get(e.senderUserId)?.user.nickname||"",portraitUri:t.get(e.senderUserId)?.user.portraitUri||"",groupNickname:t.get(e.senderUserId)?.groupNickname||""},readReceiptInfo:e.readReceiptInfo}))}#u(e){return 0===e.length?[]:e.map(e=>{const t=this.rootStore.appData.getUserInfo(e.senderUserId);return{...e,user:{nickname:t?.name||"",portraitUri:t?.portraitUri||""},readReceiptInfo:e.readReceiptInfo}})}#_(e){if(0===e.length)return[];const t=this.rootStore.appData.getSystemProfile(e[0].senderUserId);return e.map(e=>({...e,user:{nickname:t?.name||"",portraitUri:t?.portraitUri||""},readReceiptInfo:e.readReceiptInfo}))}#d=()=>{const e=this._context.getNaviInfo();if(e&&"ossConfig"in e)return e.ossConfig};async getHistoryMsgList(e,t,s,i=20){this._logger.info(ne.S_GET_HISTORY_MESSAGE_O,`${e}, ${t}, ${s}, ${i}`);const{code:o,data:n}=await c(J(e),{timestamp:t,count:i});if(o===h.SUCCESS&&n){const{list:t}=n;B(()=>{s?this.#e.getQueue(e)?.unshift(t,!1):this.#e.set(e,t,!0,10)});try{if(this.rootStore.enableReadV5&&t?.length){const s=J(e),i=t.filter(e=>1===e.messageDirection&&!!e.messageUId).map(e=>e.messageUId);this.fetchReadReceiptV5(s,i)}}catch(e){this._logger.warn(ne.S_SEND_MSG_E,`fetch V5 after history error: ${e}`)}}return{code:o,data:n}}insertMessage(e,t=!0,s=!0){const i={conversationType:e.conversationType,targetId:e.targetId,channelId:e.channelId},o=Y(i);e.messageId&&0!==e.messageId||(e.messageId=(()=>{let e=0;const t=((4294967295&Date.now())>>>0).toString(2),s=Math.floor(255*Math.random()),i=t+e.toString(2).padStart(11,"0")+s.toString(2).padStart(8,"0");return e=2047&++e,parseInt(i,2)})());const n=this.#e.get(o);let a=!1;return n&&(a=n.some(t=>W(t,e))),s&&this._logger.info(ne.S_INSERT_MESSAGE_O,`${o}, ${e.messageUId}, ${e.messageId}, isRepeat: ${a}`),a||this.#e.getQueue(o)?.push(e,t),e}updateCatchedMessage(e){const t=Y({conversationType:e.conversationType,targetId:e.targetId,channelId:e.channelId});this._logger.info(ne.S_UPDATE_MESSAGE_O,`${t}, ${e.messageUId}, ${e.messageId}, ${e.messageType}, ${e.senderUserId}, ${e.sentTime}, ${e.sentStatus}, ${e.readReceiptInfo}`);const s=this.#e.getQueue(t);if(!s)return;const i=s.get(),o=i.findIndex(t=>W(t,e));-1!==o&&s.splice(o,1,{...e,sentTime:e.sentTime||i[o].sentTime})}removeCatchedMessage(e){const t=Y({conversationType:e.conversationType,targetId:e.targetId,channelId:e.channelId});this._logger.info(ne.S_REMOVE_MESSAGE_O,`${t}, ${e.messageUId}, ${e.messageId}`);const s=this.#e.getQueue(t);if(!s)return;const i=s.get().findIndex(t=>W(t,e));-1!==i&&s.splice(i,1)}async recallMessage(e){const{conversationType:t,targetId:s,channelId:i}=e;return this._logger.info(ne.S_RECALL_MESSAGE_O,`${t}, ${s}, ${i}, ${e.messageUId}`),_({conversationType:t,targetId:s,channelId:i},{messageUId:e.messageUId,sentTime:e.sentTime})}async sendMessage(e,t,s){return this._logger.info(ne.S_SEND_MESSAGE_O,`${e}, ${t.messageType}, ${s?.messageId}`),this.#t.push({conversation:J(e),message:this.#l(J(e),t),options:s})}async sendMediaMessage(e){const{conversationKey:t,message:s,info:i,request:o,sendOptions:a}=e;if(s.messageType!==n.IMAGE&&s.messageType!==n.SIGHT&&s.messageType!==n.HQ_VOICE&&s.messageType!==n.GIF&&s.messageType!==n.FILE)return{code:h.INVALID_PARAMETER_MESSAGE_CONTENT,msg:"Invalid message type"};const r=i?.path,c=this.#l(J(t),s,a,r);let _,d,l;if(a?.messageId?(d=a.messageId,c.sentStatus=u.SENDING,this.updateCatchedMessage(c),_=c):(_=this.insertMessage(c,!1,!0),d=_.messageId),!d)return{code:h.UPLOAD_FAIL,msg:"Insert message failed"};this.#i.set(d,o);try{const e={ossConfig:this.#d()};if(l=await this.#s.push({info:i,request:o,config:e}),l.code===h.SUCCESS&&l.data){const{data:e}=l,i=this.#o[s.messageType];if(i&&e?.downloadUrl){s.content[i]=e.downloadUrl;const o={...a||{},messageId:d};return s.messageType===n.HQ_VOICE&&(o.sampleRate=16e3,o.numberOfChannels=1),await this.sendMessage(t,s,o)}this._logger.warn(ne.S_SEND_MSG_E,`Cannot set media URL: propertyName=${i}, hasUrl=${!!e?.downloadUrl}`)}else this._logger.warn(ne.S_SEND_MSG_E,`Media upload failed: code=${l.code}, error=${l?.data?.msg}`)}catch(e){this._logger.error(ne.S_SEND_MSG_E,`Exception in sendMediaMessage: ${e}`)}finally{this.#i.delete(d)}return _.sentStatus=u.FAILED,this.updateCatchedMessage(_),{code:h.UPLOAD_FAIL,msg:`Upload failed: ${l?.data?.msg}`,data:_}}async sendV5Receipts(e,t){if(!this.rootStore.enableReadV5)return;const s=Array.from(new Set((t||[]).filter(Boolean)));if(0===s.length)return void this._logger.info(ne.S_SENF_V5_RECEIPT_O,`sendV5Receipts ids size is 0, messageUIds: ${JSON.stringify(t)}`);const i=Y(e),o=this.#e.get(i)||[],n=new Set(s.filter(e=>{const t=o.find(t=>t.messageUId===e);if(!t)return!1;const s=2===t.messageDirection,i=!this.#n.has(e)&&!0!==t.sendReceipt;return s&&i}));if(0===n.size)return void this._logger.info(ne.S_SENF_V5_RECEIPT_O,"sendV5Receipts messageUIds size is 0");const a=Array.from(n);try{this._logger.info(ne.S_SENF_V5_RECEIPT_T,`sendV5Receipts: ${JSON.stringify(a)}`);const t=await d(e,a);this._logger.info(ne.S_SENF_V5_RECEIPT_R,`sendV5Receipts res: ${JSON.stringify(t)}`),a.forEach(e=>this.#n.add(e)),this.#g(e,a)}catch(e){this._logger.warn(ne.S_SEND_MSG_E,`sendV5Receipts error: ${e}`)}}async fetchReadReceiptV5(e,t){if(!this.rootStore.enableReadV5)return;const s=(t||[]).filter(Boolean);if(0!==s.length)try{const t=await l(e,s),i=t?.data||[];if(!Array.isArray(i)||0===i.length)return;const o=Y(e),n=this.#e.get(o)||[];i.forEach(e=>{const t=n.find(t=>t.messageUId===e?.messageUId);t&&(t.readReceiptInfo=e,this.updateCatchedMessage(t))})}catch(e){this._logger.warn(ne.S_SEND_MSG_E,`fetchReadReceiptV5 error: ${e}`)}}async getReadReceiptUsersV5(e,t,s){const i={read:{list:[],total:0,pageToken:""},unread:{list:[],total:0,pageToken:""}};if(!this.rootStore.enableReadV5||!t)return i;const o=s?.pageCount??100,n="number"!=typeof s?.type||0===s?.type,a="number"!=typeof s?.type||1===s?.type,r=this.rootStore.appData.groupMembersCache.getGroupMemberMap(e.targetId),c=async(s,i)=>{const n={pageToken:i||void 0,pageCount:o,readStatus:s},a=await p(e,t,n),c=a?.data||{},h=c.users||[],_="number"==typeof c.totalCount?c.totalCount:0,u=c.pageToken;return{list:h.map(e=>({id:e.userId,name:r.get(e.userId)?.user.nickname||r.get(e.userId)?.groupNickname||e.userId,portraitUri:r.get(e.userId)?.user.portraitUri,timestamp:e.timestamp})),total:_,pageToken:u}},h={...i};if(n){const e=await c(0,s?.pageTokenRead);h.read=e}if(a){const e=await c(1,s?.pageTokenUnread);h.unread=e}return h}forwardMessage(e,t){return this._logger.info(ne.S_FORWARD_MESSAGE_O,`${e}, ${t.messageType}, ${t.messageUId}`),this.#t.push({conversation:J(e),message:t})}cancelSendMediaMessage(e){this._logger.info(ne.S_CANCEL_SEND_MEDIA_MESSAGE_O,`${e}`);const t=this.#i.get(e);t&&(t.abort(),this.#i.delete(e))}getSelectedMessages(){return this._logger.info(ne.S_GET_SELECTED_MESSAGES_O),j(this.#a)}setSelectedMessages(e){this._logger.info(ne.S_SET_SELECTED_MESSAGES_O,`${e.length}`),this.#a=e}clearExcessMessage(e){this.#e.resetExcess(e)}#r(e){e.messages.forEach(e=>{const{conversationType:t,targetId:s,channelId:i,isPersited:o}=e,a=Y({conversationType:t,targetId:s,channelId:i});switch(e.messageType){case n.RECALL_MESSAGE_TYPE:this.removeCatchedMessage({...e,messageUId:e.content.messageUId});break;case"RC:SRSMsg":g({conversationType:t,targetId:s,channelId:i})}o&&this.insertMessage(e,a!==this.rootStore.conversationStore?.openedConversation?.key,!1)})}#c=e=>{try{if(!e||!Array.isArray(e))return;e.forEach(e=>{const t=Y({conversationType:e?.identifier?.conversationType,targetId:e?.identifier?.targetId,channelId:e?.identifier?.channelId}),s=this.#e.getQueue(t);if(!s)return;const i=s.get(),o=i.findIndex(t=>t.messageUId===e?.messageUId);if(-1!==o){const s={...i[o]};s.readReceiptInfo=e,this.updateCatchedMessage(s);try{const e=this.rootStore.conversationStore?.conversations.find(e=>e.key===t);e&&e.latestMessage&&e.latestMessage.messageUId===s.messageUId&&this.rootStore.conversationStore.updateCacheConversation(t,{latestMessage:{...e.latestMessage,readReceiptInfo:s.readReceiptInfo}})}catch(e){this._logger.warn(ne.S_SEND_MSG_E,`onV5ReceiptResponse error: ${e}`)}}})}catch(e){this._logger.warn(ne.S_SEND_MSG_E,`onV5ReceiptResponse error: ${e}`)}};#g(e,t){try{if(!t||!t.length)return;const s=Y(e),i=this.#e.getQueue(s);if(!i)return;const o=i.get(),n=new Set(t);o.forEach(e=>{if(e.messageUId&&n.has(e.messageUId)){const t={...e};t.sendReceipt=!0,this.updateCatchedMessage(t)}})}catch(e){this._logger.warn(ne.S_SEND_MSG_E,`markSendReceiptTrue error: ${e}`)}}#l(e,t,s,i){const{conversationType:o,targetId:n,channelId:a}=e,{isCounted:r,isPersited:c,content:h,messageType:_}=t;return{targetId:n,conversationType:o,messageDirection:1,messageType:_,sentTime:this._context.getServerTime(),isStatusMessage:s?.isStatusMessage,isCounted:r,isPersited:c,content:h,channelId:a||"",senderUserId:this._context.getCurrentId(),receivedTime:0,messageUId:"",sentStatus:u.SENDING,isOffLineMessage:!1,canIncludeExpansion:s?.canIncludeExpansion||!1,receivedStatus:0,isMentioned:s?.isMentioned,expansion:s?.expansion,messageId:s?.messageId,localTmpPath:i}}destroy(){S(r.MESSAGES,this.#r),this.clearMemoryData()}clearMemoryData(){this.#e.clear(),this.#t.destroy(),this.#s.destroy(),this.#i.clear(),this.#a=[]}}class Ee{static DISAPPEAR_INTERVAL=6e3;static typingSupportTypes=[e.PRIVATE];typingMap=K.map();#S=new Map;#p=new Map;#E=Ee.DISAPPEAR_INTERVAL;constructor(){Q(this),a(r.TYPING_STATUS,this.#m),a(r.MESSAGES,this.#T)}dispose(){S(r.TYPING_STATUS,this.#m),S(r.MESSAGES,this.#T),this.#p.forEach(e=>clearTimeout(e)),this.#p.clear(),this.typingMap.clear(),this.#S.clear()}async sendTyping(e,t){if(-1===Ee.typingSupportTypes.indexOf(e.conversationType))return;const s=this.getTypingMapKey(e);this.#S.has(s)||(this.#S.set(s,Date.now()),setTimeout(()=>this.#S.delete(s),this.#E),await E(e,t))}isTyping(e){const t=this.typingMap.get(this.getTypingMapKey(e)),s=t?Array.from(t.values()):[];return{active:s.length>0,list:s}}#m=e=>{e&&e.status&&e.status.forEach(e=>{const{conversationType:t,targetId:s,channelId:i,list:o}=e;if(-1===Ee.typingSupportTypes.indexOf(t))return;const n={conversationType:t,targetId:s,channelId:i},a=this.getTypingMapKey(n);if(!o||0===o.length)return;let r=this.typingMap.get(a);r||(r=K.map(),this.typingMap.set(a,r)),o.forEach(e=>{r.set(e.userId,e),this.#f(a,e.userId)})})};#f(e,t){const s=this.#I(e,t),i=this.#p.get(s);i&&clearTimeout(i);const o=setTimeout(()=>{B(()=>{const i=this.typingMap.get(e);i?.has(t)&&(i.delete(t),0===i.size&&this.typingMap.delete(e)),this.#p.delete(s)})},this.#E);this.#p.set(s,o)}#T=e=>{e&&e.messages&&0!==e.messages.length&&e.messages.forEach(e=>{const{conversationType:t,targetId:s,channelId:i}=e;if(-1===Ee.typingSupportTypes.indexOf(t))return;const o=`${t};;;${s};;;${i||""}`,n=this.typingMap.get(o);n&&(Array.from(n.keys()).forEach(e=>{const t=this.#I(o,e),s=this.#p.get(t);s&&clearTimeout(s),this.#p.delete(t)}),this.typingMap.delete(o))})};releaseTypingThrottle(e){const t=this.getTypingMapKey(e);this.#S.delete(t)}getTypingMapKey(e){const{conversationType:t,targetId:s,channelId:i=""}=e;return`${t};;;${s};;;${i}`}#I(e,t){return`${e};;;${t}`}}class me{#O;#C=null;#R=()=>{};#y=()=>{};#M=()=>{};#N=null;#v=!1;#A=null;#U=null;#P=!1;#D=0;#G=!1;#w=!1;list=[];#L=new Map;#$=[];#V=new Map;constructor(t,s){this.#O=t,this.#C=s,Q(this),a(r.CONNECTED,this._onConnected.bind(this)),a(r.CONVERSATION,this._onRecvConversationNtf.bind(this)),a(r.PULL_OFFLINE_MESSAGE_FINISHED,this._onPullOfflineMessageFinished.bind(this)),a(r.CONVERSATIONS_SYNCED,this._onConversationsSynced.bind(this)),a(r.MESSAGE_RECEIPT_RESPONSE_V5,this._onV5ReceiptResponse.bind(this)),this.#R=this.#b(this.#O.getUsersCache(),e.PRIVATE),this.#y=this.#b(this.#O.getGroupsCache(),e.GROUP),this.#M=this.#b(this.#O.getSystemsCache(),e.SYSTEM)}#x(){const{isConversationListIncludeUltraGroup:e}=m()||{};this.#G=!!e}#b(e,t){return H(()=>Array.from(e.entries()),s=>{B(()=>{this.list.forEach(s=>{if(s.conversationType===t&&e.has(s.targetId)){const{data:t}=e.get(s.targetId);s.name=t.name||"",s.portraitUri=t.portraitUri||"",this.#L.set(s.key,s)}})})},{fireImmediately:!1,equals:z.structural})}getCachedConversationList(){return this.list.slice()}getOpenedConversation(){return this.#N}destroy(){S(r.CONNECTED,this._onConnected),S(r.CONVERSATION,this._onRecvConversationNtf),S(r.PULL_OFFLINE_MESSAGE_FINISHED,this._onPullOfflineMessageFinished),S(r.CONVERSATIONS_SYNCED,this._onConversationsSynced),S(r.MESSAGE_RECEIPT_RESPONSE_V5,this._onV5ReceiptResponse),this.#R(),this.#y(),this.#M(),this.clearMemoryData()}clearMemoryData(){this.#A&&(clearTimeout(this.#A),this.#A=null),this.#U&&(clearTimeout(this.#U),this.#U=null),this.#$.length=0,this.#v=!1,this.#P=!1,this.#N=null,this.#D=0,this.list.length=0,this.#w=!1,this.#L.clear(),this.#C?.info(ne.S_RECEIVE_DISCONNECT_NOTIFICATION_O,"clear memory data")}_onRecvConversationNtf(e){this.#$.push(...e.conversationList),this._handleQueue()}_onPullOfflineMessageFinished(){this.#A&&(clearTimeout(this.#A),this.#A=null),this.#U&&(clearTimeout(this.#U),this.#U=null),(!this.#P&&!this.#G||this.#w&&!this.#P)&&this._getMoreRemoteConversation(!1),this.#P=!0}_handleQueueDelay(){this.#U||(this.#U=setTimeout(()=>{this.#U=null,this._handleQueue()},20))}_onConnected(){this.#D+=1,this.#x(),this.#v||this.#G||this._getMoreRemoteConversation(!0)}_onConversationsSynced(){this.#w=!0,this.#v||this._getMoreRemoteConversation(!1)}_onV5ReceiptResponse(e){try{if(!e||!Array.isArray(e))return;e.forEach(e=>{const t=e?.identifier||{},s=`${t.conversationType}|${t.targetId}|${t.channelId||""}|${e?.messageUId}`;this.#V.set(s,e);const i=Y({conversationType:t.conversationType,targetId:t.targetId,channelId:t.channelId}),o=this.#L.get(i);o&&o.latestMessage&&o.latestMessage.messageUId===e?.messageUId&&this.updateCacheConversation(i,{readReceiptInfo:e})})}catch(e){this.#C?.warn(ne.S_GET_CONVERSATION_E,`onV5ReceiptResponse error: ${e}`)}}_buildIdentifiersForLatest(t){const s=[];return t.forEach(t=>{const i=t.latestMessage;t.conversationType===e.PRIVATE&&i?.messageDirection===F.SEND&&i?.messageUId&&s.push({identifier:{conversationType:t.conversationType,targetId:t.targetId,channelId:t.channelId},messageUId:i.messageUId})}),s}async _fetchLatestReadReceiptInfoV5(t){const s=this._buildIdentifiersForLatest(t);if(!s.length)return;const i=[];for(let e=0;e<s.length;e+=100)i.push(s.slice(e,e+100));try{(await Promise.all(i.map(e=>T(e)))).forEach(e=>{(e?.data||[]).forEach(e=>{const t=e?.identifier||{},s=`${t.conversationType}|${t.targetId}|${t.channelId||""}|${e.messageUId}`;this.#V.set(s,e)})}),this.list.forEach(t=>{if(t.conversationType!==e.PRIVATE)return;const s=t.latestMessage;if(!s?.messageUId)return;const i=`${t.conversationType}|${t.targetId}|${t.channelId||""}|${s.messageUId}`,o=this.#V.get(i);o&&this.updateCacheConversation(t.key,{readReceiptInfo:o})})}catch(e){this.#C?.warn(ne.S_GET_CONVERSATION_E,`getMessageReadReceiptInfoV5ByIdentifiers error: ${e}`)}}async _getMoreRemoteConversation(e=!1,t=0){const s=0===t?20:200;this.#C?.info(ne.S_GET_CONVERSATION_T,`get conversation list: count = ${s}, startTime = ${t}`);const{code:i,data:o}=await f({count:s,startTime:t});if(this.#C?.info(ne.S_GET_CONVERSATION_R,`get conversation list: code = ${i}, data.length = ${o?.length}`),e&&this.#P)return;if(i!==h.SUCCESS&&!e)return this.#C?.error(ne.S_GET_CONVERSATION_E,`get conversation list failed: code = ${i}, count = ${s}, startTime = ${t}`),void(this.#A=setTimeout(()=>this._getMoreRemoteConversation(e,t),3e3));this._fetchLatestReadReceiptInfoV5(o||[]);const n=o||[];if(0===n.length||e)return void this._onGetRemoteConversationListDone(e);const a=0===t&&!e;a&&(this.list.length=0);const r=this._parseConversationList(n);let c=t;if(c=this._handleNextRequestTimestamp(c,r),e||a){const e=r.filter(e=>!this.list.some(t=>t.key===e.key));this.list.push(...e)}e||n.length<s?this._onGetRemoteConversationListDone(e):this.#A=setTimeout(()=>this._getMoreRemoteConversation(!1,c),300)}_handleNextRequestTimestamp(e,t){return this._updatePositionToConversationList(t,!1),t.forEach(t=>{t.updateTime&&(e=0===e?t.updateTime:Math.min(t.updateTime,e))}),e}_updatePositionToConversationList(e,t=!0){const s=[...this.list];e.forEach(e=>{let i=s.findIndex(t=>X(t,e));if(i>-1){if(!t)return{origin:i,current:i};s.splice(i,1)}const{isTop:o,updateTime:n}=e;let a=s.findIndex(e=>o?!e.isTop||n>e.updateTime:!e.isTop&&n>e.updateTime);-1===a&&(a=s.length),s.splice(a,0,e)}),this.list=s}_onGetRemoteConversationListDone(e){e||(this.#v=!0),this._handleQueue()}_handleQueue(){if(0===this.#$.length)return;if(this.list.length>=20&&!this.#v)return;const e=new Set,t=new Set,s=new Set,i=Number.MAX_SAFE_INTEGER,o=Date.now();if(this._handleQueueNotify(i=>{const{changeType:o,conversation:n}=i;1===o?(s.add(n),e.add(n)):2===o&&(t.add(n),e.add(n))},e,i,o),t.size&&this._recalculatePosition(t),s.size){const e=[...s].filter(e=>!t.has(e));e.length&&e.forEach(e=>{this.list.indexOf(e)>-1&&this.list.splice(this.list.indexOf(e),1,e)})}this._handleQueueDelay()}_recalculatePosition(e){const t=[...e].sort((e,t)=>e.updateTime-t.updateTime);this._updatePositionToConversationList(t)}_handleQueueNotify(e,t,s,i){if(!this.#v){let o=0;for(;o<this.#$.length&&Date.now()-i<20&&t.size<s;){const t=this.#$[o];if(t.updatedItems?.latestMessage){if(!t.updatedItems.latestMessage.val.isOffLineMessage)break;this.#$.splice(o,1),e(this._handleConversationNtf(t))}else o+=1}return}for(;this.#$.length&&Date.now()-i<20&&t.size<s;){const t=this.#$.shift();this.#D<=1&&t.updatedItems?.latestMessage?.val.isOffLineMessage||e(this._handleConversationNtf(t))}}_handleConversationNtf(t){const{conversation:s,updatedItems:i}=t,o=Y(s);let n=this.#L.get(o);return n&&i?this._handleUpdatedItems(n,i,s):!n&&i?.latestMessage?(s.conversationType===e.PRIVATE?n=this._transPriConversation(s):s.conversationType===e.GROUP?n=this._transGroupConversation(s):s.conversationType===e.SYSTEM&&(n=this._transSystemConversation(s)),n&&this.#L.set(n.key,n),{changeType:2,conversation:n}):{changeType:0}}_handleUpdatedItems(e,t,s){let i=0;t.isTop&&(e.isTop=t.isTop.val,i=Math.max(2,i)),t.notificationLevel&&(e.notificationLevel=t.notificationLevel.val,i=Math.max(1,i)),t.latestMessage?.val&&(this._paddingData(e,s),e.readReceiptInfo=void 0,i=Math.max(2,i));try{const t=`${e.conversationType}|${e.targetId}|${e.channelId||""}|${e.latestMessage?.messageUId||""}`,s=this.#V.get(t);s&&(e.readReceiptInfo=s,i=Math.max(1,i))}catch(e){}return{changeType:i,conversation:e}}getMoreConversationList(e,t){let s=e?this.list.findIndex(t=>X(t,e)):-1;-1===s?s=0:s+=1;const i=s+(t||20),o=this.list.slice(s,i),n=this.list.length>i||!this.#v;return this.#C?.info(ne.K_NOTIFY_GET_CONVERSATIONS_O,`get more conversation, conversation: ${e?.key}, count: ${t}, list: ${JSON.stringify(o.length)}`),{hasMore:n,code:h.SUCCESS,list:o,isFirstScreen:!e}}openConversation(t){if(t){const s=this.#F(t);return this.#N=s,this.#C?.info(ne.K_OPEN_CONVERSATION_O,`open conversation, key: ${s.key}`),void(t.conversationType===e.GROUP&&this.#O.groupMembersCache.initGroupMembers(t.targetId))}this.#C?.info(ne.K_OPEN_CONVERSATION_O,`close conversation, key: ${this.#N?.key}`),this.#N=null}async removeConversation(e){const t=this.list.findIndex(t=>t.key===e);if(t>-1){const[s]=this.list.splice(t,1);return this.#L.delete(e),void this.#C?.info(ne.S_REMOVE_CONVERSATION_O,`remove conversation: ${s}`)}this.#C?.warn(ne.S_REMOVE_CONVERSATION_O,`remove conversation failed: ${e} not found`)}_parseConversationList(t){const s=[];return t.forEach(t=>{const{conversationType:i,targetId:o}=t;switch(i){case e.PRIVATE:s.push(this._transPriConversation(t));break;case e.GROUP:s.push(this._transGroupConversation(t));break;case e.SYSTEM:s.push(this._transSystemConversation(t));break;default:this.#C?.warn(ne.S_PARSE_CONVERSATION_E,`unknown conversation type: ${i}, targetId: ${o}`)}}),s}_paddingData(e,t){e.unreadCount=t.unreadMessageCount||0,e.isTop=!!t.isTop,e.latestMessage=t.latestMessage,e.updateTime=t.operationTime||t.latestMessage?.sentTime||0,t.notificationLevel&&(e.notificationLevel=t.notificationLevel)}_transPriConversation(e){const t=this.#O?.getUserProfile(e.targetId),s=this.#F(e);return t&&(s.name=t.name,s.nickName=t.remark||"",s.portraitUri=t.portraitUri||""),this._paddingData(s,e),s}_transSystemConversation(e){const t=this.#O?.getSystemProfile(e.targetId),s=this.#F(e);return t&&(s.name=t.name,s.portraitUri=t.portraitUri||""),this._paddingData(s,e),s}_transGroupConversation(e){const t=this.#O?.getGroupProfile(e.targetId),s=this.#F(e);return t&&(s.name=t.name,s.nickName=t.remark||"",s.portraitUri=t.portraitUri||""),this._paddingData(s,e),s}count=0;#F(e){const t=Y(e);if(this.#L.has(t))return this.#L.get(t);this.count++;const s={key:t,targetId:e.targetId,conversationType:e.conversationType,channelId:e.channelId||"",name:"",nickName:"",portraitUri:"",draft:"",latestMessage:null,isTop:!1,notificationLevel:I.ALL_MESSAGE,unreadCount:0,updateTime:0,memberCount:0};return this.#L.set(t,s),s}#k(t){let s;switch(t.conversationType){case e.PRIVATE:s=this.#O?.getUserProfile(t.targetId);break;case e.GROUP:s=this.#O?.getGroupProfile(t.targetId);break;case e.SYSTEM:s=this.#O?.getSystemProfile(t.targetId)}return s}createCachedConversation(t){const s=this.#k(t),i=this.#F(t);return-1===this.list.findIndex(e=>e.key===i.key)&&(s&&(i.name=s.name||"",i.portraitUri=s.portraitUri||"",t.conversationType!==e.SYSTEM&&(i.nickName=s.remark||"")),i.updateTime=Date.now(),this.list.unshift(i),this._recalculatePosition(new Set([i]))),i}updateCacheConversation(e,t){if(!this.#P)return;const s=this.list.findIndex(t=>t.key===e);if(s>-1)return Object.keys(t).forEach(e=>{const i=e;this.list[s][i]=t[e]}),this.#L.set(e,this.list[s]),void 0===t.isTop&&void 0===t.latestMessage||this._recalculatePosition(new Set([this.list[s]])),void this.#C?.info(ne.S_UPDATE_CONVERSATION_O,`update conversation: ${e}`);this.#C?.warn(ne.S_UPDATE_CONVERSATION_O,`update conversation failed: ${e} not found`)}async clearUnreadCount(e){const t=this.list.find(t=>t.key===e);if(t){const e={conversationType:t.conversationType,targetId:t.targetId,channelId:t.channelId};await g(e),await O(e,(new Date).getTime())}}}class Te{_kitStore;openedConversation=null;conversations=[];#q=null;#C=null;constructor(e,t){this._kitStore=e,this.#C=t,Q(this),this.#Q(e)}async#Q(e){this.#q=new me(e.appData,this.#C),this.#K(),H(()=>this.#q?.list,e=>{e&&(this.conversations=e?.slice())})}#K(){const e=this.#q?.getCachedConversationList()||[];B(()=>{this.conversations=e})}getConversations(e=null,t=10){return this.#q?.getMoreConversationList(e,t)}openConversation(e){!e&&this.openedConversation&&this._kitStore.messageStore.clearExcessMessage(this.openedConversation?.key),this.#q?.openConversation(e),B(()=>{this.openedConversation=e})}createCachedConversation(e){this.#C?.info(ne.K_CREATE_CACHED_CONVERSATION_O,`create cached conversation: ${JSON.stringify(e)}`);const t=this.#q?.createCachedConversation(e);return B(()=>{this.conversations.find(e=>e.key===t.key)||this.conversations.push(t)}),t}removeConversation(e){this.#C?.info(ne.K_REMOVE_CONVERSATION_O,`remove conversation: ${e}`),this.#q?.removeConversation(e),B(()=>{this.conversations=this.conversations.filter(t=>t.key!==e),this.#C?.info(ne.K_REMOVE_CONVERSATION_O,`remove conversation: ${e}, current conversations length: ${this.conversations.length}`)})}updateCacheConversation(e,t){this.#q?.updateCacheConversation(e,t)}getTotalUnreadCount(){return(this.#q?.getCachedConversationList()||[]).reduce((e,t)=>e+t.unreadCount,0)}async clearUnreadCount(e){await(this.#q?.clearUnreadCount(e))}clearMemoryData(){this.#q?.clearMemoryData()}destroy(){this.#q?.destroy()}}class fe{_logger;cache=K.map();converting=K.set();error=K.set();#B=new Map;static MAX_CACHE_SIZE=200;static REQUEST_TIMEOUT=3e4;constructor(e){this._logger=e,Q(this),a(r.SPEECH_TO_TEXT_RESPONSE,this.#H)}getSTTText(e){return this.cache.get(e)}isConverting(e){return this.converting.has(e)}hasError(e){return this.error.has(e)}async requestForMessage(e){const{messageUId:t}=e;if(this.cache.has(t))return h.SUCCESS;if(this.converting.has(t))return h.SUCCESS;this.error.delete(t),this.converting.add(t);const s={messageType:n.HQ_VOICE,remoteUrl:e.content.remoteUrl,duration:e.content.duration,sampleRate:e.content.sampleRate,numberOfChannels:e.content.numberOfChannels};try{this._logger?.info(ne.S_STT_REQUEST_T,`request: ${t}`);const{code:e,msg:i}=await C(t,s);if(this._logger?.info(ne.S_STT_REQUEST_R,`request: ${t}`),e===h.SUCCESS){const e=setTimeout(()=>{this.#B.delete(t),this.converting.has(t)&&(this.converting.delete(t),this.error.add(t),this._logger?.warn(ne.S_STT_TIMEOUT_E,`speech-to-text timeout: ${t}`))},fe.REQUEST_TIMEOUT);this.#B.set(t,e)}else this.converting.delete(t),this.error.add(t),this._logger?.warn(ne.S_STT_REQUEST_E,`request failed: code=${e}, uid=${t}, msg=${i}`);return e}catch(e){return this.converting.delete(t),this.error.add(t),this._logger?.warn(ne.S_STT_REQUEST_E,`request exception: ${e}`),-1}}#H=e=>{console.log("response",e);try{const{code:t,messageUId:s,sttInfo:i}=e||{};this._logger?.info(ne.S_STT_RESPONSE_R,`response: ${s}`);const o=this.#B.get(s);if(o&&(clearTimeout(o),this.#B.delete(s)),t===h.SUCCESS){for(this.cache.set(s,i.text);this.cache.size>fe.MAX_CACHE_SIZE;){const e=this.cache.keys().next().value||"";this.cache.delete(e)}this.error.delete(s),this.converting.delete(s),this._logger?.info?.(ne.S_STT_RESPONSE_O,`success: ${s}`)}else this.converting.delete(s),this.error.add(s),this._logger?.warn(ne.S_STT_RESPONSE_E,`failed: code=${t}, uid=${s}`)}catch(e){this._logger?.warn(ne.S_STT_RESPONSE_E,`exception: ${e}`)}};clearMemoryData(){this.cache.clear(),this.converting.clear(),this.error.clear(),this.#B.forEach(e=>clearTimeout(e)),this.#B.clear()}destroy(){S(r.SPEECH_TO_TEXT_RESPONSE,this.#H),this.clearMemoryData()}}class Ie{config;constructor(e){this.config={timeout:5e3,...e}}async getUserProfile(e){return this.withTimeout(this.fetchUser(e))}async getGroupProfile(e){return this.withTimeout(this.fetchGroup(e))}async getSystemProfile(e){return this.withTimeout(this.fetchSystem(e))}async getGroupMembers(e){return this.withTimeout(this.fetchGroupMembers(e))}async withTimeout(e){return Promise.race([e,new Promise((e,t)=>setTimeout(()=>t("Request timeout"),this.config.timeout))])}}class Oe extends Ie{_hooks;constructor(e){super({timeout:8e3}),this._hooks=e}async fetchUser(e){if(!this._hooks.reqUserProfiles)throw new Error("reqUserProfiles hook not implemented");return this._hooks.reqUserProfiles(e)}async fetchGroup(e){if(!this._hooks.reqGroupProfiles)throw new Error("reqGroupProfiles hook not implemented");return this._hooks.reqGroupProfiles(e)}async fetchSystem(e){if(!this._hooks.reqSystemProfiles)throw new Error("reqSystemProfiles hook not implemented");return this._hooks.reqSystemProfiles(e)}fetchGroupMembers(e){if(!this._hooks.reqGroupMembers)throw new Error("reqGroupMembers hook not implemented");return this._hooks.reqGroupMembers(e)}}class Ce{logger;dataSource;#z=new oe(20);#Y=new Map;constructor(e,t){this.logger=e,this.dataSource=t,Q(this)}async initGroupMembers(e){if(this.#z.get(e))return;if(this.#Y.get(e))return;const t=this.dataSource.getGroupMembers(e);this.#Y.set(e,t);try{const s=this.logger.createTraceId();this.logger.info(ne.S_GET_GROUP_MEMBERS_HOOK_T,e,s);const i=await t;if(this.#Y.delete(e),!i||!Array.isArray(i))return void this.logger.error(ne.S_GET_GROUP_MEMBERS_HOOK_E,"result must be a Array",s);const o=i.filter((e,t)=>!this.#J(e)||(this.logger.error(ne.S_GET_GROUP_MEMBERS_HOOK_E,`result[${t}] is invalid, member: ${JSON.stringify(e)}`,s),!1)).map(this.#X);this.logger.info(ne.S_GET_GROUP_MEMBERS_HOOK_R,`groupId: ${e}, memberCount: ${i.length}`,s),this.#z.set(e,o,!1,0)}catch(t){this.#Y.delete(e),this.logger.error(ne.S_GET_GROUP_MEMBERS_HOOK_E,e,t)}}getGroupMembers(e){return this.#z.get(e)||[]}getGroupMember(e,t){const s=this.#z.get(e),i=s?.find(e=>e.user.id===t);return i?{...i}:void 0}getGroupMemberMap(e){const t=this.#z.get(e),s=new Map;return t?.forEach(e=>{s.set(e.user.id,{...e})}),s}#J(e){return"object"!=typeof e||"string"!=typeof e.groupNickname||"object"!=typeof e.user||!e.user.id||"string"!=typeof e.user.id||"string"!=typeof e.user.nickname}#X(e){const{groupNickname:t,user:s}=e;return{user:{...s},groupNickname:t}}clearMemoryData(){this.#z.clear(),this.#Y.clear()}}class Re{logger;#W;#j=K.map();#Z=K.map();#ee=K.map();groupMembersCache;#te={ids:[]};#se={ids:[],timer:void 0};#ie={ids:[],timer:void 0};constructor(e,t={}){this.logger=e,this.#W=new Oe(t),this.groupMembersCache=new Ce(e,this.#W),Q(this)}getUserProfile(e){return this.#oe({id:e,cache:this.#j,queue:this.#te,batchFetch:e=>this.#W.getUserProfile(e)})}getGroupProfile(e){return this.#oe({id:e,cache:this.#Z,queue:this.#se,batchFetch:e=>this.#W.getGroupProfile(e)})}getSystemProfile(e){return this.#oe({id:e,cache:this.#ee,queue:this.#ie,batchFetch:e=>this.#W.getSystemProfile(e)})}getUserInfo(e){return this.#j.get(e)?.data}getUsersCache(){return this.#j}getGroupsCache(){return this.#Z}getSystemsCache(){return this.#ee}updateUserProfile(e,t){t?this.#ne(this.#j,[e],[t]):(this.logger.warn(ne.K_USER_PROFILE_NOT_FOUND_O,`user id ${e} not found, request remote data`),this.#W.getUserProfile([e]))}updateGroupProfile(e,t){t?this.#ne(this.#Z,[e],[t]):(this.logger.warn(ne.K_GROUP_PROFILE_NOT_FOUND_O,`group id ${e} not found, request remote data`),this.#W.getGroupProfile([e]))}updateSystemProfile(e,t){t?this.#ne(this.#ee,[e],[t]):(this.logger.warn(ne.K_SYSTEM_PROFILE_NOT_FOUND_O,`system id ${e} not found, request remote data`),this.#W.getSystemProfile([e]))}async getProfileSync(e,t){if(t===k.PRIVATE){return(await this.#W.getUserProfile([e]))[0]}if(t===k.GROUP){return(await this.#W.getGroupProfile([e]))[0]}return(await this.#W.getSystemProfile([e]))[0]}#oe(e){const t=Date.now(),s=e.cache.get(e.id);if(s)return s.expires>t||s.pending||this.#ae({id:e.id,cache:e.cache,queue:e.queue,batchFetch:e.batchFetch}),s.data;this.#ae({id:e.id,cache:e.cache,queue:e.queue,batchFetch:e.batchFetch})}#ae(e){let t=e.cache.get(e.id);t&&e.cache.set(e.id,{...t,pending:!0}),e.queue.ids=[...new Set([...e.queue.ids,e.id])],e.queue.timer&&clearTimeout(e.queue.timer),e.queue.timer=setTimeout(()=>this.#re(e.cache,e.queue,e.batchFetch),200)}async#re(e,t,s){const i=[...t.ids];if(t.ids=[],t.timer=void 0,0!==i.length)try{const t=await s(i);B(()=>this.#ne(e,i,t))}catch(t){B(()=>this.#ce(e,i))}}#ne(e,t,s){const i=Date.now();s.forEach(t=>{const{id:s}=t;s&&(e.set(s,{data:t,expires:i+6e5,pending:!1}),this.logger.info(ne.S_UPDATE_CACHE_O,`update cache ${s} success, data: ${JSON.stringify(t)}`))})}#ce(e,t){t.forEach(t=>{const s=e.get(t);s&&e.set(t,{...s,pending:!1})})}clearMemoryData(){[this.#te,this.#se,this.#ie].forEach(e=>{e.timer&&clearTimeout(e.timer)}),this.#j.clear(),this.#Z.clear(),this.#ee.clear(),this.groupMembersCache.clearMemoryData()}}class ye{rootStore;_logger;constructor(e,t){this.rootStore=e,this._logger=t}_monitorIds=[];init(){const e=Object.getOwnPropertyNames(Object.getPrototypeOf(this));for(const t of e)t.startsWith("monitor")&&"function"==typeof this[t]&&this._monitorIds.push(this[t]())}destroy(){this._monitorIds.forEach(e=>{R(e)})}monitorSendMessage(){return y(s,async(e,t)=>{const{code:s,data:i}=await t;if(i?.isPersited){const t={...i,sentStatus:s===h.SUCCESS?u.SENT:u.FAILED,...e[2]};this.rootStore.messageStore?.updateCatchedMessage(t),this.rootStore.conversationStore?.updateCacheConversation(Y(e[0]),{latestMessage:t})}},e=>{const[,,t]=e;if(t){const{messageId:s}=t,i=t?.onSendBefore;t.onSendBefore=t=>{this._logger.info(ne.S_ON_SEND_BEFORE_S,`${s}, isPersited: ${t.isPersited}`),t.isPersited&&(s?this.rootStore.messageStore?.updateCatchedMessage(t):this.rootStore.messageStore?.insertMessage(t),this.rootStore.conversationStore?.updateCacheConversation(Y(e[0]),{latestMessage:t,draft:"",readReceiptInfo:void 0})),i?.(t)}}return e})}monitorClearMessagesUnreadStatus(){return y(g,async(e,t)=>{this._logger.info(ne.S_CLEAR_MESSAGES_UNREAD_STATUS_T,JSON.stringify(e));const s=await t;this._logger.info(ne.S_CLEAR_MESSAGES_UNREAD_STATUS_R,JSON.stringify(s));const i=e[0],o=Y(i);this.rootStore.conversationStore?.updateCacheConversation(o,{unreadCount:0})})}monitorRemoveConversation(){return y(M,async(e,t)=>{this._logger.info(ne.S_REMOVE_CONVERSATION_T,JSON.stringify(e));const s=await t;this._logger.info(ne.S_REMOVE_CONVERSATION_R,JSON.stringify(s));const i=e[0],o=Y(i);this.rootStore.conversationStore?.removeConversation(o)})}monitorSetConversationNotificationLevel(){return y(N,async(e,t)=>{this._logger.info(ne.S_SET_CONVERSATION_NOTIFICATION_LEVEL_T,JSON.stringify(e));const s=await t;this._logger.info(ne.S_SET_CONVERSATION_NOTIFICATION_LEVEL_R,JSON.stringify(s));const i=e[0],o=e[1],n=Y(i);this.rootStore.conversationStore?.updateCacheConversation(n,{notificationLevel:o})})}monitorSetConversationToTop(){return y(v,async(e,t)=>{this._logger.info(ne.S_SET_CONVERSATION_TO_TOP_T,JSON.stringify(e));const s=await t;this._logger.info(ne.S_SET_CONVERSATION_TO_TOP_R,JSON.stringify(s));const i=e[0],o=e[1],n=Y(i);this.rootStore.conversationStore?.updateCacheConversation(n,{isTop:o})})}monitorRecallMessage(){return y(_,async(e,t)=>{const{code:s,data:i}=await t;if(s===h.SUCCESS&&i){const[t,s]=e;this._logger.info(ne.S_RECALL_MESSAGE_T,JSON.stringify(e)),this.rootStore.messageStore?.removeCatchedMessage({...t,messageUId:s.messageUId,channelId:t.channelId||""}),this._logger.info(ne.S_RECALL_MESSAGE_R,JSON.stringify(i)),this.rootStore.messageStore?.insertMessage(i,!1,!0)}})}monitorDisconnect(){return y(A,async(e,t)=>{this.rootStore.conversationStore?.clearMemoryData(),this.rootStore.messageStore?.clearMemoryData(),this.rootStore.appData?.clearMemoryData()})}}const Me="1.2.1";class Ne{_context;_logger;_option;messageStore;conversationStore;typingStore;speechToTextStore;appData;currentUserId="";connectStatus=K.box(q.DISCONNECTED);#he=K.box(!0);get enableReadV5(){return this.#he.get()}constructor(e,t,s){this._context=e,this._logger=t,this._option=s,this.appData=new Re(this._logger,this._option.hooks),a(r.CONNECTED,this._onConnected),a(r.DISCONNECT,this._onDisconnected),a(r.SUSPEND,this._onSuspend),a(r.CONNECTING,this._onConnecting),new ye(this,this._logger).init(),this.messageStore=new pe(this._logger,this,this._context),this.conversationStore=new Te(this,this._logger),this.typingStore=new Ee,this