UNPKG

@rongcloud/imkit-store

Version:

RongCloud IM UIKit Store

1 lines 57.7 kB
"use strict";Object.defineProperty(exports,"__esModule",{value:!0});var e=require("@rongcloud/imlib-next"),t=require("@rongcloud/engine"),s=require("mobx");const o=e=>`[${e.targetId}][${e.conversationType}][${e.channelId||""}]`,n=e=>{const[t,s,o]=e.split("][");return{targetId:t.replace("[",""),conversationType:~~s,channelId:o.replace("]","")}},r=(e,t)=>e.targetId===t.targetId&&e.conversationType===t.conversationType&&(e.channelId===t.channelId||!t.channelId);e.ConversationType.PRIVATE,e.ConversationType.GROUP,e.ConversationType.SYSTEM;const i=(e,t)=>{const s=e.messageUId&&t.messageUId?"messageUId":"messageId";return e[s]===t[s]},a=e=>JSON.parse(JSON.stringify(e)),c=(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,o)=>{s.set(o,c(e,t))});else if(e instanceof Set)s=new Set,t.set(e,s),e.forEach(e=>{s.add(c(e,t))});else if(Array.isArray(e)){s=[],t.set(e,s);for(let o=0;o<e.length;o++)s[o]=c(e[o],t)}else{s=Object.create(Object.getPrototypeOf(e)),t.set(e,s);for(const o in e)Object.prototype.hasOwnProperty.call(e,o)&&(s[o]=c(e[o],t))}return s},h=()=>"undefined"!=typeof uni&&"function"==typeof uni.getSystemInfoSync;var d;!function(e){e.android="android",e.ios="ios"}(d||(d={}));const _=(t,s)=>{const o=uni.$RongKitStore.enableReadV5&&[e.ConversationType.PRIVATE,e.ConversationType.GROUP].includes(t),n=t===e.ConversationType.GROUP&&s&&s.directionalUserIdList&&s.directionalUserIdList.length>0;return!(!o||n)};class l{queue=[];maxSize;constructor(e){this.maxSize=e,s.makeAutoObservable(this)}push(e,t){this.queue.push(c(e)),t&&this._trimExcess(!0)}pop(){return this.queue.pop()}unshift(e,t){this.queue.unshift(...c(e)),t&&this._trimExcess(!1)}shift(){return this.queue.shift()}clear(){this.queue=[]}set(e,t=!0){this.queue=c(e),t&&this._trimExcess()}get(){return c(this.queue)}resetExcess(){this._trimExcess()}splice(e,t,...s){this.queue.splice(e,t,...c(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 u{maxKeySize;map=new Map;activeMap=new Map;constructor(e=30){this.maxKeySize=e,s.makeAutoObservable(this,{map:s.observable,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,o=30){const n=new l(o);n.set(t,s),this.map.set(e,n),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 g,S,p;!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"}(g||(g={})),function(e){e[e.TASK_CANCEL=39001]="TASK_CANCEL"}(S||(S={}));class E{_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(g.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(g.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(g.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:o}=await t;e.code=s,e.result=o,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 m extends E{_logger;_tag="MessageSendQueue";constructor(e){super(10,5,e),this._logger=e}async _handle(s){const{conversation:o,message:n,options:r}=s,{conversationType:i,targetId:c,channelId:h}=o,d=this._logger.createTraceId();this._logger.info(g.S_SEND_MSG_T,`type: ${n.messageType}, conversationType: ${i}, targetId: ${c}, channelId: ${h||""}`,d);const{isCounted:l,isPersited:u,content:S,messageType:p}=n,E=new e.BaseMessage(p,S,u,l);if(t.isObject(E.content))try{E.content=a(E.content)}catch(e){this._logger.warn(g.S_SEND_MSG_E,e.message)}const m={...r,needReceipt:_(i,r||{})},{code:T,data:C}=await e.sendMessage(o,E,{...m,onSendBefore(e){n.messageId=e.messageId,r?.onSendBefore?.(e)}});return T!==t.ErrorCode.SUCCESS?this._logger.warn(g.S_SEND_MSG_R,`code: ${T}`,d):this._logger.info(g.S_SEND_MSG_R,"success",d),{code:T,data:C}}}!function(e){e.ALIYUN="aliyun",e.S3="s3",e.STC="stc",e.MINIO="minio",e.QINIU="qiniu",e.BAIDU="baidu",e.RCX="rcx"}(p||(p={}));class T{_url;_getFileToken;_serverType=0;constructor(e,t,s){this._url=e,this._getFileToken=t,this._serverType=s}async safeExecute(e,s,o,n=t.ErrorCode.UPLOAD_FAIL){try{return await e.execute(s)}catch(e){return console.error(`${o} request.execute error`,e),{code:n,msg:e instanceof Error?e.message:String(e)}}}upload(e,s){return e.fileSize>t.MAX_UPLOAD_FILE_SIZE?Promise.resolve({code:t.ErrorCode.UPLOAD_FAIL,msg:"the file size is over 5GB!"}):this.commonUpload(e,s)}}function C(e){switch(e){case t.FileType.IMAGE:return"image/jpeg";case t.FileType.AUDIO:return"audio/amr";case t.FileType.VIDEO:return"video/mpeg4";case t.FileType.FILE:return"application/octet-stream";case t.FileType.SIGHT:return"video/mpeg4";case t.FileType.COMBINE_HTML:return"text/html";default:return"multipart/form-data"}}const f={[p.QINIU]:class extends T{async commonUpload(e,s){const{fileType:o}=e;try{const{code:e,data:n,msg:r}=await this._getFileToken(o,void 0,void 0,void 0);if(e!==t.ErrorCode.SUCCESS)return{code:e,msg:r};const i=n,a={token:i.token,key:i.fileName},c={url:t.fixUrlProtocol(this._url),headers:{},body:a,method:"POST"},h=await this.safeExecute(s,c,p.QINIU);return 200===h.code||204===h.code?{code:t.ErrorCode.SUCCESS,data:{uniqueName:i.fileName,uploadMethod:t.UploadMethod.QINIU}}:{code:t.ErrorCode.UPLOAD_FAIL,msg:h.msg}}catch(e){return console.error("QINIU prepareUploadData error",e),{code:e}}}},[p.ALIYUN]:class extends T{async commonUpload(e,s){const{fileType:o}=e;try{const{code:e,data:n,msg:r}=await this._getFileToken(o,void 0,void 0,void 0);if(e!==t.ErrorCode.SUCCESS||!n)return{code:e,msg:r};const i=n,a=t.fixUrlProtocol(`${n.ossBucketName}.${this._url}`),c={url:a,headers:{},body:{token:i.token,OSSAccessKeyId:i.osskeyId,policy:i.ossPolicy,Signature:i.ossSign,success_action_status:"200",key:i.fileName},method:"POST"},h=await this.safeExecute(s,c,p.ALIYUN);return 200===h.code||204===h.code?{code:t.ErrorCode.SUCCESS,data:{uniqueName:i.fileName,uploadMethod:t.UploadMethod.ALI}}:{code:t.ErrorCode.UPLOAD_FAIL,msg:h.msg}}catch(e){return console.error("ALIYUN commonUpload error",e),{code:e}}}},[p.S3]:class extends T{async commonUpload(e,s){const{fileType:o}=e;try{const{code:e,data:n,msg:r}=await this._getFileToken(o,void 0,void 0,void 0);if(e!==t.ErrorCode.SUCCESS||!n)return{code:e,msg:r};const i=n,a=t.fixUrlProtocol(`${i.s3BucketName}.${this._url}`),c={url:a,headers:{},body:{"Content-Type":C(o),"Content-Disposition":o===t.FileType.COMBINE_HTML?"inline":"attachment","x-amz-credential":i.s3Credential,"x-amz-algorithm":i.s3Algorithm,"x-amz-date":i.s3Date,policy:i.s3Policy,"x-amz-signature":i.s3Signature,key:i.fileName},method:"POST"},h=await this.safeExecute(s,c,p.S3);return 200===h.code||204===h.code?{code:t.ErrorCode.SUCCESS,data:{uniqueName:i.fileName,uploadMethod:t.UploadMethod.AWS}}:{code:t.ErrorCode.UPLOAD_FAIL,msg:h.msg}}catch(e){return console.error("S3 commonUpload error",e),{code:e}}}},[p.MINIO]:class extends T{async commonUpload(e,s){const{fileName:o,fileType:n,buffer:r}=e;try{const{code:r,data:i,msg:a}=await this._getFileToken(n,void 0,"PUT",void 0);if(r!==t.ErrorCode.SUCCESS||!i)return{code:r,msg:a};const c=i,h=t.fixUrlProtocol(`${this._url}/${c.minioBucketName}/${c.fileName}`),d=n===t.FileType.COMBINE_HTML?"inline":"attachment",_={url:h,headers:{"Content-Disposition":`${d}; filename=${encodeURIComponent(o||c.fileName)};`,Authorization:c.minioAuthorization,"x-amz-content-sha256":c.minioContentSha256,"x-amz-date":c.minioDate,"Content-Type":C(n)||"text/plain"},body:{},method:"PUT",filePath:e.path},l=await this.safeExecute(s,_,p.MINIO);return 200===l.code||204===l.code?{code:t.ErrorCode.SUCCESS,data:{uniqueName:c.fileName,uploadMethod:t.UploadMethod.MINIO}}:{code:t.ErrorCode.UPLOAD_FAIL,msg:l.msg}}catch(e){return console.error("MINIO commonUpload error",e),{code:e}}}}};async function I(s,o,n){const{serverType:r,customDomain:i,ossConfig:a,uploadServer:c,bosAddr:h}=o;if(!a||0===a.length)return{code:t.ErrorCode.INVALID_PARAMETER_MEDIA_URL,msg:"ossConfig is empty"};const d=function(e,t,s,o,n){if(s)return[{type:p.RCX,url:s,p:"1"}];if(e)return JSON.parse(e).map(e=>{const t={type:p.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 r=[];return o&&r.push({type:p.QINIU,url:o,p:"1"}),n&&r.push({type:p.BAIDU,url:n,p:"2"}),r}(a,0,i,c,h);if(0===d.length)return{code:t.ErrorCode.INVALID_PARAMETER_MEDIA_URL,msg:"uploadUrlList is empty"};const _=[];for(let o=0;o<d.length;o++){const i=d[o];if(!(i.type in f))continue;const a=new f[i.type](i.url,e.getFileToken,r),{code:c,data:h,msg:l}=await a.upload(s,n);try{if(c===t.ErrorCode.RC_FILE_SIZE_EXCEED_LIMIT)return{code:c,msg:"File size exceeds the limit"};if(c===t.ErrorCode.INVALID_PARAMETER_SIZE_NOT_FOUND)return{code:c,msg:"File size not found"};if(n.isAbort())return{code:c,msg:l};if(c===t.ErrorCode.SUCCESS&&h){let{downloadUrl:o,uploadMethod:n,uniqueName:r}=h;if(!o){const i=await e.getFileUrl(s.fileType,r||"",r,void 0,n);i.code===t.ErrorCode.SUCCESS&&i.data&&(o=i.data.downloadUrl)}return o?{code:t.ErrorCode.SUCCESS,data:{downloadUrl:o}}:{code:t.ErrorCode.UPLOAD_FAIL,msg:"Get download url fail"}}_.push({type:i.type,url:i.url,code:c,msg:l})}catch(e){_.push({type:i.type,url:i.url,code:t.ErrorCode.UPLOAD_FAIL,msg:e instanceof Error?e.message:String(e)})}}return{code:t.ErrorCode.UPLOAD_FAIL,data:{downloadUrl:"",msg:`Failed to upload through all channels, msg: ${JSON.stringify(_)}`}}}class y extends E{_logger;constructor(e){super(2,5,e),this._logger=e}_tag="UploadQueue";_handle(e){const{info:t,config:s,request:o}=e;return I(t,s,o)}}class O{_logger;rootStore;_context;#e=new u(10);#t;#s;#o=new Map;#n={[e.MessageType.IMAGE]:"imageUri",[e.MessageType.SIGHT]:"sightUrl",[e.MessageType.HQ_VOICE]:"remoteUrl",[e.MessageType.GIF]:"remoteUrl",[e.MessageType.FILE]:"fileUrl"};#r=new Set;#i=[];constructor(t,o,n){this._logger=t,this.rootStore=o,this._context=n,s.makeAutoObservable(this),e.addEventListener(e.Events.MESSAGES,this.#a.bind(this)),e.addEventListener(e.Events.MESSAGE_RECEIPT_RESPONSE_V5,this.#c),this.#t=new m(this._logger),this.#s=new y(this._logger)}getMessages(t){const s=this.#e.get(t);if(!s||0===s.length)return[];const{conversationType:o}=n(t);switch(o){case e.ConversationType.GROUP:return this.#h(s);case e.ConversationType.SYSTEM:return this.#d(s);default:return this.#_(s)}}getMessageByUid(t,s){if(!t||!s)return;const r=o(t),{conversationType:i}=n(r),a=(this.#e.get(r)||[]).find(e=>e.messageUId===s);if(!a)return;let c;switch(i){case e.ConversationType.GROUP:[c]=this.#h([a]);break;case e.ConversationType.SYSTEM:[c]=this.#d([a]);break;default:[c]=this.#_([a])}return c}#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}))}#_(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}})}#d(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}))}#l=()=>{const e=this._context.getNaviInfo();if(e&&"ossConfig"in e)return e.ossConfig};async getHistoryMsgList(t,o,r,i=20){this._logger.info(g.S_GET_HISTORY_MESSAGE_O,`${t}, ${o}, ${r}, ${i}`);const{code:a,data:c}=await e.getHistoryMessages(n(t),{timestamp:o,count:i});if(a===e.ErrorCode.SUCCESS&&c){const{list:e}=c;s.runInAction(()=>{r?this.#e.getQueue(t)?.unshift(e,!1):this.#e.set(t,e,!0,10)});try{if(this.rootStore.enableReadV5&&e?.length){const s=n(t),o=e.filter(e=>1===e.messageDirection&&!!e.messageUId).map(e=>e.messageUId);this.fetchReadReceiptV5(s,o)}}catch(e){this._logger.warn(g.S_SEND_MSG_E,`fetch V5 after history error: ${e}`)}}return{code:a,data:c}}insertMessage(e,t=!0,s=!0){const n={conversationType:e.conversationType,targetId:e.targetId,channelId:e.channelId},r=o(n);e.messageId&&0!==e.messageId||(e.messageId=(()=>{let e=0;const t=((4294967295&Date.now())>>>0).toString(2),s=Math.floor(255*Math.random()),o=t+e.toString(2).padStart(11,"0")+s.toString(2).padStart(8,"0");return e=2047&++e,parseInt(o,2)})());const a=this.#e.get(r);let c=!1;return a&&(c=a.some(t=>i(t,e))),s&&this._logger.info(g.S_INSERT_MESSAGE_O,`${r}, ${e.messageUId}, ${e.messageId}, isRepeat: ${c}`),c||this.#e.getQueue(r)?.push(e,t),e}updateCatchedMessage(e){const t=o({conversationType:e.conversationType,targetId:e.targetId,channelId:e.channelId});this._logger.info(g.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 n=s.get(),r=n.findIndex(t=>i(t,e));-1!==r&&s.splice(r,1,{...e,sentTime:e.sentTime||n[r].sentTime})}removeCatchedMessage(e){const t=o({conversationType:e.conversationType,targetId:e.targetId,channelId:e.channelId});this._logger.info(g.S_REMOVE_MESSAGE_O,`${t}, ${e.messageUId}, ${e.messageId}`);const s=this.#e.getQueue(t);if(!s)return;const n=s.get().findIndex(t=>i(t,e));-1!==n&&s.splice(n,1)}async recallMessage(t){const{conversationType:s,targetId:o,channelId:n}=t;return this._logger.info(g.S_RECALL_MESSAGE_O,`${s}, ${o}, ${n}, ${t.messageUId}`),e.recallMessage({conversationType:s,targetId:o,channelId:n},{messageUId:t.messageUId,sentTime:t.sentTime})}async sendMessage(e,t,s){return this._logger.info(g.S_SEND_MESSAGE_O,`${e}, ${t.messageType}, ${s?.messageId}`),this.#t.push({conversation:n(e),message:this.#u(n(e),t),options:s})}async sendMediaMessage(t){const{conversationKey:s,message:o,info:r,request:i,sendOptions:a}=t;if(o.messageType!==e.MessageType.IMAGE&&o.messageType!==e.MessageType.SIGHT&&o.messageType!==e.MessageType.HQ_VOICE&&o.messageType!==e.MessageType.GIF&&o.messageType!==e.MessageType.FILE)return{code:e.ErrorCode.INVALID_PARAMETER_MESSAGE_CONTENT,msg:"Invalid message type"};const c=r?.path,h=this.#u(n(s),o,a,c);let d,_,l;if(a?.messageId?(_=a.messageId,h.sentStatus=e.SentStatus.SENDING,this.updateCatchedMessage(h),d=h):(d=this.insertMessage(h,!1,!0),_=d.messageId),!_)return{code:e.ErrorCode.UPLOAD_FAIL,msg:"Insert message failed"};this.#o.set(_,i);try{const t={ossConfig:this.#l()};if(l=await this.#s.push({info:r,request:i,config:t}),l.code===e.ErrorCode.SUCCESS&&l.data){const{data:t}=l,n=this.#n[o.messageType];if(n&&t?.downloadUrl){o.content[n]=t.downloadUrl;const r={...a||{},messageId:_};return o.messageType===e.MessageType.HQ_VOICE&&(r.sampleRate=16e3,r.numberOfChannels=1),await this.sendMessage(s,o,r)}this._logger.warn(g.S_SEND_MSG_E,`Cannot set media URL: propertyName=${n}, hasUrl=${!!t?.downloadUrl}`)}else this._logger.warn(g.S_SEND_MSG_E,`Media upload failed: code=${l.code}, error=${l?.data?.msg}`)}catch(e){this._logger.error(g.S_SEND_MSG_E,`Exception in sendMediaMessage: ${e}`)}finally{this.#o.delete(_)}return d.sentStatus=e.SentStatus.FAILED,this.updateCatchedMessage(d),{code:e.ErrorCode.UPLOAD_FAIL,msg:`Upload failed: ${l?.data?.msg}`,data:d}}async sendV5Receipts(t,s){if(!this.rootStore.enableReadV5)return;const n=Array.from(new Set((s||[]).filter(Boolean)));if(0===n.length)return void this._logger.info(g.S_SENF_V5_RECEIPT_O,`sendV5Receipts ids size is 0, messageUIds: ${JSON.stringify(s)}`);const r=o(t),i=this.#e.get(r)||[],a=new Set(n.filter(e=>{const t=i.find(t=>t.messageUId===e);if(!t)return!1;const s=2===t.messageDirection,o=!this.#r.has(e)&&!0!==t.sendReceipt;return s&&o}));if(0===a.size)return void this._logger.info(g.S_SENF_V5_RECEIPT_O,"sendV5Receipts messageUIds size is 0");const c=Array.from(a);try{this._logger.info(g.S_SENF_V5_RECEIPT_T,`sendV5Receipts: ${JSON.stringify(c)}`);const s=await e.sendReadReceiptResponseV5(t,c);this._logger.info(g.S_SENF_V5_RECEIPT_R,`sendV5Receipts res: ${JSON.stringify(s)}`),c.forEach(e=>this.#r.add(e)),this.#g(t,c)}catch(e){this._logger.warn(g.S_SEND_MSG_E,`sendV5Receipts error: ${e}`)}}async fetchReadReceiptV5(t,s){if(!this.rootStore.enableReadV5)return;const n=(s||[]).filter(Boolean);if(0!==n.length)try{const s=await e.getMessageReadReceiptInfoV5(t,n),r=s?.data||[];if(!Array.isArray(r)||0===r.length)return;const i=o(t),a=this.#e.get(i)||[];r.forEach(e=>{const t=a.find(t=>t.messageUId===e?.messageUId);t&&(t.readReceiptInfo=e,this.updateCatchedMessage(t))})}catch(e){this._logger.warn(g.S_SEND_MSG_E,`fetchReadReceiptV5 error: ${e}`)}}async getReadReceiptUsersV5(t,s,o){const n={read:{list:[],total:0,pageToken:""},unread:{list:[],total:0,pageToken:""}};if(!this.rootStore.enableReadV5||!s)return n;const r=o?.pageCount??100,i="number"!=typeof o?.type||0===o?.type,a="number"!=typeof o?.type||1===o?.type,c=this.rootStore.appData.groupMembersCache.getGroupMemberMap(t.targetId),h=async(o,n)=>{const i={pageToken:n||void 0,pageCount:r,readStatus:o},a=await e.getMessagesReadReceiptUsersByPageV5(t,s,i),h=a?.data||{},d=h.users||[],_="number"==typeof h.totalCount?h.totalCount:0,l=h.pageToken;return{list:d.map(e=>({id:e.userId,name:c.get(e.userId)?.user.nickname||c.get(e.userId)?.groupNickname||e.userId,portraitUri:c.get(e.userId)?.user.portraitUri,timestamp:e.timestamp})),total:_,pageToken:l}},d={...n};if(i){const e=await h(0,o?.pageTokenRead);d.read=e}if(a){const e=await h(1,o?.pageTokenUnread);d.unread=e}return d}forwardMessage(e,t){return this._logger.info(g.S_FORWARD_MESSAGE_O,`${e}, ${t.messageType}, ${t.messageUId}`),this.#t.push({conversation:n(e),message:t})}cancelSendMediaMessage(e){this._logger.info(g.S_CANCEL_SEND_MEDIA_MESSAGE_O,`${e}`);const t=this.#o.get(e);t&&(t.abort(),this.#o.delete(e))}getSelectedMessages(){return this._logger.info(g.S_GET_SELECTED_MESSAGES_O),a(this.#i)}setSelectedMessages(e){this._logger.info(g.S_SET_SELECTED_MESSAGES_O,`${e.length}`),this.#i=e}clearExcessMessage(e){this.#e.resetExcess(e)}#a(t){t.messages.forEach(t=>{const{conversationType:s,targetId:n,channelId:r,isPersited:i}=t,a=o({conversationType:s,targetId:n,channelId:r});switch(t.messageType){case e.MessageType.RECALL_MESSAGE_TYPE:this.removeCatchedMessage({...t,messageUId:t.content.messageUId});break;case"RC:SRSMsg":e.clearMessagesUnreadStatus({conversationType:s,targetId:n,channelId:r})}i&&this.insertMessage(t,a!==this.rootStore.conversationStore?.openedConversation?.key,!1)})}#c=e=>{try{if(!e||!Array.isArray(e))return;e.forEach(e=>{const t=o({conversationType:e?.identifier?.conversationType,targetId:e?.identifier?.targetId,channelId:e?.identifier?.channelId}),s=this.#e.getQueue(t);if(!s)return;const n=s.get(),r=n.findIndex(t=>t.messageUId===e?.messageUId);if(-1!==r){const s={...n[r]};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(g.S_SEND_MSG_E,`onV5ReceiptResponse error: ${e}`)}}})}catch(e){this._logger.warn(g.S_SEND_MSG_E,`onV5ReceiptResponse error: ${e}`)}};#g(e,t){try{if(!t||!t.length)return;const s=o(e),n=this.#e.getQueue(s);if(!n)return;const r=n.get(),i=new Set(t);r.forEach(e=>{if(e.messageUId&&i.has(e.messageUId)){const t={...e};t.sendReceipt=!0,this.updateCatchedMessage(t)}})}catch(e){this._logger.warn(g.S_SEND_MSG_E,`markSendReceiptTrue error: ${e}`)}}#u(t,s,o,n){const{conversationType:r,targetId:i,channelId:a}=t,{isCounted:c,isPersited:h,content:d,messageType:_}=s;return{targetId:i,conversationType:r,messageDirection:1,messageType:_,sentTime:this._context.getServerTime(),isStatusMessage:o?.isStatusMessage,isCounted:c,isPersited:h,content:d,channelId:a||"",senderUserId:this._context.getCurrentId(),receivedTime:0,messageUId:"",sentStatus:e.SentStatus.SENDING,isOffLineMessage:!1,canIncludeExpansion:o?.canIncludeExpansion||!1,receivedStatus:0,isMentioned:o?.isMentioned,expansion:o?.expansion,messageId:o?.messageId,localTmpPath:n}}destroy(){e.removeEventListener(e.Events.MESSAGES,this.#a),this.clearMemoryData()}clearMemoryData(){this.#e.clear(),this.#t.destroy(),this.#s.destroy(),this.#o.clear(),this.#i=[]}}class M{static DISAPPEAR_INTERVAL=6e3;static typingSupportTypes=[e.ConversationType.PRIVATE];typingMap=s.observable.map();#S=new Map;#p=new Map;#E=M.DISAPPEAR_INTERVAL;constructor(){s.makeAutoObservable(this),e.addEventListener(e.Events.TYPING_STATUS,this.#m),e.addEventListener(e.Events.MESSAGES,this.#T)}dispose(){e.removeEventListener(e.Events.TYPING_STATUS,this.#m),e.removeEventListener(e.Events.MESSAGES,this.#T),this.#p.forEach(e=>clearTimeout(e)),this.#p.clear(),this.typingMap.clear(),this.#S.clear()}async sendTyping(t,s){if(-1===M.typingSupportTypes.indexOf(t.conversationType))return;const o=this.getTypingMapKey(t);this.#S.has(o)||(this.#S.set(o,Date.now()),setTimeout(()=>this.#S.delete(o),this.#E),await e.sendTypingStatusMessage(t,s))}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:o,channelId:n,list:r}=e;if(-1===M.typingSupportTypes.indexOf(t))return;const i={conversationType:t,targetId:o,channelId:n},a=this.getTypingMapKey(i);if(!r||0===r.length)return;let c=this.typingMap.get(a);c||(c=s.observable.map(),this.typingMap.set(a,c)),r.forEach(e=>{c.set(e.userId,e),this.#C(a,e.userId)})})};#C(e,t){const o=this.#f(e,t),n=this.#p.get(o);n&&clearTimeout(n);const r=setTimeout(()=>{s.runInAction(()=>{const s=this.typingMap.get(e);s?.has(t)&&(s.delete(t),0===s.size&&this.typingMap.delete(e)),this.#p.delete(o)})},this.#E);this.#p.set(o,r)}#T=e=>{e&&e.messages&&0!==e.messages.length&&e.messages.forEach(e=>{const{conversationType:t,targetId:s,channelId:o}=e;if(-1===M.typingSupportTypes.indexOf(t))return;const n=`${t};;;${s};;;${o||""}`,r=this.typingMap.get(n);r&&(Array.from(r.keys()).forEach(e=>{const t=this.#f(n,e),s=this.#p.get(t);s&&clearTimeout(s),this.#p.delete(t)}),this.typingMap.delete(n))})};releaseTypingThrottle(e){const t=this.getTypingMapKey(e);this.#S.delete(t)}getTypingMapKey(e){const{conversationType:t,targetId:s,channelId:o=""}=e;return`${t};;;${s};;;${o}`}#f(e,t){return`${e};;;${t}`}}class R{#I;#y=null;#O=()=>{};#M=()=>{};#R=()=>{};#v=null;#N=!1;#A=null;#U=null;#P=!1;#D=0;#L=!1;#G=!1;list=[];#w=new Map;#b=[];#V=new Map;constructor(t,o){this.#I=t,this.#y=o,s.makeAutoObservable(this),e.addEventListener(e.Events.CONNECTED,this._onConnected.bind(this)),e.addEventListener(e.Events.CONVERSATION,this._onRecvConversationNtf.bind(this)),e.addEventListener(e.Events.PULL_OFFLINE_MESSAGE_FINISHED,this._onPullOfflineMessageFinished.bind(this)),e.addEventListener(e.Events.CONVERSATIONS_SYNCED,this._onConversationsSynced.bind(this)),e.addEventListener(e.Events.MESSAGE_RECEIPT_RESPONSE_V5,this._onV5ReceiptResponse.bind(this)),this.#O=this.#$(this.#I.getUsersCache(),e.ConversationType.PRIVATE),this.#M=this.#$(this.#I.getGroupsCache(),e.ConversationType.GROUP),this.#R=this.#$(this.#I.getSystemsCache(),e.ConversationType.SYSTEM)}#x(){const{isConversationListIncludeUltraGroup:t}=e.getAppSettings()||{};this.#L=!!t}#$(e,t){return s.reaction(()=>Array.from(e.entries()),o=>{s.runInAction(()=>{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.#w.set(s.key,s)}})})},{fireImmediately:!1,equals:s.comparer.structural})}getCachedConversationList(){return this.list.slice()}getOpenedConversation(){return this.#v}destroy(){e.removeEventListener(e.Events.CONNECTED,this._onConnected),e.removeEventListener(e.Events.CONVERSATION,this._onRecvConversationNtf),e.removeEventListener(e.Events.PULL_OFFLINE_MESSAGE_FINISHED,this._onPullOfflineMessageFinished),e.removeEventListener(e.Events.CONVERSATIONS_SYNCED,this._onConversationsSynced),e.removeEventListener(e.Events.MESSAGE_RECEIPT_RESPONSE_V5,this._onV5ReceiptResponse),this.#O(),this.#M(),this.#R(),this.clearMemoryData()}clearMemoryData(){this.#A&&(clearTimeout(this.#A),this.#A=null),this.#U&&(clearTimeout(this.#U),this.#U=null),this.#b.length=0,this.#N=!1,this.#P=!1,this.#v=null,this.#D=0,this.list.length=0,this.#G=!1,this.#w.clear(),this.#y?.info(g.S_RECEIVE_DISCONNECT_NOTIFICATION_O,"clear memory data")}_onRecvConversationNtf(e){this.#b.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.#L||this.#G&&!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.#N||this.#L||this._getMoreRemoteConversation(!0)}_onConversationsSynced(){this.#G=!0,this.#N||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 n=o({conversationType:t.conversationType,targetId:t.targetId,channelId:t.channelId}),r=this.#w.get(n);r&&r.latestMessage&&r.latestMessage.messageUId===e?.messageUId&&this.updateCacheConversation(n,{readReceiptInfo:e})})}catch(e){this.#y?.warn(g.S_GET_CONVERSATION_E,`onV5ReceiptResponse error: ${e}`)}}_buildIdentifiersForLatest(s){const o=[];return s.forEach(s=>{const n=s.latestMessage;s.conversationType===e.ConversationType.PRIVATE&&n?.messageDirection===t.MessageDirection.SEND&&n?.messageUId&&o.push({identifier:{conversationType:s.conversationType,targetId:s.targetId,channelId:s.channelId},messageUId:n.messageUId})}),o}async _fetchLatestReadReceiptInfoV5(t){const s=this._buildIdentifiersForLatest(t);if(!s.length)return;const o=[];for(let e=0;e<s.length;e+=100)o.push(s.slice(e,e+100));try{(await Promise.all(o.map(t=>e.getMessageReadReceiptInfoV5ByIdentifiers(t)))).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.ConversationType.PRIVATE)return;const s=t.latestMessage;if(!s?.messageUId)return;const o=`${t.conversationType}|${t.targetId}|${t.channelId||""}|${s.messageUId}`,n=this.#V.get(o);n&&this.updateCacheConversation(t.key,{readReceiptInfo:n})})}catch(e){this.#y?.warn(g.S_GET_CONVERSATION_E,`getMessageReadReceiptInfoV5ByIdentifiers error: ${e}`)}}async _getMoreRemoteConversation(t=!1,s=0){const o=0===s?20:200;this.#y?.info(g.S_GET_CONVERSATION_T,`get conversation list: count = ${o}, startTime = ${s}`);const{code:n,data:r}=await e.getConversationList({count:o,startTime:s});if(this.#y?.info(g.S_GET_CONVERSATION_R,`get conversation list: code = ${n}, data.length = ${r?.length}`),t&&this.#P)return;if(n!==e.ErrorCode.SUCCESS&&!t)return this.#y?.error(g.S_GET_CONVERSATION_E,`get conversation list failed: code = ${n}, count = ${o}, startTime = ${s}`),void(this.#A=setTimeout(()=>this._getMoreRemoteConversation(t,s),3e3));this._fetchLatestReadReceiptInfoV5(r||[]);const i=r||[];if(0===i.length||t)return void this._onGetRemoteConversationListDone(t);const a=0===s&&!t;a&&(this.list.length=0);const c=this._parseConversationList(i);let h=s;if(h=this._handleNextRequestTimestamp(h,c),t||a){const e=c.filter(e=>!this.list.some(t=>t.key===e.key));this.list.push(...e)}t||i.length<o?this._onGetRemoteConversationListDone(t):this.#A=setTimeout(()=>this._getMoreRemoteConversation(!1,h),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 o=s.findIndex(t=>r(t,e));if(o>-1){if(!t)return{origin:o,current:o};s.splice(o,1)}const{isTop:n,updateTime:i}=e;let a=s.findIndex(e=>n?!e.isTop||i>e.updateTime:!e.isTop&&i>e.updateTime);-1===a&&(a=s.length),s.splice(a,0,e)}),this.list=s}_onGetRemoteConversationListDone(e){e||(this.#N=!0),this._handleQueue()}_handleQueue(){if(0===this.#b.length)return;if(this.list.length>=20&&!this.#N)return;const e=new Set,t=new Set,s=new Set,o=Number.MAX_SAFE_INTEGER,n=Date.now();if(this._handleQueueNotify(o=>{const{changeType:n,conversation:r}=o;1===n?(s.add(r),e.add(r)):2===n&&(t.add(r),e.add(r))},e,o,n),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,o){if(!this.#N){let n=0;for(;n<this.#b.length&&Date.now()-o<20&&t.size<s;){const t=this.#b[n];if(t.updatedItems?.latestMessage){if(!t.updatedItems.latestMessage.val.isOffLineMessage)break;this.#b.splice(n,1),e(this._handleConversationNtf(t))}else n+=1}return}for(;this.#b.length&&Date.now()-o<20&&t.size<s;){const t=this.#b.shift();this.#D<=1&&t.updatedItems?.latestMessage?.val.isOffLineMessage||e(this._handleConversationNtf(t))}}_handleConversationNtf(t){const{conversation:s,updatedItems:n}=t,r=o(s);let i=this.#w.get(r);return i&&n?this._handleUpdatedItems(i,n,s):!i&&n?.latestMessage?(s.conversationType===e.ConversationType.PRIVATE?i=this._transPriConversation(s):s.conversationType===e.ConversationType.GROUP?i=this._transGroupConversation(s):s.conversationType===e.ConversationType.SYSTEM&&(i=this._transSystemConversation(s)),i&&this.#w.set(i.key,i),{changeType:2,conversation:i}):{changeType:0}}_handleUpdatedItems(e,t,s){let o=0;t.isTop&&(e.isTop=t.isTop.val,o=Math.max(2,o)),t.notificationLevel&&(e.notificationLevel=t.notificationLevel.val,o=Math.max(1,o)),t.latestMessage?.val&&(this._paddingData(e,s),e.readReceiptInfo=void 0,o=Math.max(2,o));try{const t=`${e.conversationType}|${e.targetId}|${e.channelId||""}|${e.latestMessage?.messageUId||""}`,s=this.#V.get(t);s&&(e.readReceiptInfo=s,o=Math.max(1,o))}catch(e){}return{changeType:o,conversation:e}}getMoreConversationList(t,s){let o=t?this.list.findIndex(e=>r(e,t)):-1;-1===o?o=0:o+=1;const n=o+(s||20),i=this.list.slice(o,n),a=this.list.length>n||!this.#N;return this.#y?.info(g.K_NOTIFY_GET_CONVERSATIONS_O,`get more conversation, conversation: ${t?.key}, count: ${s}, list: ${JSON.stringify(i.length)}`),{hasMore:a,code:e.ErrorCode.SUCCESS,list:i,isFirstScreen:!t}}openConversation(t){if(t){const s=this.#F(t);return this.#v=s,this.#y?.info(g.K_OPEN_CONVERSATION_O,`open conversation, key: ${s.key}`),void(t.conversationType===e.ConversationType.GROUP&&this.#I.groupMembersCache.initGroupMembers(t.targetId))}this.#y?.info(g.K_OPEN_CONVERSATION_O,`close conversation, key: ${this.#v?.key}`),this.#v=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.#w.delete(e),void this.#y?.info(g.S_REMOVE_CONVERSATION_O,`remove conversation: ${s}`)}this.#y?.warn(g.S_REMOVE_CONVERSATION_O,`remove conversation failed: ${e} not found`)}_parseConversationList(t){const s=[];return t.forEach(t=>{const{conversationType:o,targetId:n}=t;switch(o){case e.ConversationType.PRIVATE:s.push(this._transPriConversation(t));break;case e.ConversationType.GROUP:s.push(this._transGroupConversation(t));break;case e.ConversationType.SYSTEM:s.push(this._transSystemConversation(t));break;default:this.#y?.warn(g.S_PARSE_CONVERSATION_E,`unknown conversation type: ${o}, targetId: ${n}`)}}),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.#I?.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.#I?.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.#I?.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(t){const s=o(t);if(this.#w.has(s))return this.#w.get(s);this.count++;const n={key:s,targetId:t.targetId,conversationType:t.conversationType,channelId:t.channelId||"",name:"",nickName:"",portraitUri:"",draft:"",latestMessage:null,isTop:!1,notificationLevel:e.NotificationLevel.ALL_MESSAGE,unreadCount:0,updateTime:0,memberCount:0};return this.#w.set(s,n),n}#k(t){let s;switch(t.conversationType){case e.ConversationType.PRIVATE:s=this.#I?.getUserProfile(t.targetId);break;case e.ConversationType.GROUP:s=this.#I?.getGroupProfile(t.targetId);break;case e.ConversationType.SYSTEM:s=this.#I?.getSystemProfile(t.targetId)}return s}createCachedConversation(t){const s=this.#k(t),o=this.#F(t);return-1===this.list.findIndex(e=>e.key===o.key)&&(s&&(o.name=s.name||"",o.portraitUri=s.portraitUri||"",t.conversationType!==e.ConversationType.SYSTEM&&(o.nickName=s.remark||"")),o.updateTime=Date.now(),this.list.unshift(o),this._recalculatePosition(new Set([o]))),o}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 o=e;this.list[s][o]=t[e]}),this.#w.set(e,this.list[s]),void 0===t.isTop&&void 0===t.latestMessage||this._recalculatePosition(new Set([this.list[s]])),void this.#y?.info(g.S_UPDATE_CONVERSATION_O,`update conversation: ${e}`);this.#y?.warn(g.S_UPDATE_CONVERSATION_O,`update conversation failed: ${e} not found`)}async clearUnreadCount(t){const s=this.list.find(e=>e.key===t);if(s){const t={conversationType:s.conversationType,targetId:s.targetId,channelId:s.channelId};await e.clearMessagesUnreadStatus(t),await e.sendSyncReadStatusMessage(t,(new Date).getTime())}}}class v{_kitStore;openedConversation=null;conversations=[];#q=null;#y=null;constructor(e,t){this._kitStore=e,this.#y=t,s.makeAutoObservable(this),this.#Q(e)}async#Q(e){this.#q=new R(e.appData,this.#y),this.#K(),s.reaction(()=>this.#q?.list,e=>{e&&(this.conversations=e?.slice())})}#K(){const e=this.#q?.getCachedConversationList()||[];s.runInAction(()=>{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),s.runInAction(()=>{this.openedConversation=e})}createCachedConversation(e){this.#y?.info(g.K_CREATE_CACHED_CONVERSATION_O,`create cached conversation: ${JSON.stringify(e)}`);const t=this.#q?.createCachedConversation(e);return s.runInAction(()=>{this.conversations.find(e=>e.key===t.key)||this.conversations.push(t)}),t}removeConversation(e){this.#y?.info(g.K_REMOVE_CONVERSATION_O,`remove conversation: ${e}`),this.#q?.removeConversation(e),s.runInAction(()=>{this.conversations=this.conversations.filter(t=>t.key!==e),this.#y?.info(g.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 N{_logger;cache=s.observable.map();converting=s.observable.set();error=s.observable.set();#B=new Map;static MAX_CACHE_SIZE=200;static REQUEST_TIMEOUT=3e4;constructor(t){this._logger=t,s.makeAutoObservable(this),e.addEventListener(e.Events.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(t){const{messageUId:s}=t;if(this.cache.has(s))return e.ErrorCode.SUCCESS;if(this.converting.has(s))return e.ErrorCode.SUCCESS;this.error.delete(s),this.converting.add(s);const o={messageType:e.MessageType.HQ_VOICE,remoteUrl:t.content.remoteUrl,duration:t.content.duration,sampleRate:t.content.sampleRate,numberOfChannels:t.content.numberOfChannels};try{this._logger?.info(g.S_STT_REQUEST_T,`request: ${s}`);const{code:t,msg:n}=await e.requestSpeechToTextForMessage(s,o);if(this._logger?.info(g.S_STT_REQUEST_R,`request: ${s}`),t===e.ErrorCode.SUCCESS){const e=setTimeout(()=>{this.#B.delete(s),this.converting.has(s)&&(this.converting.delete(s),this.error.add(s),this._logger?.warn(g.S_STT_TIMEOUT_E,`speech-to-text timeout: ${s}`))},N.REQUEST_TIMEOUT);this.#B.set(s,e)}else this.converting.delete(s),this.error.add(s),this._logger?.warn(g.S_STT_REQUEST_E,`request failed: code=${t}, uid=${s}, msg=${n}`);return t}catch(e){return this.converting.delete(s),this.error.add(s),this._logger?.warn(g.S_STT_REQUEST_E,`request exception: ${e}`),-1}}#H=t=>{console.log("response",t);try{const{code:s,messageUId:o,sttInfo:n}=t||{};this._logger?.info(g.S_STT_RESPONSE_R,`response: ${o}`);const r=this.#B.get(o);if(r&&(clearTimeout(r),this.#B.delete(o)),s===e.ErrorCode.SUCCESS){for(this.cache.set(o,n.text);this.cache.size>N.MAX_CACHE_SIZE;){const e=this.cache.keys().next().value||"";this.cache.delete(e)}this.error.delete(o),this.converting.delete(o),this._logger?.info?.(g.S_STT_RESPONSE_O,`success: ${o}`)}else this.converting.delete(o),this.error.add(o),this._logger?.warn(g.S_STT_RESPONSE_E,`failed: code=${s}, uid=${o}`)}catch(e){this._logger?.warn(g.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(){e.removeEventListener(e.Events.SPEECH_TO_TEXT_RESPONSE,this.#H),this.clearMemoryData()}}class A{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 U extends A{_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 P{logger;dataSource;#z=new u(20);#Y=new Map;constructor(e,t){this.logger=e,this.dataSource=t,s.makeAutoObservable(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(g.S_GET_GROUP_MEMBERS_HOOK_T,e,s);const o=await t;if(this.#Y.delete(e),!o||!Array.isArray(o))return void this.logger.error(g.S_GET_GROUP_MEMBERS_HOOK_E,"result must be a Array",s);const n=o.filter((e,t)=>!this.#X(e)||(this.logger.error(g.S_GET_GROUP_MEMBERS_HOOK_E,`result[${t}] is invalid, member: ${JSON.stringify(e)}`,s),!1)).map(this.#J);this.logger.info(g.S_GET_GROUP_MEMBERS_HOOK_R,`groupId: ${e}, memberCount: ${o.length}`,s),this.#z.set(e,n,!1,0)}catch(t){this.#Y.delete(e),this.logger.error(g.S_GET_GROUP_MEMBERS_HOOK_E,e,t)}}getGroupMembers(e){return this.#z.get(e)||[]}getGroupMember(e,t){const s=this.#z.get(e),o=s?.find(e=>e.user.id===t);return o?{...o}:void 0}getGroupMemberMap(e){const t=this.#z.get(e),s=new Map;return t?.forEach(e=>{s.set(e.user.id,{...e})}),s}#X(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}#J(e){const{groupNickname:t,user:s}=e;return{user:{...s},groupNickname:t}}clearMemoryData(){this.#z.clear(),this.#Y.clear()}}class D{logger;#W;#j=s.observable.map();#Z=s.observable.map();#ee=s.observable.map();groupMembersCache;#te={ids:[]};#se={ids:[],timer:void 0};#oe={ids:[],timer:void 0};constructor(e,t={}){this.logger=e,this.#W=new U(t),this.groupMembersCache=new P(e,this.#W),s.makeAutoObservable(this)}getUserProfile(e){return this.#ne({id:e,cache:this.#j,queue:this.#te,batchFetch:e=>this.#W.getUserProfile(e)})}getGroupProfile(e){return this.#ne({id:e,cache:this.#Z,queue:this.#se,batchFetch:e=>this.#W.getGroupProfile(e)})}getSystemProfile(e){return this.#ne({id:e,cache:this.#ee,queue:this.#oe,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.#re(this.#j,[e],[t]):(this.logger.warn(g.K_USER_PROFILE_NOT_FOUND_O,`user id ${e} not found, request remote data`),this.#W.getUserProfile([e]))}updateGroupProfile(e,t){t?this.#re(this.#Z,[e],[t]):(this.logger.warn(g.K_GROUP_PROFILE_NOT_FOUND_O,`group id ${e} not found, request remote data`),this.#W.getGroupProfile([e]))}updateSystemProfile(e,t){t?this.#re(this.#ee,[e],[t]):(this.logger.warn(g.K_SYSTEM_PROFILE_NOT_FOUND_O,`system id ${e} not found, request remote data`),this.#W.getSystemProfile([e]))}async getProfileSync(e,s){if(s===t.ConversationType.PRIVATE){return(await this.#W.getUserProfile([e]))[0]}if(s===t.ConversationType.GROUP){return(await this.#W.getGroupProfile([e]))[0]}return(await this.#W.getSystemProfile([e]))[0]}#ne(e){const t=Date.now(),s=e.cache.get(e.id);if(s)return s.expires>t||s.pending||this.#ie({id:e.id,cache:e.cache,queue:e.queue,batchFetch:e.batchFetch}),s.data;this.#ie({id:e.id,cache:e.cache,queue:e.queue,batchFetch:e.batchFetch})}#ie(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.#ae(e.cache,e.queue,e.batchFetch),200)}async#ae(e,t,o){const n=[...t.ids];if(t.ids=[],t.timer=void 0,0!==n.length)try{const t=await o(n);s.runInAction(()=>this.#re(e,n,t))}catch(t){s.runInAction(()=>this.#ce(e,n))}}#re(e,t,s){const o=Date.now();s.forEach(t=>{const{id:s}=t;s&&(e.set(s,{data:t,expires:o+6e5,pending:!1}),this.logger.info(g.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.#oe].forEach(e=>{e.timer&&clearTimeout(e.timer)}),this.#j.clear(),this.#Z.clear(),this.#ee.clear(),this.groupMembersCache.clearMemoryData()}}class L{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(t=>{e.removeMonitor(t)})}monitorSendMessage(){return e.addMonitor(e.sendMessage,async(t,s)=>{const{code:n,data:r}=await s;if(r?.isPersited){const s={...r,sentStatus:n===e.ErrorCode.SUCCESS?e.SentStatus.SENT:e.SentStatus.FAILED,...t[2]};this.rootStore.messageStore?.updateCatchedMessage(s),this.rootStore.conversationStore?.updateCacheConversation(o(t[0]),{latestMessage:s})}},e=>{const[,,t]=e;if(t){const{messageId:s}=t,n=t?.onSendBefore;t.onSendBefore=t=>{this._logger.info(g.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(o(e[0]),{latestMessage:t,draft:"",readReceiptInfo:void 0})),n?.(t)}}return e})}monitorClearMessagesUnreadStatus(){return e.addMonitor(e.clearMessagesUnreadStatus,async(e,t)=>{this._logger.info(g.S_CLEAR_MESSAGES_UNREAD_STATUS_T,JSON.stringify(e));const s=await t;this._logger.info(g.S_CLEAR_MESSAGES_UNREAD_STATUS_R,JSON.stringify(s));const n=e[0],r=o(n);this.rootStore.conversationStore?.updateCacheConversation(r,{unreadCount:0})})}monitorRemoveConversation(){return e.addMonitor(e.removeConversation,async(e,t)=>{this._logger.info(g.S_REMOVE_CONVERSATION_T,JSON.stringify(e));const s=await t;this._logger.info(g.S_REMOVE_CONVERSATION_R,JSON.stringify(s));const n=e[0],r=o(n);this.rootStore.conversationStore?.removeConversation(r)})}monitorSetConversationNotificationLevel(){return e.addMonitor(e.setConversationNotificationLevel,async(e,t)=>{this._logger.info(g.S_SET_CONVERSATION_NOTIFICATION_LEVEL_T,JSON.stringify(e));const s=await t;this._logger.info(g.S_SET_CONVERSATION_NOTIFICATION_LEVEL_R,JSON.stringify(s));const n=e[0],r=e[1],i=o(n);this.rootStore.conversationStore?.updateCacheConversation(i,{notificationLevel:r})})}monitorSetConversationToTop(){return e.addMonitor(e.setConversationToTop,asy