@tencentcloud/lite-chat 1.1.1 → 1.2.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1 +1 @@
1
- !function(e,s){"object"==typeof exports&&"undefined"!=typeof module?module.exports=s():"function"==typeof define&&define.amd?define(s):(e="undefined"!=typeof globalThis?globalThis:e||self)["TencentCloudChatMessage-enhancer"]=s()}(this,(function(){"use strict";const e={deleteMessage:[{required:!0,rules:["array"],allowEmpty:!1}],revokeMessage:[{required:!0,rules:["object"],allowEmpty:!1}],resendMessage:[{key:"message",required:!0,rules:["object"],allowEmpty:!1},{key:"options",required:!1,rules:["object"],allowEmpty:!1}],getMessageList:{conversationID:{required:!0,rules:["string"],allowEmpty:!1},nextReqMessageID:{required:!1,rules:["string"],allowEmpty:!0},count:{required:!1,rules:["number"],allowEmpty:!0}},getMessageListHopping:{conversationID:{required:!0,rules:["string"],allowEmpty:!1},sequence:{required:!1,rules:["number"],allowEmpty:!0},direction:{required:!1,rules:["number"],allowEmpty:!0},count:{required:!1,rules:["number"],allowEmpty:!0}}},s={deleteMessage:!0,revokeMessage:!0,resendMessage:!0,getMessageList:!0,getMessageListHopping:!0,createTextMessage:!0};function t(e,s,t,n){return new(t||(t=Promise))((function(o,r){function i(e){try{c(n.next(e))}catch(e){r(e)}}function a(e){try{c(n.throw(e))}catch(e){r(e)}}function c(e){var s;e.done?o(e.value):(s=e.value,s instanceof t?s:new t((function(e){e(s)}))).then(i,a)}c((n=n.apply(e,s||[])).next())}))}"function"==typeof SuppressedError&&SuppressedError;class n{constructor(e){this._core=e}deleteMessage(e){return t(this,void 0,void 0,(function*(){const{to:s,messageIdentifiers:t}=e,n="openim.delete_c2c_msg_ramble",o={From_Account:this._getCurrentUserId(),To_Account:s,MsgKeyList:t},r=this._core.helper.generateProtocolData({servcmd:n,data:o}),i=`${r.head.seq}${n}`;return this._core.channel.sendPacket(r,{requestId:i})}))}revokeMessage(e){return t(this,void 0,void 0,(function*(){const{to:s,from:t,sequence:n,time:o,random:r}=e,i="openim.msgwithdraw",a={MsgInfo:{From_Account:t,To_Account:s,MsgSeq:n,MsgRandom:r,MsgTimeStamp:o}},c=this._core.helper.generateProtocolData({servcmd:i,data:a}),g=`${c.head.seq}${i}`;return this._core.channel.sendPacket(c,{requestId:g})}))}_getCurrentUserId(){var e,s;return null===(s=null===(e=this._core)||void 0===e?void 0:e.store.get("login"))||void 0===s?void 0:s.userId}}class o{constructor(e){this._core=e}deleteMessage(e){return t(this,void 0,void 0,(function*(){const{to:s,messageIdentifiers:t}=e,n="group_open_http_svc.delete_group_ramble_msg_by_seq",o={GroupId:s,Deleter_Account:this._getCurrentUserId(),Seqs:t},r=this._core.helper.generateProtocolData({servcmd:n,data:o}),i=`${r.head.seq}${n}`;return this._core.channel.sendPacket(r,{requestId:i})}))}revokeMessage(e){return t(this,void 0,void 0,(function*(){const{to:s,sequence:t}=e,n="group_open_http_svc.group_msg_recall",o={GroupId:s,MsgSeqList:[{MsgSeq:t}]},r=this._core.helper.generateProtocolData({servcmd:n,data:o}),i=`${r.head.seq}${n}`;return this._core.channel.sendPacket(r,{requestId:i})}))}_getCurrentUserId(){var e,s;return null===(s=null===(e=this._core)||void 0===e?void 0:e.store.get("login"))||void 0===s?void 0:s.userId}}const r=2116,i="C2C",a="GROUP",c=20,g=1,l=300;var u,d,h;!function(e){e.MSG_TEXT="TIMTextElem",e.MSG_CUSTOM="TIMCustomElem",e.MSG_LOCATION="TIMLocationElem",e.MSG_FACE="TIMFaceElem"}(u||(u={})),function(e){e[e.DATA_HAS_EXPIRED=0]="DATA_HAS_EXPIRED",e[e.HAS_MORE_DATA=1]="HAS_MORE_DATA",e[e.NO_MORE_DATA=2]="NO_MORE_DATA"}(d||(d={})),function(e){e[e.FORWARD=0]="FORWARD",e[e.BACKWARD=1]="BACKWARD"}(h||(h={}));class v{constructor(e){this._core=e}generateRevokeMessage(e){const{conversationID:s,sequence:t,random:n,tinyID:o,clientTime:r,revokeReason:i,revoker:a}=e;let c={};const{messageStore:g}=this._core.message;return c=g.revokeMessage({conversationID:s,sequence:t,random:n}),c||(c={conversationID:s,sequence:t},o&&r&&n&&(c.ID=`${o}-${r}-${n}`)),c=Object.assign(Object.assign({},c),{revoker:a,revokeReason:i,revokerInfo:{userID:a,nick:"",avatar:""}}),c}updateRevokerInfo(e){return t(this,void 0,void 0,(function*(){const s=e.map((e=>e.revoker));try{const t=yield this._fetchUserInfos(s);t&&e.forEach((e=>{const{revoker:s}=e;t[s]&&(e.revokerInfo.nick=t[s].nick||"",e.revokerInfo.avatar=t[s].avatar||"",e.revokerInfo.userID=s)}))}catch(e){console.debug(e)}}))}filterValidMessages(e){return e.filter((e=>{const s=!this._core.helper.isEmpty(null==e?void 0:e.getElements()),t=1===(null==e?void 0:e.isPlaceMessage);if(!s){this._core.ssoLog.createSSOLogData({method:"emptyMessageBody"}).setLogInfo({message:`from:${e.from} to:${e.to} sequence:${e.sequence}`}).end()}return s&&!t}))}_fetchUserInfos(e){return t(this,void 0,void 0,(function*(){var s,t;const n=yield null===(s=this._core.user.userProfile)||void 0===s?void 0:s.getUserProfile({userIDList:e});return(null==n?void 0:n.data)?null===(t=n.data)||void 0===t?void 0:t.reduce(((e,{userID:s,nick:t,avatar:n})=>(e[s]={nick:t||"",avatar:n||""},e)),{}):null}))}}var M=new class{constructor(){this._core=null,this._c2cMessageAction=null,this._groupMessageAction=null}install(e){this._core=e,this._groupMessageAction=new o(e),this._c2cMessageAction=new n(e),this._messageHelper=new v(e);const{notificationCenter:s,helper:t,InnerEvent:r}=e;s.subscribeInnerEvent(r.DESTROY,this._dispose,this),t.registerApi("deleteMessage",this),t.registerApi("revokeMessage",this),t.registerApi("resendMessage",this)}deleteMessage(e){return t(this,void 0,void 0,(function*(){let s=[],t=[];const{conversationID:n,conversationType:o}=e[0],i=n.replace(o,"");if("@TIM#SYSTEM"===o)throw new this._core.helper.ChatError({code:r});if(e.forEach((e=>{const{conversationID:r,conversationType:i,status:a,_onlineOnlyFlag:c,sequence:g,random:l,time:u}=e||{};if("success"===a&&r===n&&i===o){if(!c){const e="C2C"===i?`${g}_${l}_${u}`:String(g);s.push(e)}t.push(e)}})),0===s.length)return this._handleDeleteMessageSuccess(t),{code:0,data:{messageList:t}};s.length>30&&(s=s.slice(0,30),t=t.slice(0,30));try{return"C2C"===o?yield this._c2cMessageAction.deleteMessage({to:i,messageIdentifiers:s}):yield this._groupMessageAction.deleteMessage({to:i,messageIdentifiers:s}),this._handleDeleteMessageSuccess(t),{code:0,data:{messageList:t}}}catch(e){const{errorCode:s}=e;throw new this._core.helper.ChatError({functionName:"deleteMessage",code:s})}}))}revokeMessage(e){return t(this,void 0,void 0,(function*(){var s;const t=this._core.ssoLog.createSSOLogData({method:"revokeMessage"}),{conversationType:n,isRevoked:o}=e;let r=null;if("@TIM#SYSTEM"===n)throw new this._core.helper.ChatError({message:"system message cannot be revoked"});if(o)throw new this._core.helper.ChatError({message:"message has been revoked"});t.setLogInfo({message:`type:${e.type} from:${e.from} to:${e.to}`});try{if(r="C2C"===n?yield this._c2cMessageAction.revokeMessage(e):yield this._groupMessageAction.revokeMessage(e),r){const{RecallRetList:n}=r,o=(null===(s=null==n?void 0:n[0])||void 0===s?void 0:s.RetCode)||0;if(0!==o)throw new this._core.helper.ChatError({code:o});return t.end(),yield this._handleRevokeMessageSuccess(e),{code:0,data:{message:e}}}}catch(e){const{errorCode:s}=e,t=new this._core.helper.ChatError({functionName:"revokeMessage",code:s});throw this._core.ssoLog.getSSOLogData("revokeMessage").setError(t).end(),t}}))}resendMessage(e,s){return t(this,void 0,void 0,(function*(){var t,n;return e.isResend=!0,e.status="unSend",null===(n=null===(t=this._core)||void 0===t?void 0:t.apiMap)||void 0===n?void 0:n.sendMessage(e,s)}))}_handleDeleteMessageSuccess(e){0!==e.length&&(e.forEach((e=>{e.isDeleted=!0;const s=this._core.message.messageStore.getLocalMessageList(e.conversationID);null==s||s.forEach((s=>{s.ID===e.ID&&(s.isDeleted=!0)}))})),this._core.notificationCenter.emitInnerEvent(this._core.InnerEvent.MESSAGE_DELETED,e[0].conversationID))}_handleRevokeMessageSuccess(e){return t(this,void 0,void 0,(function*(){var s;e.isRevoked=!0,e.revoker=null===(s=this._core.store.get("login"))||void 0===s?void 0:s.userId,yield this._messageHelper.updateRevokerInfo([e]),this._core.notificationCenter.emitInnerEvent(this._core.InnerEvent.MESSAGE_REVOKED,[e])}))}_dispose(){const{notificationCenter:e,InnerEvent:s}=this._core;e.subscribeInnerEvent(s.DESTROY,this._dispose,this)}};class _{static parseServerPushElement(e){const{MsgContent:s={Text:""}}=e,{Text:t}=s;return new _({text:t})}constructor(e){this.type="TIMTextElem",this.content={text:e.text||""}}validateBeforeSend(){var e,s;return(null===(s=null===(e=this.content)||void 0===e?void 0:e.text)||void 0===s?void 0:s.length)>0?{isValid:!0}:{isValid:!1,error:{message:"content can not be empty"}}}convertToBackendFormat(){const{text:e}=this.content;return{MsgType:this.type,MsgContent:{Text:e}}}}var p=new class{install(e){this._core=e,e.message.messageFactory.registerElementClass(u.MSG_TEXT,_),e.helper.registerApi("createTextMessage",this)}createTextMessage(e){var s,t;if(!e)return null;const n="string"==typeof e.payload?e.payload:(null===(s=null==e?void 0:e.payload)||void 0===s?void 0:s.text)||"",o=new _({text:n}),r=null===(t=this._core.store.get("login"))||void 0===t?void 0:t.userId,i=this._core.message.messageFactory.createMessage(Object.assign(Object.assign({},e),{from:r}));return i.setElement(o),i}};class m{install(e){this._messageHelper=new v(e),this._core=e;const{notificationCenter:s,InnerEvent:{MESSAGE_PUSH:t,DESTROY:n},InnerEventSubType:{C2C_NOTIFY_MESSAGE:o}}=e;s.subscribeInnerEvent(t,o,this._handleC2CNotifyMessage,this),s.subscribeInnerEvent(n,this._dispose,this)}_handleC2CNotifyMessage(e){const{C2cNotifyMsgArray:s}=e;null==s||s.forEach((e=>{Object.keys(e).includes("WithdrawC2cMsgNotify")&&this._handleC2CRevokeMessage(e)}))}_handleC2CRevokeMessage(e){return t(this,void 0,void 0,(function*(){try{const{WithdrawC2cMsgNotify:{C2cWithdrawInfoArray:s}}=e,t=[],{notificationCenter:n,OuterEvent:o,InnerEvent:r}=this._core;s.forEach((e=>{const{MsgRand:s,MsgSeq:n,To_Account:o,From_Account:r,RevokerInfo:{Revoker_Account:i,Reason:a}}=e,c=this._getCurrentUserId()===r?`C2C${o}`:`C2C${r}`,g=this._messageHelper.generateRevokeMessage({conversationID:c,sequence:n,random:s,revoker:i,revokeReason:a});t.push(g)})),0!==t.length&&n.emitInnerEvent(r.MESSAGE_REVOKED,{revokedMessages:t,updateUnreadCount:!0}),yield this._messageHelper.updateRevokerInfo(t),n.emitOuterEvent(o.MESSAGE_REVOKED,{name:o.MESSAGE_REVOKED,data:t})}catch(e){console.debug(e)}}))}_getCurrentUserId(){var e,s;return null===(s=null===(e=this._core)||void 0===e?void 0:e.store.get("login"))||void 0===s?void 0:s.userId}_dispose(){const{notificationCenter:e,InnerEvent:{MESSAGE_PUSH:s,DESTROY:t},InnerEventSubType:{C2C_NOTIFY_MESSAGE:n}}=this._core;e.unSubscribeInnerEvent(s,n,this._handleC2CNotifyMessage,this),e.unSubscribeInnerEvent(t,this._dispose,this)}}class E{install(e){this._messageHelper=new v(e),this._core=e;const{notificationCenter:s,InnerEvent:{MESSAGE_PUSH:t,DESTROY:n},InnerEventSubType:{GROUP_NOTIFY_MESSAGE:o}}=e;s.subscribeInnerEvent(t,o,this._handleGroupNotifyMessage,this),s.subscribeInnerEvent(n,this._dispose,this)}_handleGroupNotifyMessage(e){const{GroupTips:s}=e;null==s||s.forEach((e=>{var s;Array.isArray(null===(s=null==e?void 0:e.MsgBody)||void 0===s?void 0:s.GroupWithdrawInfoArray)&&this._handleGroupRevokeMessage(e)}))}_handleGroupRevokeMessage(e){return t(this,void 0,void 0,(function*(){try{const{RevokerInfo:s,MsgBody:{GroupWithdrawInfoArray:t}}=e,n=[],{notificationCenter:o,OuterEvent:r,InnerEvent:i}=this._core;t.forEach((e=>{const{Random:t,MsgSeq:o,GroupId:r,MsgClientTime:i,TinyId:a,TopicId:c,RevokerInfo:{Revoker_Account:g=(null==s?void 0:s.Revoker_Account)||"",Reason:l=(null==s?void 0:s.Reason)||""}}=e,u=c?`GROUP${c}`:`GROUP${r}`,d=this._messageHelper.generateRevokeMessage({conversationID:u,sequence:o,random:t,tinyID:a,clientTime:i,revoker:g,revokeReason:l});n.push(d)})),0!==n.length&&(o.emitInnerEvent(i.MESSAGE_REVOKED,{revokedMessages:n,updateUnreadCount:!0}),yield this._messageHelper.updateRevokerInfo(n),o.emitOuterEvent(r.MESSAGE_REVOKED,{name:r.MESSAGE_REVOKED,data:n}))}catch(e){console.debug(e)}}))}_dispose(){const{notificationCenter:e,InnerEvent:{MESSAGE_PUSH:s,DESTROY:t},InnerEventSubType:{GROUP_NOTIFY_MESSAGE:n}}=this._core;e.unSubscribeInnerEvent(s,n,this._handleGroupNotifyMessage,this),e.unSubscribeInnerEvent(t,this._dispose,this)}}var I=new class{constructor(){this._c2cMessageReceiver=new m,this._groupMessageReceiver=new E}install(e){this._c2cMessageReceiver.install(e),this._groupMessageReceiver.install(e)}};class f{constructor(e){this._lastMessageSequenceMapOnDisconnect=new Map,this._core=e,this._messageHelper=new v(e)}getRoamingMessagesByAnchor(e){return t(this,void 0,void 0,(function*(){try{const s=this._core.ssoLog.createSSOLogData({method:"getRoamingMessagesByAnchor"}),{conversationID:t,count:n,direction:o,sequence:r}=e,i=t.replace(a,"");let c=r;if(o===h.BACKWARD){if("number"!=typeof r)return{messageList:[],hasNoMoreHistoryMessage:!1,nextReqMessageIDFromServer:""};c=r+n-1}const g={GroupId:i,ReqMsgNumber:n,WithRecalledMsg:1,Version:1};c&&(g.ReqMsgSeq=c);const l="group_open_http_svc.group_msg_get",u=this._core.helper.generateProtocolData({servcmd:l,data:g}),v=`${u.head.seq}${l}`,M=yield this._core.channel.sendPacket(u,{requestId:v});if(M){const{RspMsgList:e,NextReqMsgSeq:t=0,IsFinished:n,InvisibleMsgSeq:a}=M;s.setLogInfo({message:`groupID:${i} sequence:${r} reqSeq:${c} direction:${o}\n complete:${n} nextSequence:${t} remoteMsgCount:${e.length} invisibleSequenceList:${a}`}).end();const g=[];for(let s=0;s<e.length;s++){const t=e[s],n=this._parseMessage(t);g.push(n)}g.reverse();return{messageList:g,invisibleSequenceList:a,nextReqMessageIDFromServer:t,hasNoMoreHistoryMessage:[d.NO_MORE_DATA,d.DATA_HAS_EXPIRED].includes(n)}}}catch(e){const s=new this._core.helper.ChatError({code:null==e?void 0:e.code});this._core.ssoLog.getSSOLogData("getRoamingMessagesByAnchor").setError(s).end()}}))}recoverHistoryMessage(e){return t(this,void 0,void 0,(function*(){const{message:{messageReceiver:s,messageStore:n},notificationCenter:o,OuterEvent:r}=this._core;null==e||e.forEach((e=>t(this,void 0,void 0,(function*(){const{conversationID:t,lastMessage:i}=e;let a=this._getLocalLastMessageSequence(t);const c=i.lastSequence;if(this._shouldRecoverHistory({localLastMessageSequence:a,serverLastMessageSequence:c})){const e=c-a;let i=!1;const g=Math.ceil(e/20);for(let e=0;e<g;e++)try{const e=c-a,g=Math.min(20,e),l=yield this.getRoamingMessagesByAnchor({conversationID:t,sequence:a+g,direction:h.FORWARD,count:g}),{nextReqMessageIDFromServer:u,hasNoMoreHistoryMessage:d,messageList:v}=l;i=d&&u<0,a=v[v.length-1].sequence;const M=[];if(Array.isArray(v)&&(v.forEach((e=>{s.groupMessageReceiver.updateMessageProfile(e);n.storeConversationMessage(e)&&M.push(e)})),M.length>0&&o.emitOuterEvent(r.MESSAGE_RECEIVED,{name:r.MESSAGE_RECEIVED,data:M})),i)break}catch(e){console.debug(e);break}}}))))}))}updateLastMessageSequenceMapOnDisconnect(){const e=this._core.message.messageStore.getContinuousMessagesByConversation();for(const[s,t]of e){if(s.startsWith("C2C"))continue;const e=Array.from(t.values());if((null==e?void 0:e.length)>0){const t=e[e.length-1].sequence;this._lastMessageSequenceMapOnDisconnect.set(s,t)}}}_shouldRecoverHistory(e){const{localLastMessageSequence:s,serverLastMessageSequence:t}=e;if("number"!=typeof s||"number"!=typeof t)return!1;const n=t-s;return 0!==t&&s&&(n>=g&&n<l)}_getLocalLastMessageSequence(e){if(this._lastMessageSequenceMapOnDisconnect.has(e))return this._lastMessageSequenceMapOnDisconnect.get(e);const s=this._core.message.messageStore.getLocalMessageList(e),t=s[s.length-1];return null==t?void 0:t.sequence}_parseMessage(e){const s=a,t=this._core.message.messageHelper.parseServerGroupMessage(e),n=this._core.message.messageFactory.createMessage(Object.assign(Object.assign({},t),{conversationType:s,flow:"in"}));return n.setElement(t.elements),n}}var S=new class{constructor(){this._clearedConversations=new Set,this._fetchedCompleteConversations=new Set}install(e){this._core=e,this._groupMessageHistory=new f(e),this._messageHelper=new v(e);const{InnerEvent:s,notificationCenter:t}=e;e.helper.registerApi("getMessageList",this),e.helper.registerApi("getMessageListHopping",this),t.subscribeInnerEvent(s.RECOVER_CONVERSATIONS_COMPLETED,this._recoverHistoryMessage,this),t.subscribeInnerEvent(s.SOCKET_DISCONNECTED,this._handleSocketDisconnected,this),t.subscribeInnerEvent(s.DESTROY,this._dispose,this)}getMessageList(e){return t(this,void 0,void 0,(function*(){try{const s=this._core.ssoLog.createSSOLogData({method:"getMessageList"});let{conversationID:t,nextReqMessageID:n}=e;const o=c;if("@TIM#SYSTEM"===t)return{code:0,data:{messageList:[],isCompleted:!1,nextMessageSeq:""}};const r=this._getAvailableLocalMessagesCount({conversationID:t,nextReqMessageID:n});if(this._needFetchHistoryMessageList({conversationID:t,availableLocalMessagesCount:r,targetCount:o})){let e=null;if(t.startsWith(a)&&(e=yield this._groupMessageHistory.getRoamingMessagesByAnchor({conversationID:t,sequence:Number(n),count:o,direction:h.FORWARD})),e){const{nextReqMessageIDFromServer:o,hasNoMoreHistoryMessage:i,messageList:a}=e,c=this._messageHelper.filterValidMessages(a),g=this._core.message.messageStore.prependLocalMessageList({messageList:c,conversationID:t}),l=this._core.message.messageStore.getLocalMessageList(t).slice(0,g.length+r),u=l.filter((e=>e.isRevoked));yield this._messageHelper.updateRevokerInfo(u);const d={nextReqMessageID:i?"":String(o),messageList:l,isCompleted:i},h=l.map((e=>e.sequence));return s.setLogInfo({message:`conversationID: ${t} nextReqMessageID: ${n} \n availableLocalMessagesCount: ${r} sequenceList: ${JSON.stringify(h)} `}).end(),{code:0,data:d}}return{code:0,data:{messageList:[],isCompleted:!1,nextMessageSeq:""}}}s.setLogInfo({message:`conversationID: ${t} nextReqMessageID: ${n} availableLocalMessagesCount: ${r}}`}).end();return{code:0,data:this._getMessageListFromMemory({conversationID:t,nextReqMessageID:n,count:o})}}catch(e){const s=new this._core.helper.ChatError({code:null==e?void 0:e.code});this._core.ssoLog.getSSOLogData("getMessageList").setError(s).end(),console.debug(s)}}))}getMessageListHopping(e){return t(this,void 0,void 0,(function*(){var s,t;const{conversationID:n,sequence:o,direction:r=h.FORWARD}=e,{isEmpty:i}=this._core.helper;if(![h.BACKWARD,h.FORWARD].includes(r))throw new this._core.helper.ChatError({message:"direction must be 0 or 1"});let{count:g=c}=e;g=g>c?c:g;let l=null;if(n.startsWith(a)&&(l=yield this._groupMessageHistory.getRoamingMessagesByAnchor({conversationID:n,sequence:o,count:g,direction:r})),l){const{nextReqMessageIDFromServer:e,hasNoMoreHistoryMessage:n,messageList:a,invisibleSequenceList:c}=l,g=this._messageHelper.filterValidMessages(a);if(this._core.message.messageStore.storeSparseMessageList(g),r===h.FORWARD){const s=n&&e<1;return{code:0,data:{messageList:g,isCompleted:s,nextMessageSeq:s?"":e}}}if(r===h.BACKWARD){if(i(a)&&i(c))return{code:0,data:{messageList:[],isCompleted:!0,nextMessageSeq:""}};const e=(null===(s=null==a?void 0:a[a.length-1])||void 0===s?void 0:s.sequence)||0,n=(null===(t=null==c?void 0:c[c.length-1])||void 0===t?void 0:t.sequence)||0;return{code:0,data:{messageList:g.filter((e=>e.sequence>=o)),isCompleted:!1,nextMessageSeq:Math.max(e,n)+1}}}return{code:0,data:l}}return{code:0,data:{messageList:[],isCompleted:!1,nextMessageSeq:""}}}))}_getAvailableLocalMessagesCount({conversationID:e,nextReqMessageID:s}){const t=this._core.message.messageStore.getLocalMessageList(e),{length:n}=t;if(!s)return n;let o=-1;return(null==e?void 0:e.startsWith(i))?o=t.findIndex((e=>e.ID===s)):(null==e?void 0:e.startsWith(a))&&(o=t.findIndex((e=>s.includes("-")?e.ID===s:String(e.sequence)===s))),-1===o?0:o}_needFetchHistoryMessageList({conversationID:e,availableLocalMessagesCount:s,targetCount:t}){return!!this._clearedConversations.has(e)||s<=t&&!this._fetchedCompleteConversations.has(e)}_getMessageListFromMemory({conversationID:e,nextReqMessageID:s,count:t}){const n=this._core.message.messageStore.getLocalMessageList(e),o=n.length;let r=o,a={isCompleted:!1,nextReqMessageID:"",messageList:[]},c=0,g=o;return s?s&&(g=n.findIndex((t=>e.startsWith(i)?t.ID===s:String(t.sequence)===s)),c=g>t?g-t:0,r=g):c=o>t?o-t:0,a.nextReqMessageID=0===c?"":this._generateNextReqMessageID({conversationID:e,targetIndex:c}),a.messageList=n.slice(c,g),a.isCompleted=r<=t,a}_generateNextReqMessageID({conversationID:e,targetIndex:s}){const t=this._core.message.messageStore.getLocalMessageList(e);return e.startsWith("C2C")?t[s].ID:String(t[s].sequence)}_recoverHistoryMessage(){const{conversationMap:e}=this._core.store.get("conversation")||{};if(e instanceof Map){const s=[...e.values()].filter((e=>e.type===a));this._groupMessageHistory.recoverHistoryMessage(s)}}_handleSocketDisconnected(){this._groupMessageHistory.updateLastMessageSequenceMapOnDisconnect()}_dispose(){const{notificationCenter:e,InnerEvent:s}=this._core;e.unSubscribeInnerEvent(s.RECOVER_CONVERSATIONS_COMPLETED,this._recoverHistoryMessage,this),e.unSubscribeInnerEvent(s.SOCKET_DISCONNECTED,this._handleSocketDisconnected,this),e.unSubscribeInnerEvent(s.DESTROY,this._dispose,this)}};var R=new class{install(e){this._core=e;const{helper:s}=e;s.registerApi("getMessageReactions",this),s.registerApi("getMessageReadReceiptList",this)}getMessageReadReceiptList(e){return t(this,void 0,void 0,(function*(){return console.log("getMessageReadReceiptList: options: ",e),{code:0,data:{messageList:[]}}}))}getMessageReactions(e){return t(this,void 0,void 0,(function*(){return console.log("getMessageReactions: options: ",e),{code:0,data:[]}}))}};return function(t){M.install(t),p.install(t),I.install(t),S.install(t),R.install(t),t.helper.registerValidateConfig({auth:s,params:e})}}));
1
+ !function(e,t){"object"==typeof exports&&"undefined"!=typeof module?module.exports=t():"function"==typeof define&&define.amd?define(t):(e="undefined"!=typeof globalThis?globalThis:e||self)["TencentCloudChatMessage-enhancer"]=t()}(this,(function(){"use strict";function e(e,t,s,o){return new(s||(s=Promise))((function(n,r){function i(e){try{c(o.next(e))}catch(e){r(e)}}function a(e){try{c(o.throw(e))}catch(e){r(e)}}function c(e){var t;e.done?n(e.value):(t=e.value,t instanceof s?t:new s((function(e){e(t)}))).then(i,a)}c((o=o.apply(e,t||[])).next())}))}"function"==typeof SuppressedError&&SuppressedError;const t=new class{init(e){this.core=e}};var s,o,n;!function(e){e.MSG_TEXT="TIMTextElem",e.MSG_CUSTOM="TIMCustomElem",e.MSG_LOCATION="TIMLocationElem",e.MSG_FACE="TIMFaceElem"}(s||(s={})),function(e){e[e.DATA_HAS_EXPIRED=0]="DATA_HAS_EXPIRED",e[e.HAS_MORE_DATA=1]="HAS_MORE_DATA",e[e.NO_MORE_DATA=2]="NO_MORE_DATA"}(o||(o={})),function(e){e[e.FORWARD=0]="FORWARD",e[e.BACKWARD=1]="BACKWARD"}(n||(n={}));const r="MSG_REACTION",i=0,a=1,c={ZH_CN:"zh (cmn-Hans-CN)",EN_US:"en-US",YUE_HK:"yue-Hant-HK",JA_JP:"ja-JP",ZH_PY:"zh-PY"},d="16k_zh",u="16k_en",l="16k_yue",g="16k_ja",m="16k_zh-PY",h={[c.ZH_CN]:d,[c.EN_US]:u,[c.YUE_HK]:l,[c.JA_JP]:g,[c.ZH_PY]:m},p=/\.(wav|pcm|ogg-opus|speex|silk|mp3|m4a|aac|amr)/,_={READ:0,UNREAD:1};const v=2116,M="C2C",f="GROUP",y=20,R=1,E=300;function I(s){return e(this,void 0,void 0,(function*(){var o;const{appStore:n}=t.core,{messageList:r,conversationID:i}=s,a=n.conversationStore.getConversationMap();let c=null===(o=a.get(i))||void 0===o?void 0:o.peerReadTime;if(!c){const s=i.replace(M,""),o=yield function(s){return e(this,void 0,void 0,(function*(){const e={To_Account:s};return t.core.common.buildAndSendPacket({servcmd:"openim.get_peer_read_time",data:e})}))}([s]);if(o){const{ReadTime:e}=o;c=null==e?void 0:e[0],a.has(i)&&(a.get(i).peerReadTime=c)}}r.forEach((e=>{e.time<=c&&!e.isPeerRead&&"out"===e.flow&&(e.isPeerRead=!0)}))}))}function C(s){return e(this,void 0,void 0,(function*(){var e;const{message:o,user:n,appStore:r,constants:{OuterConstant:i}}=t.core,a=r.conversationStore.getConversationMap();if(a.has(s)){const r=null===(e=a.get(s))||void 0===e?void 0:e.userProfile;if(r&&s.startsWith(i.CONV_C2C)){const{avatar:e,nick:o}=r;t.core.message.messageDataHandler.updateNickAndAvatarOfSentMessage({conversationID:s,latestAvatar:e,latestNick:o,isSentByMe:!1})}const{data:c}=(yield n.userProfile.getMyProfile())||{};if(c){const{avatar:e,nick:t}=c;o.messageDataHandler.updateNickAndAvatarOfSentMessage({conversationID:s,latestAvatar:e,latestNick:t,isSentByMe:!0})}}}))}function S(e){let s;const{message:o}=t.core,{conversationID:n,messageID:r}=e;if(s=o.messageDataHandler.getLocalMessageList(n).find((e=>e.ID===r)),!s){s=o.messageDataHandler.getSparseMessageList(n).find((e=>e.ID===r))}return s}function D(e){return e.map((e=>{const{from:t,to:s,cloudCustomData:o,avatar:n,nick:r,ID:i,clientSequence:a,clientTime:c,messageRandom:d,messageSequence:u,time:l}=e;return{ClientSeq:a,CloudCustomData:o,From_Account:t,From_AccountHeadurl:n,From_AccountNick:r,Id:i,MsgBody:JSON.parse(JSON.stringify(e.transformElementsToServerFormat())),MsgClientTime:c,MsgRandom:d,Random:d,MsgSeq:u,MsgTimeStamp:l,ReceiverId:s,SenderId:t,To_Account:s}}))}function A(e){var s;const{From_Account:o,From_AccountHeadurl:n,From_AccountNick:r,GroupId:i,MsgClientTime:a,ClientSeq:c,To_Account:d,MsgTimeStamp:u,TinyId:l,MsgRandom:g,MsgSeq:m}=e;return{from:o,avatar:n,nick:r,clientTime:a,time:u,tinyID:l,random:g,sequence:m,to:d,groupID:i,clientSequence:c,_elements:null===(s=e.MsgBody)||void 0===s?void 0:s.map((e=>{const{MsgType:s}=e;return t.core.message.messageFactory.getElementClass(s).parseServerPushElement(e)}))}}var L=new class{constructor(){this._reactionsMap=new Map}init(e){this._core=e;const{helper:t,notificationCenter:s,InnerEvent:{MESSAGE_PUSH:o},InnerEventSubType:{MESSAGE_REACTION_UPDATED:n,MESSAGE_REACTION_UPDATED_SYNC:r}}=e;t.registerApi({apiName:"addMessageReaction",context:this}),t.registerApi({apiName:"removeMessageReaction",context:this}),t.registerApi({apiName:"getMessageReactions",context:this}),t.registerApi({apiName:"getAllUserListOfMessageReaction",context:this}),s.subscribeInnerEvent(o,n,this._handleReactionUpdated,this),s.subscribeInnerEvent(o,r,this._handleReactionSync,this)}addMessageReaction(s,o){return e(this,void 0,void 0,(function*(){const{OuterConstant:n,ssoLog:r,helper:i}=this._core;this._validateMessageReactionBusinessCapability();const a=r.createSSOLogData({method:"addMessageReaction"}),{conversationID:c,ID:d,conversationType:u,from:l,to:g,clientSequence:m,random:h,time:p,sequence:_}=s;try{return this._recordMessageReactedByMe(d,o),u===n.CONV_C2C?yield function(s,o){return e(this,void 0,void 0,(function*(){var e;const{from:n,to:r,clientSequence:i,random:a,time:c,reactionID:d}=s,u={From_Account:n,To_Account:r,MsgKey:`${i}_${a}_${c}`,Reaction:d,Add_Account:[null===(e=o.store.get("login"))||void 0===e?void 0:e.userId]};return t.core.common.buildAndSendPacket({servcmd:"openim_msg_ext_http_svc.reaction_add",data:u})}))}({from:l,to:g,clientSequence:m,random:h,time:p,reactionID:o},this._core):u===n.CONV_GROUP&&(yield function(s,o){return e(this,void 0,void 0,(function*(){var e;const{to:n,reactionID:r,sequence:i}=s,a={GroupId:n,MsgSeq:i,Reaction:r,Add_Account:[null===(e=o.store.get("login"))||void 0===e?void 0:e.userId]};return t.core.common.buildAndSendPacket({servcmd:"openim_msg_ext_http_svc.group_reaction_add",data:a})}))}({to:g,reactionID:o,sequence:_},this._core)),a.setLogInfo({message:`conversationID:${c} messageID:${d} reactionID:${o}`}).end(),{code:0}}catch(e){this._removeMyReactionRecord(d,o);const{errorCode:t}=e||{},s=new i.ChatError({functionName:"addMessageReaction",code:t});a.setError(s).end(),console.error("addMessageReaction error: ",e)}}))}removeMessageReaction(s,o){return e(this,void 0,void 0,(function*(){const{OuterConstant:n,ssoLog:r,helper:i}=this._core;this._validateMessageReactionBusinessCapability();const a=r.createSSOLogData({method:"removeMessageReaction"});try{const{conversationID:r,ID:i,conversationType:c,from:d,to:u,clientSequence:l,random:g,time:m,sequence:h}=s;return this._removeMyReactionRecord(i,o),c===n.CONV_C2C?yield function(s,o){return e(this,void 0,void 0,(function*(){var e;const{from:n,to:r,clientSequence:i,random:a,time:c,reactionID:d}=s,u={From_Account:n,To_Account:r,MsgKey:`${i}_${a}_${c}`,Reaction:d,Del_Account:[null===(e=o.store.get("login"))||void 0===e?void 0:e.userId]};return t.core.common.buildAndSendPacket({servcmd:"openim_msg_ext_http_svc.reaction_del",data:u})}))}({from:d,to:u,clientSequence:l,random:g,time:m,reactionID:o},this._core):c===n.CONV_GROUP&&(yield function(s,o){return e(this,void 0,void 0,(function*(){var e;const{common:{isTopic:n},constants:{OuterConstant:{GROUP_ID_PREFIX:r}}}=t.core,{to:i,reactionID:a,sequence:c}=s,d=null===(e=o.store.get("login"))||void 0===e?void 0:e.userId;let u,l=i;n(i)&&(u=i,l=u.split(r.TOPIC)[0]);const g={TopicId:u,GroupId:l,MsgSeq:c,Reaction:a,Del_Account:[d]};return t.core.common.buildAndSendPacket({servcmd:"openim_msg_ext_http_svc.group_reaction_del",data:g},o)}))}({to:u,reactionID:o,sequence:h},this._core)),a.setLogInfo({message:`conversationID:${r} messageID:${i} reactionID:${o}`}).end(),{code:0}}catch(e){const{errorCode:t}=e||{},s=new i.ChatError({functionName:"removeMessageReaction",code:t});a.setError(s).end(),console.error("removeMessageReaction error: ",e)}}))}getAllUserListOfMessageReaction(s){return e(this,void 0,void 0,(function*(){this._validateMessageReactionBusinessCapability();const{message:o,reactionID:n,nextSeq:r=0}=s,i=s.count>100?100:s.count,{conversationID:a}=o,{ssoLog:c,helper:d,constants:u}=this._core;try{let s=null;if(s=a.startsWith(u.OuterConstant.CONV_C2C)?yield function(s){return e(this,void 0,void 0,(function*(){const{message:e,nextSeq:o,reactionID:n,count:r}=s,{from:i,to:a,clientSequence:c,random:d,time:u}=e,l={Reaction:n,NextSeq:o,Count:r,From_Account:i,To_Account:a,MsgKey:`${c}_${d}_${u}`};return t.core.common.buildAndSendPacket({servcmd:"openim_msg_ext_http_svc.reaction_iterate",data:l})}))}({message:o,reactionID:n,nextSeq:r,count:i}):yield function(s){return e(this,void 0,void 0,(function*(){const{common:{isTopic:e},constants:{OuterConstant:{GROUP_ID_PREFIX:o}}}=t.core,{message:n,nextSeq:r,reactionID:i,count:a}=s,{sequence:c}=n;let d,u=n.to;e(n.to)&&(d=n.to,u=d.split(o.TOPIC)[0]);const l={Reaction:i,NextSeq:r,TopicId:d,GroupId:u,Count:a,MsgSeq:c};return t.core.common.buildAndSendPacket({servcmd:"openim_msg_ext_http_svc.group_reaction_iterate",data:l})}))}({message:o,reactionID:n,nextSeq:r,count:i}),s){const{Reaction_Account:e,NextSeq:t}=s,o=yield this._getUserProfileList(e);return{code:0,data:{nextSeq:t,isCompleted:0===r,userList:o}}}}catch(e){const{errorCode:t}=e||{},s=new d.ChatError({functionName:"getAllUserListOfMessageReaction",code:t});c.createSSOLogData({method:"removeMessageReaction"}).setError(s).end(),console.error("getAllUserListOfMessageReaction error: ",e)}}))}getMessageReactions(s){return e(this,void 0,void 0,(function*(){const{constants:o}=this._core;this._validateMessageReactionBusinessCapability();const{messageList:n,maxUserCountPerReaction:r=10}=s,i=n[0];let a=null;const c=new Map,{from:d,to:u,conversationType:l}=i,g=this._generateMessageKeyList(n,c);l===o.OuterConstant.CONV_C2C?a=yield function(s){return e(this,void 0,void 0,(function*(){const{from:e,to:o,messageKeyList:n,maxUserCountPerReaction:r}=s,i={From_Account:e,To_Account:o,MsgKeyList:n,Count:r};return t.core.common.buildAndSendPacket({servcmd:"openim_msg_ext_http_svc.reaction_multi_stat",data:i})}))}({from:d,to:u,messageKeyList:g,maxUserCountPerReaction:r}):l===o.OuterConstant.CONV_GROUP&&(a=yield function(s){return e(this,void 0,void 0,(function*(){const{common:{isTopic:e},constants:{OuterConstant:{GROUP_ID_PREFIX:o}}}=t.core;let n,{groupId:r,messageSequenceList:i,maxUserCountPerReaction:a}=s;e(r)&&(n=r,r=r.split(o.TOPIC)[0]);const c={GroupId:r,TopicId:n,MsgSeqList:i,Count:a};return t.core.common.buildAndSendPacket({servcmd:"openim_msg_ext_http_svc.group_reaction_multi_stat",data:c})}))}({groupId:u,messageSequenceList:g,maxUserCountPerReaction:r}));const{Results:m=[]}=a||{},h=this._extractUserIDsFromReactionResults(m),p=yield this._getUserProfileMap(h);return{code:0,data:{resultList:m.map((e=>{const{ReactionList:t,MsgSeq:s,MsgKey:o}=e;return{messageID:this._generateMessageID({messageSequence:s,messageKey:o,messageIDMap:c}),reactionList:t.map((e=>{const{Reaction:t,Count:s,Reaction_Account:o,ReactedByMe:n}=e;return{reactionID:t,totalUserCount:s,partialUserList:this._generatePartialUserInfo({userIDList:o,userProfileMap:p}),reactedByMyself:1===n}}))}}))}}}))}dispose(){this._reactionsMap.clear()}_extractUserIDsFromReactionResults(e){const t=[];return null==e||e.forEach((e=>{const{ReactionList:s=[]}=e;s.forEach((e=>{e.Reaction_Account&&t.push(...e.Reaction_Account)}))})),t}_getUserProfileList(t){return e(this,void 0,void 0,(function*(){var e;try{const s=yield null===(e=this._core.user.userProfile)||void 0===e?void 0:e.getUserProfile({userIDList:t});return s?s.data:[]}catch(e){return[]}}))}_getUserProfileMap(t){return e(this,void 0,void 0,(function*(){const e=new Map;return(yield this._getUserProfileList(t)).forEach((t=>{const{nick:s,avatar:o,userID:n}=t;e.set(n,{nick:s,avatar:o,userID:n})})),e}))}_recordMessageReactedByMe(e,t){const s=`${e}-${t}`;this._reactionsMap.has(s)?this._reactionsMap.get(s).reactedByMe=!0:this._reactionsMap.set(s,{reactedByMe:!0})}_removeMyReactionRecord(e,t){const s=`${e}-${t}`;this._reactionsMap.has(s)&&(this._reactionsMap.get(s).reactedByMe=!1)}_recordMessageReactionInfo(e){const{messageID:t,reactionID:s,reactionInfo:o}=e,n=`${t}-${s}`,r=this._reactionsMap.get(n)||{};this._reactionsMap.set(n,Object.assign(Object.assign({},r),o))}_validateMessageReactionBusinessCapability(){const{helper:e,constants:t}=this._core;if(!e.checkBusinessCapabilityBits(r))throw new e.ChatError({functionName:"addMessageReaction",code:t.ERROR_CODE.NO_USE,replacement1:"addMessageReaction"})}_handleReactionUpdated(t){const{MsgReactionNotifyList:s}=t,{notificationCenter:o,constants:n}=this._core;s.forEach((t=>e(this,void 0,void 0,(function*(){const{C2CMsgInfo:e,GroupMsgInfo:s,MsgReactionSummary:r}=t,{TinyId:i,MsgClientTime:a,MsgRandom:c}=Object.assign(Object.assign({},e),s),d=`${i}-${a}-${c}`,u=this._extractUserIDsFromReactionResults([{ReactionList:r}]),l=yield this._getUserProfileMap(u),g=r.map((e=>{var t;const{Reaction:s,Reaction_Account:o}=e,n=this._generatePartialUserInfo({userIDList:o,userProfileMap:l}),r=o?e.Count:0,i=(null===(t=this._reactionsMap.get(`${d}-${s}`))||void 0===t?void 0:t.reactedByMe)||!1;return this._recordMessageReactionInfo({messageID:d,reactionID:s,reactionInfo:{reactionID:s,totalUserCount:r,partialUserList:n}}),{reactionID:s,totalUserCount:r,partialUserList:n,reactedByMyself:i}}));o.emitOuterEvent(n.OuterEvent.MESSAGE_REACTIONS_UPDATED,{name:n.OuterEvent.MESSAGE_REACTIONS_UPDATED,data:{messageID:d,reactionList:g}})}))))}_handleReactionSync(e){var t;const{notificationCenter:s,constants:o}=this._core,{C2CMsgInfo:n={},GroupMsgInfo:r={},Reaction:i,OperateType:a}=e.MsgReactionNotify,{TinyId:c="",MsgClientTime:d=0,MsgRandom:u=0}=Object.assign(Object.assign({},n),r),l=`${c}-${d}-${u}`,g=`${l}-${i}`;if(1===a?this._recordMessageReactedByMe(l,i):this._removeMyReactionRecord(l,i),null===(t=this._reactionsMap.get(g))||void 0===t?void 0:t.reactionID){const e=this._reactionsMap.get(g);e.reactedByMyself=1===a,s.emitOuterEvent(o.OuterEvent.MESSAGE_REACTIONS_UPDATED,{name:o.OuterEvent.MESSAGE_REACTIONS_UPDATED,data:{messageID:l,reactionList:[e]}})}}_generatePartialUserInfo({userIDList:e,userProfileMap:t}){const s=[];return null==e||e.forEach((e=>{t.has(e)&&s.push(t.get(e))})),s}_generateMessageID(e){const{messageSequence:t,messageKey:s,messageIDMap:o}=e;return s?o.get(s):o.get(t)}_generateMessageKeyList(e,t){const{constants:s}=this._core,o=e[0],{conversationType:n}=o;let r=[];return n===s.OuterConstant.CONV_C2C?r=e.map((e=>{const{clientSequence:s,random:o,time:n,ID:r}=e,i=`${s}_${o}_${n}`;return t.set(i,r),i})):n===s.OuterConstant.CONV_GROUP&&(r=e.map((e=>{const{ID:s,sequence:o}=e;return t.set(o,s),o}))),r}};var O=new class{init(e){this._core=e;const{helper:t,InnerEvent:{MESSAGE_PUSH:s},InnerEventSubType:{C2C_MESSAGE_READ_RECEIPT:o,GROUP_MESSAGE_READ_RECEIPT:n},notificationCenter:r}=e;t.registerApi({apiName:"sendMessageReadReceipt",context:this}),t.registerApi({apiName:"getMessageReadReceiptList",context:this}),t.registerApi({apiName:"getGroupMessageReadMemberList",context:this}),r.subscribeInnerEvent(s,o,this._handleC2CMessageReadReceipt,this),r.subscribeInnerEvent(s,n,this._handleGroupMessageReadReceipt,this)}sendMessageReadReceipt(s){return e(this,void 0,void 0,(function*(){const{common:o,constants:n}=this._core,r=this._filterValidMessageSendByOther(s);if(0===r.length)throw new o.ChatError({code:n.ERROR_CODE.READ_RECEIPT_MSG_LIST_EMPTY});try{const{conversationType:s}=r[0];return s===n.OuterConstant.CONV_C2C?yield function(s){return e(this,void 0,void 0,(function*(){const{common:e,constants:o}=t.core,n={Peer_Account:s[0].conversationID.replace(o.OuterConstant.CONV_C2C,""),C2CMsgInfo:s.map((e=>{const{from:t,to:s,sequence:o,random:n,time:r,clientTime:i}=e;return{From_Account:t,To_Account:s,MsgSeq:o,MsgRandom:n,MsgTime:r,MsgClientTime:i}}))};return e.buildAndSendPacket({servcmd:"openim.c2c_msg_read_receipt",data:n})}))}(r):yield function(s){return e(this,void 0,void 0,(function*(){const{common:e,constants:o}=t.core,n={GroupId:s[0].conversationID.replace(o.OuterConstant.CONV_GROUP,""),MsgSeqList:s.map((e=>({MsgSeq:e.sequence})))};return e.buildAndSendPacket({servcmd:"group_open_http_svc.group_msg_receipt",data:n})}))}(r),{code:0,data:{}}}catch(e){const{errorCode:t,errorInfo:s}=e;throw new o.ChatError({code:t,message:s})}}))}getMessageReadReceiptList(s){return e(this,void 0,void 0,(function*(){const{common:o,constants:n}=this._core;try{const{conversationType:o}=s[0];if(o===n.OuterConstant.CONV_GROUP){const o=this._filterValidMessageSendByMe(s);if((null==o?void 0:o.length)>0){const n=yield function(s){return e(this,void 0,void 0,(function*(){const{common:e,constants:o}=t.core,n={GroupId:s[0].conversationID.replace(o.OuterConstant.CONV_GROUP,""),MsgSeqList:s.map((e=>({MsgSeq:e.sequence})))};return e.buildAndSendPacket({servcmd:"group_open_http_svc.get_group_msg_receipt",data:n})}))}(o),{GroupMsgReceiptList:r}=n||{};this._updateGroupMessagesReadReceiptInfo({messageList:s,readReceiptList:r})}}return{code:0,data:{messageList:s}}}catch(e){const{errorCode:t,errorInfo:s}=e;throw new o.ChatError({code:t,message:s})}}))}getGroupMessageReadMemberList(s){return e(this,void 0,void 0,(function*(){const{constants:o,common:n}=this._core,{message:r,filter:i=_.READ,cursor:a=""}=s,{conversationID:c,sequence:d,ID:u}=r,l=c.replace(o.OuterConstant.CONV_GROUP,""),g=s.count>=100?100:s.count;try{const s=yield function(s){return e(this,void 0,void 0,(function*(){const{sequence:e,groupID:o,filter:n,cursor:r,count:i}=s,a={MsgSeq:e,GroupId:o,Filter:n,Cursor:r,Num:i};return t.core.common.buildAndSendPacket({servcmd:"group_open_http_svc.get_group_msg_receipt_detail",data:a})}))}({groupID:l,sequence:d,filter:i,cursor:a,count:g});if(s){const{Cursor:e,IsFinish:t,UnreadList:o,ReadList:n}=s,r={cursor:e,isCompleted:1===t,messageID:u,unreadUserIDList:[],readUserIDList:[]};return i===_.READ?r.readUserIDList=n.map((e=>e.Read_Account)):i===_.UNREAD&&(r.unreadUserIDList=o.map((e=>e.Unread_Account))),{code:0,data:r}}}catch(e){const{errorCode:t,errorInfo:s}=e;throw new n.ChatError({code:t,message:s})}}))}_handleC2CMessageReadReceipt(e){const t=[],{constants:s,helper:o}=this._core,{C2cMsgInfo:n,PeerReadTime:r,Peer_Account:i}=e;if(o.isEmpty(n))return;const a=`${s.OuterConstant.CONV_C2C}${i}`;null==n||n.forEach((e=>{const{TinyId:s,MsgClientTime:o,MsgRandom:n}=e,c=`${s}-${o}-${n}`,d=S({conversationID:a,messageID:c});d&&!d.readReceiptInfo.isPeerRead&&(d.readReceiptInfo.isPeerRead=!0,d.readReceiptInfo.timestamp=r,t.push({userID:i,messageID:c,isPeerRead:!0,timestamp:r}))})),this._emitReadReceiptEventIfNeed(t)}_updateGroupMessagesReadReceiptInfo(e){const{messageList:t,readReceiptList:s}=e,o=new Map;t.forEach((e=>{o.set(e.sequence,e)})),null==s||s.forEach((e=>{if(0===e.Code){const{MsgSeq:t,ReadNum:s,UnreadNum:n}=e,r=o.get(t);r&&(r.readReceiptInfo.readCount=s,r.readReceiptInfo.unreadCount=n)}}))}_handleGroupMessageReadReceipt(e){const t=[],{constants:s}=this._core,{GroupTips:o}=e;o.forEach((e=>{const{MsgBody:{GroupMsgReceiptList:o},GroupInfo:{GroupId:n}}=e,r=`${s.OuterConstant.CONV_GROUP}${n}`;null==o||o.forEach((e=>{const{TinyId:s,MsgClientTime:o,MsgRandom:i,ReadNum:a,UnreadNum:c}=e,d=`${s}-${o}-${i}`,u=S({conversationID:r,messageID:d}),l={groupID:n,messageID:d,readCount:0,unreadCount:0};u&&("number"==typeof a&&(u.readReceiptInfo.readCount=a,l.readCount=a),"number"==typeof c&&(u.readReceiptInfo.unreadCount=c,l.unreadCount=c),t.push(l))}))})),this._emitReadReceiptEventIfNeed(t)}_emitReadReceiptEventIfNeed(e){const{notificationCenter:t,OuterEvent:s}=this._core;e.length>0&&t.emitOuterEvent(s.MESSAGE_READ_RECEIPT_RECEIVED,{name:s.MESSAGE_READ_RECEIPT_RECEIVED,data:e})}_filterValidMessageSendByOther(e){return this._filterNeedReadReceiptMessages(e).filter((e=>{const{from:t}=e;return t!==this._core.common.getCurrentUserID()}))}_filterValidMessageSendByMe(e){const{OuterConstant:t}=this._core.constants;return this._filterNeedReadReceiptMessages(e).filter((e=>{const{from:s,status:o}=e;return s===this._core.common.getCurrentUserID()&&o===t.MessageStatus.SUCCESS}))}_filterNeedReadReceiptMessages(e){return e.filter((e=>!0===e.needReadReceipt))}dispose(){const{InnerEvent:{MESSAGE_PUSH:e},InnerEventSubType:{C2C_MESSAGE_READ_RECEIPT:t,GROUP_MESSAGE_READ_RECEIPT:s},notificationCenter:o}=this._core;o.unSubscribeInnerEvent(e,t,this._handleC2CMessageReadReceipt,this),o.unSubscribeInnerEvent(e,s,this._handleGroupMessageReadReceipt,this)}};const T=Object.assign(Object.assign({deleteMessage:[{required:!0,rules:["array"],allowEmpty:!1}],revokeMessage:[{required:!0,rules:["object"],allowEmpty:!1}],resendMessage:[{key:"message",required:!0,rules:["object"],allowEmpty:!1},{key:"options",required:!1,rules:["object"],allowEmpty:!1}],getMessageList:{conversationID:{required:!0,rules:["string"],allowEmpty:!1},nextReqMessageID:{required:!1,rules:["string"],allowEmpty:!0},count:{required:!1,rules:["number"],allowEmpty:!0}},getMessageListHopping:{conversationID:{required:!0,rules:["string"],allowEmpty:!1},sequence:{required:!1,rules:["number"],allowEmpty:!0},direction:{required:!1,rules:["number"],allowEmpty:!0},count:{required:!1,rules:["number"],allowEmpty:!0}},createTextAtMessage:{to:{required:!0,rules:["string"],allowEmpty:!1},conversationType:{required:!0,rules:["string"],allowEmpty:!1,customValidator:e=>"GROUP"===e||"conversationType should be GROUP."},payload:{required:!0,rules:["object"],allowEmpty:!1,customValidator:e=>{const t=function(e){var t;if("string"!=typeof(null==e?void 0:e.text)||"string"==typeof e.text&&0===(null===(t=null==e?void 0:e.text)||void 0===t?void 0:t.length))return"payload.text is invalid.";return!0}(e);return!0!==t?t:!((null==e?void 0:e.atUserList)&&!Array.isArray(e.atUserList))||"atUserList should be an array or undefind."}}},findMessage:[{required:!0,rules:["string"],allowEmpty:!1}],translateText:{sourceTextList:{required:!0,rules:["array"],allowEmpty:!1},sourceLanguage:{required:!0,rules:["string"],allowEmpty:!1},targetLanguage:{required:!0,rules:["string"],allowEmpty:!1}},createForwardMessage:{to:{required:!0,rules:["string"],allowEmpty:!1},conversationType:{required:!0,rules:["string"],allowEmpty:!1,customValidator:e=>!(!e.startsWith("C2C")&&!e.startsWith("GROUP"))||"conversationType is invalid."},payload:{required:!0,rules:["object"],allowEmpty:!1}},createLocationMessage:{to:{required:!0,rules:["string"],allowEmpty:!1},conversationType:{required:!0,rules:["string"],allowEmpty:!1},payload:{required:!0,rules:["object"],allowEmpty:!1,customValidator:e=>{const{utils:{isString:s,isNumber:o}}=t.core;return s(null==e?void 0:e.description)?o(null==e?void 0:e.longitude)?!!o(null==e?void 0:e.latitude)||"payload.latitude must be a number.":"payload.longitude must be a number.":"payload.description must be a string."}}}},{addMessageReaction:[{key:"message",required:!0,rules:["object"],allowEmpty:!1},{key:"reactionID",required:!0,rules:["string"],allowEmpty:!1}],removeMessageReaction:[{key:"message",required:!0,rules:["object"],allowEmpty:!1},{key:"reactionID",required:!0,rules:["string"],allowEmpty:!1}],getMessageReactions:{messageList:{required:!0,rules:["array"],allowEmpty:!1},maxUserCountPerReaction:{required:!1,rules:["number"],allowEmpty:!0,customValidator:e=>"number"!=typeof e?"maxUserCountPerReaction is invalid.":!(e<0||e>10)||"maxUserCountPerReaction should between [0, 10]."}},getAllUserListOfMessageReaction:{message:{required:!0,rules:["object"],allowEmpty:!1,customValidator:e=>"success"===e.status||"message is invalid."},reactionID:{required:!0,rules:["string"],allowEmpty:!1},nextSeq:{required:!1,rules:["number"],allowEmpty:!0},count:{required:!1,rules:["number"],allowEmpty:!0}}}),{sendMessageReadReceipt:[{required:!0,rules:["array"],allowEmpty:!1}],getMessageReadReceiptList:[{required:!0,rules:["array"],allowEmpty:!1}],getGroupMessageReadMemberList:{message:{required:!0,rules:["object"],allowEmpty:!1},filter:{required:!1,rules:["number"],allowEmpty:!0},count:{required:!1,rules:["number"],allowEmpty:!0},cursor:{required:!1,rules:["string"],allowEmpty:!0}}}),q=Object.assign(Object.assign({deleteMessage:!0,revokeMessage:!0,resendMessage:!0,getMessageList:!0,getMessageListHopping:!0,createTextAtMessage:!0,findMessage:!0,translateText:!0,createForwardMessage:!0,createLocationMessage:!0},{addMessageReaction:!0,removeMessageReaction:!0,getMessageReactions:!0,getAllUserListOfMessageReaction:!0}),{sendMessageReadReceipt:!0,getMessageReadReceiptList:!0,getGroupMessageReadMemberList:!0});class b{constructor(e){this._core=e}deleteMessage(t){return e(this,void 0,void 0,(function*(){const{to:e,messageIdentifiers:s}=t,o="openim.delete_c2c_msg_ramble",n={From_Account:this._core.common.getCurrentUserID(),To_Account:e,MsgKeyList:s},r=this._core.helper.generateProtocolData({servcmd:o,data:n}),i=`${r.head.seq}${o}`;return this._core.channel.sendPacket(r,{requestId:i})}))}revokeMessage(t){return e(this,void 0,void 0,(function*(){const{to:e,from:s,sequence:o,time:n,random:r}=t,i="openim.msgwithdraw",a={MsgInfo:{From_Account:s,To_Account:e,MsgSeq:o,MsgRandom:r,MsgTimeStamp:n}},c=this._core.helper.generateProtocolData({servcmd:i,data:a}),d=`${c.head.seq}${i}`;return this._core.channel.sendPacket(c,{requestId:d})}))}}class w{constructor(e){this._core=e}deleteMessage(t){return e(this,void 0,void 0,(function*(){const{to:e,messageIdentifiers:s}=t,o="group_open_http_svc.delete_group_ramble_msg_by_seq",n={GroupId:e,Deleter_Account:this._core.common.getCurrentUserID(),Seqs:s},r=this._core.helper.generateProtocolData({servcmd:o,data:n}),i=`${r.head.seq}${o}`;return this._core.channel.sendPacket(r,{requestId:i})}))}revokeMessage(t){return e(this,void 0,void 0,(function*(){const{to:e,sequence:s}=t,o="group_open_http_svc.group_msg_recall",n={GroupId:e,MsgSeqList:[{MsgSeq:s}]},r=this._core.helper.generateProtocolData({servcmd:o,data:n}),i=`${r.head.seq}${o}`;return this._core.channel.sendPacket(r,{requestId:i})}))}}class P{constructor(e){this._core=e}generateRevokeMessage(e){const{conversationID:t,sequence:s,random:o,tinyID:n,clientTime:r,revokeReason:i,revoker:a}=e;let c={};const{messageDataHandler:d}=this._core.message;return c=d.revokeMessage({conversationID:t,sequence:s,random:o,revoker:a}),c||(c={conversationID:t,sequence:s},n&&r&&o&&(c.ID=`${n}-${r}-${o}`)),c=Object.assign(Object.assign({},c),{revoker:a,revokeReason:i,revokerInfo:{userID:a,nick:"",avatar:""}}),c}updateRevokerInfo(t){return e(this,void 0,void 0,(function*(){const e=t.map((e=>e.revoker));try{const s=yield this._fetchUserInfos(e);s&&t.forEach((e=>{const{revoker:t}=e;s[t]&&(e.revokerInfo.nick=s[t].nick||"",e.revokerInfo.avatar=s[t].avatar||"",e.revokerInfo.userID=t)}))}catch(e){console.debug(e)}}))}filterValidMessages(e){return e.filter((e=>{const t=!this._core.helper.isEmpty(null==e?void 0:e.getElements()),s=1===(null==e?void 0:e.isPlaceMessage);if(!t){this._core.ssoLog.createSSOLogData({method:"emptyMessageBody"}).setLogInfo({message:`from:${e.from} to:${e.to} sequence:${e.sequence}`}).end()}return t&&!s}))}_fetchUserInfos(t){return e(this,void 0,void 0,(function*(){var e,s;const o=yield null===(e=this._core.user.userProfile)||void 0===e?void 0:e.getUserProfile({userIDList:t});return(null==o?void 0:o.data)?null===(s=o.data)||void 0===s?void 0:s.reduce(((e,{userID:t,nick:s,avatar:o})=>(e[t]={nick:s||"",avatar:o||""},e)),{}):null}))}}var N=new class{constructor(){this._core=null,this._c2cMessageAction=null,this._groupMessageAction=null}init(e){this._core=e,this._groupMessageAction=new w(e),this._c2cMessageAction=new b(e),this._messageHelper=new P(e);const{helper:t}=e;t.registerApi({apiName:"deleteMessage",context:this}),t.registerApi({apiName:"revokeMessage",context:this}),t.registerApi({apiName:"resendMessage",context:this}),t.registerApi({apiName:"findMessage",context:this})}deleteMessage(t){return e(this,void 0,void 0,(function*(){let e=[],s=[];const{conversationID:o,conversationType:n}=t[0],r=o.replace(n,"");if("@TIM#SYSTEM"===n)throw new this._core.helper.ChatError({code:v});if(t.forEach((t=>{const{conversationID:r,conversationType:i,status:a,_onlineOnlyFlag:c,sequence:d,random:u,time:l}=t||{};if("success"===a&&r===o&&i===n){if(!c){const t="C2C"===i?`${d}_${u}_${l}`:String(d);e.push(t)}s.push(t)}})),0===e.length)return this._handleDeleteMessageSuccess(s),{code:0,data:{messageList:s}};e.length>30&&(e=e.slice(0,30),s=s.slice(0,30));try{return"C2C"===n?yield this._c2cMessageAction.deleteMessage({to:r,messageIdentifiers:e}):yield this._groupMessageAction.deleteMessage({to:r,messageIdentifiers:e}),this._handleDeleteMessageSuccess(s),{code:0,data:{messageList:s}}}catch(e){const{errorCode:t}=e;throw new this._core.helper.ChatError({functionName:"deleteMessage",code:t})}}))}revokeMessage(t){return e(this,void 0,void 0,(function*(){var e;const s=this._core.ssoLog.createSSOLogData({method:"revokeMessage"}),{conversationType:o,isRevoked:n}=t;let r=null;if("@TIM#SYSTEM"===o)throw new this._core.helper.ChatError({message:"system message cannot be revoked"});if(n)throw new this._core.helper.ChatError({message:"message has been revoked"});s.setLogInfo({message:`type:${t.type} from:${t.from} to:${t.to}`});try{if(r="C2C"===o?yield this._c2cMessageAction.revokeMessage(t):yield this._groupMessageAction.revokeMessage(t),r){const{RecallRetList:o}=r,n=(null===(e=null==o?void 0:o[0])||void 0===e?void 0:e.RetCode)||0;if(0!==n)throw new this._core.helper.ChatError({code:n});return s.end(),yield this._handleRevokeMessageSuccess(t),{code:0,data:{message:t}}}}catch(e){const{errorCode:t}=e,s=new this._core.helper.ChatError({functionName:"revokeMessage",code:t});throw this._core.ssoLog.getSSOLogData("revokeMessage").setError(s).end(),s}}))}resendMessage(t,s){return e(this,void 0,void 0,(function*(){var e,o;return t.isResend=!0,t.status="unSend",null===(o=null===(e=this._core)||void 0===e?void 0:e.apiMap)||void 0===o?void 0:o.sendMessage(t,s)}))}findMessage(e){return this._core.message.messageDataHandler.findMessage(e)}_handleDeleteMessageSuccess(e){0!==e.length&&(e.forEach((e=>{e.isDeleted=!0;const t=this._core.message.messageDataHandler.getLocalMessageList(e.conversationID);null==t||t.forEach((t=>{t.ID===e.ID&&(t.isDeleted=!0)}))})),this._core.notificationCenter.emitInnerEvent(this._core.InnerEvent.MESSAGE_DELETED,e[0].conversationID))}_handleRevokeMessageSuccess(t){return e(this,void 0,void 0,(function*(){var e;const s=null===(e=this._core.store.get("login"))||void 0===e?void 0:e.userId,{conversationID:o,sequence:n,random:r}=t;this._core.message.messageDataHandler.revokeMessage({conversationID:o,sequence:n,random:r,revoker:s}),yield this._messageHelper.updateRevokerInfo([t])}))}};class k{static parseServerPushElement(e){const{MsgContent:t={}}=e,{Index:s,Data:o}=t;return new k({index:s,data:o})}constructor(e){this.type=s.MSG_FACE;const{index:t,data:o}=e;this.content={index:t,data:o}}validateBeforeSend(){var e,t;return"number"==typeof(null===(e=this.content)||void 0===e?void 0:e.index)&&"string"==typeof(null===(t=this.content)||void 0===t?void 0:t.data)?{isValid:!0}:{isValid:!1,error:{message:"content is invalid"}}}transformToServerFormat(e){const{isMergerMessage:t=!1}=e||{},s=t?this.payload:this.content,{index:o,data:n}=s;return{MsgType:this.type,MsgContent:{Index:o,Data:n}}}}class x{static parseServerPushElement(e){const{MsgContent:t={}}=e,{Desc:s,Longitude:o,Latitude:n}=t;return new x({description:s,longitude:o,latitude:n})}constructor(e){this.type=s.MSG_LOCATION;const{description:t,longitude:o,latitude:n}=e;this.content={description:t,longitude:o,latitude:n}}validateBeforeSend(){return{isValid:!0}}transformToServerFormat(e){const{isMergerMessage:t=!1}=e||{},s=t?this.payload:this.content,{description:o,longitude:n,latitude:r}=s;return{MsgType:this.type,MsgContent:{Desc:o,Longitude:n,Latitude:r}}}}var G=new class{init(e){this._core=e,e.message.messageFactory.registerElementClass(s.MSG_FACE,k),e.message.messageFactory.registerElementClass(s.MSG_LOCATION,x),e.helper.registerApi({apiName:"createFaceMessage",context:this}),e.helper.registerApi({apiName:"createTextAtMessage",context:this}),e.helper.registerApi({apiName:"createForwardMessage",context:this}),e.helper.registerApi({apiName:"createLocationMessage",context:this})}createFaceMessage(e){if(!e)return null;const{index:t,data:s}=(null==e?void 0:e.payload)||{},o=new k({index:t,data:s}),n=this._core.common.getCurrentUserID(),r=this._core.message.messageFactory.createMessage(Object.assign(Object.assign({},e),{from:n}));return r.setElement(o),r}createTextAtMessage(e){const{atUserList:t}=(null==e?void 0:e.payload)||{},s=this._core.apiMap.createTextMessage(e),{OuterConstant:o}=this._core;if(!s)return null;if(Array.isArray(t)){const e=[],n=[];t.forEach((t=>{t!==o.MSG_AT_ALL?(e.push({GroupAtAllFlag:i,GroupAt_Account:t}),n.push(t)):(e.push({GroupAtAllFlag:a}),n.push(o.MSG_AT_ALL))})),s._groupAtInfoList=e,s.atUserList=n}return s}createForwardMessage(e){const{helper:t,OuterConstant:s}=this._core,{to:o,conversationType:n,priority:r,payload:i,needReadReceipt:a,receiverList:c,cloudCustomData:d="",isSupportExtension:u=!1}=e;if(!Array.isArray(i._elements))throw new t.ChatError({functionName:"createForwardMessage",code:2454});if(i.type===s.MSG_GRP_TIP)throw new t.ChatError({functionName:"createForwardMessage",code:2453});const l=this._core.common.getCurrentUserID(),g=this._core.message.messageFactory.createMessage({to:o,from:l,conversationType:n,isPlaceMessage:0,priority:r,payload:i,needReadReceipt:a,isSupportExtension:u,cloudCustomData:d,receiverList:c});return g.setRelayFlag(!0),g.setElement(i._elements[0]),g}createLocationMessage(e){if(!e)return null;const{description:t,longitude:s,latitude:o}=(null==e?void 0:e.payload)||{},n=new x({description:t,longitude:s,latitude:o}),r=this._core.common.getCurrentUserID(),i=this._core.message.messageFactory.createMessage(Object.assign(Object.assign({},e),{from:r}));return i.setElement(n),i}};class U{init(e){this._messageHelper=new P(e),this._core=e;const{notificationCenter:t,InnerEvent:{MESSAGE_PUSH:s},InnerEventSubType:{C2C_REVOKED_MESSAGE:o},helper:{registerWorkflowStep:n},constants:{WORKFLOW_NAME:r,WORKFLOW_STEP:i}}=e;t.subscribeInnerEvent(s,o,this._handleC2CNotifyMessage,this),n(r.SYNC_SERVER_INFO_AFTER_RE_ONLINE,i.HANDLE_C2C_REVOKED_MESSAGE_FROM_SYNC_UNREAD,this._handleC2CRevokeMessagesFromUnreadMessageSync,this)}_handleC2CNotifyMessage(e){const{C2cNotifyMsgArray:t}=e;null==t||t.forEach((e=>{Object.keys(e).includes("WithdrawC2cMsgNotify")&&this._handleC2CRevokeMessage(e)}))}_handleC2CRevokeMessage(t){return e(this,void 0,void 0,(function*(){try{const{WithdrawC2cMsgNotify:{C2cWithdrawInfoArray:e}}=t;yield this._parseAndEmitC2CRevokedMessages(e)}catch(e){console.debug(e)}}))}_parseAndEmitC2CRevokedMessages(t){return e(this,void 0,void 0,(function*(){const e=[],{notificationCenter:s,OuterEvent:o,common:{getCurrentUserID:n}}=this._core;t.forEach((t=>{const{MsgRand:s,MsgSeq:o,To_Account:r,From_Account:i,RevokerInfo:{Revoker_Account:a,Revoke_Reason:c,Reason:d=c}}=t,u=n()===i?`C2C${r}`:`C2C${i}`,l=this._messageHelper.generateRevokeMessage({conversationID:u,sequence:o,random:s,revoker:a,revokeReason:d});e.push(l)})),e.length>0&&(yield this._messageHelper.updateRevokerInfo(e),s.emitOuterEvent(o.MESSAGE_REVOKED,{name:o.MESSAGE_REVOKED,data:e}))}))}_handleC2CRevokeMessagesFromUnreadMessageSync(t){return e(this,void 0,void 0,(function*(){const{revokedMessageList:e}=t.result;yield this._parseAndEmitC2CRevokedMessages(e)}))}dispose(){const{notificationCenter:e,InnerEvent:{MESSAGE_PUSH:t},InnerEventSubType:{C2C_REVOKED_MESSAGE:s}}=this._core;e.unSubscribeInnerEvent(t,s,this._handleC2CNotifyMessage,this)}}class F{init(e){this._messageHelper=new P(e),this._core=e;const{notificationCenter:t,InnerEvent:{MESSAGE_PUSH:s},InnerEventSubType:{GROUP_MESSAGE_REVOKED:o}}=e;t.subscribeInnerEvent(s,o,this._handleGroupNotifyMessage,this)}_handleGroupNotifyMessage(e){const{GroupTips:t}=e;null==t||t.forEach((e=>{var t;Array.isArray(null===(t=null==e?void 0:e.MsgBody)||void 0===t?void 0:t.GroupWithdrawInfoArray)&&this._handleGroupRevokeMessage(e)}))}_handleGroupRevokeMessage(t){return e(this,void 0,void 0,(function*(){try{const{RevokerInfo:e,MsgBody:{GroupWithdrawInfoArray:s}}=t,o=[],{notificationCenter:n,OuterEvent:r,InnerEvent:i}=this._core;s.forEach((t=>{const{Random:s,MsgSeq:n,GroupId:r,MsgClientTime:i,TinyId:a,TopicId:c,RevokerInfo:{Revoker_Account:d=(null==e?void 0:e.Revoker_Account)||"",Reason:u=(null==e?void 0:e.Reason)||""}}=t,l=c?`GROUP${c}`:`GROUP${r}`,g=this._messageHelper.generateRevokeMessage({conversationID:l,sequence:n,random:s,tinyID:a,clientTime:i,revoker:d,revokeReason:u});o.push(g)})),0!==o.length&&(yield this._messageHelper.updateRevokerInfo(o),n.emitOuterEvent(r.MESSAGE_REVOKED,{name:r.MESSAGE_REVOKED,data:o}))}catch(e){console.debug(e)}}))}dispose(){const{notificationCenter:e,InnerEvent:{MESSAGE_PUSH:t},InnerEventSubType:{GROUP_MESSAGE_REVOKED:s}}=this._core;e.unSubscribeInnerEvent(t,s,this._handleGroupNotifyMessage,this)}}var H=new class{constructor(){this._c2cMessageReceiver=new U,this._groupMessageReceiver=new F}init(e){this._c2cMessageReceiver.init(e),this._groupMessageReceiver.init(e)}dispose(){this._c2cMessageReceiver.dispose(),this._groupMessageReceiver.dispose()}};class ${constructor(e){this._lastMessageSequenceMapOnDisconnect=new Map,this._core=e,this._messageHelper=new P(e)}getRoamingMessagesByAnchor(t){return e(this,void 0,void 0,(function*(){try{const e=this._core.ssoLog.createSSOLogData({method:"getRoamingMessagesByAnchor"}),{conversationID:s,count:r,direction:i,sequence:a}=t,c=s.replace(f,"");let d=a;if(i===n.BACKWARD){if("number"!=typeof a)return{messageList:[],hasNoMoreHistoryMessage:!1,nextReqMessageIDFromServer:""};d=a+r-1}const u={GroupId:c,ReqMsgNumber:r,WithRecalledMsg:1,Version:1};d&&(u.ReqMsgSeq=d);const l="group_open_http_svc.group_msg_get",g=this._core.helper.generateProtocolData({servcmd:l,data:u}),m=`${g.head.seq}${l}`,h=yield this._core.channel.sendPacket(g,{requestId:m});if(h){const{RspMsgList:t=[],NextReqMsgSeq:s=0,IsFinished:n,InvisibleMsgSeq:r}=h;e.setLogInfo({message:`groupID:${c} sequence:${a} reqSeq:${d} direction:${i}\n complete:${n} nextSequence:${s} remoteMsgCount:${t.length} invisibleSequenceList:${r}`}).end();const u=[];for(let e=0;e<t.length;e++){const s=t[e],o=this._parseMessage(s);u.push(o)}u.reverse();const l=[o.NO_MORE_DATA,o.DATA_HAS_EXPIRED].includes(n);return{messageList:this._messageHelper.filterValidMessages(u),invisibleSequenceList:r,nextReqMessageIDFromServer:s,hasNoMoreHistoryMessage:l}}}catch(e){const t=new this._core.helper.ChatError({code:null==e?void 0:e.code});this._core.ssoLog.getSSOLogData("getRoamingMessagesByAnchor").setError(t).end()}}))}recoverHistoryMessage(t){return e(this,void 0,void 0,(function*(){const{message:{messageReceiver:s,messageDataHandler:o},notificationCenter:r,OuterEvent:i,constants:{OuterConstant:a}}=this._core,c=[];null==t||t.forEach((t=>e(this,void 0,void 0,(function*(){const{conversationID:e,lastMessage:d}=t;let u=this._getLocalLastMessageSequence(e);const l=d.lastSequence;if(this._shouldRecoverHistory({localLastMessageSequence:u,serverLastMessageSequence:l})){const t=l-u;let a=!1;const c=Math.ceil(t/20);for(let t=0;t<c;t++)try{const t=l-u,c=Math.min(20,t),d=yield this.getRoamingMessagesByAnchor({conversationID:e,sequence:u+c,direction:n.FORWARD,count:c}),{nextReqMessageIDFromServer:g,hasNoMoreHistoryMessage:m,messageList:h}=d;a=m&&g<0,u=h[h.length-1].sequence;const p=[];if(Array.isArray(h)&&(h.forEach((e=>{s.groupMessageReceiver.updateMessageProfile(e);o.storeConversationMessage(e)&&p.push(e)})),p.length>0&&r.emitOuterEvent(i.MESSAGE_RECEIVED,{name:i.MESSAGE_RECEIVED,data:p})),a)break}catch(e){console.debug(e);break}}else c.push(e.replace(a.CONV_GROUP,""))})))),this._recoverGroupRevokeNotice(c)}))}updateLastMessageSequenceMapOnDisconnect(){const e=this._core.message.messageDataHandler.getContinuousMessagesByConversation();for(const[t,s]of e){if(t.startsWith("C2C"))continue;const e=Array.from(s.values());if((null==e?void 0:e.length)>0){const s=e[e.length-1].sequence;this._lastMessageSequenceMapOnDisconnect.set(t,s)}}}_shouldRecoverHistory(e){const{localLastMessageSequence:t,serverLastMessageSequence:s}=e;if("number"!=typeof t||"number"!=typeof s)return!1;const o=s-t;return 0!==s&&t&&(o>=R&&o<E)}_getLocalLastMessageSequence(e){if(this._lastMessageSequenceMapOnDisconnect.has(e))return this._lastMessageSequenceMapOnDisconnect.get(e);const t=this._core.message.messageDataHandler.getLocalMessageList(e),s=t[t.length-1];return null==s?void 0:s.sequence}_parseMessage(e){const{constants:{OuterConstant:t}}=this._core,s=f;4===e.Event&&(e.MsgBody.MsgType=t.MSG_GRP_TIP);const o=this._core.message.messageHelper.parseServerGroupMessage(e),n=this._core.message.messageFactory.createMessage(Object.assign(Object.assign({},o),{conversationType:s,flow:"in"}));return n.setElement(o.elements),n}_recoverGroupRevokeNotice(e){const t=this._filterValidGroupIDList(e);if(0===t.length)return;const s=Math.min(Math.ceil(t.length/10),5);Promise.all(Array.from({length:s},((e,s)=>{const o=10*s,n=Math.min(o+10,t.length);return this._fetchGroupRevokeNotice(t.slice(o,n))}))).catch((e=>console.error(e)))}_fetchGroupRevokeNotice(s){return e(this,void 0,void 0,(function*(){var o;try{const n=yield function(s){return e(this,void 0,void 0,(function*(){const{appStore:e,constants:{OuterConstant:o},common:n}=t.core,r=e.groupStore.getGroupMap(),i={NotifyReqList:s.map((e=>{const s=r.get(e);return{NotifyType:1,Limit:20,Type:n.isCommunity({type:s.type,groupID:e})?o.GRP_COMMUNITY:void 0,GroupId:e,BeginTime:(null==s?void 0:s._lastRevokedTime)||0,EndTime:1e3*t.core.common.timeManager.getServerTimeMs()}}))||[]};return n.buildAndSendPacket({servcmd:"group_open_http_svc.batch_get_group_notify",data:i})}))}(s);if(n){const e=[];null===(o=null==n?void 0:n.NotifyRspList)||void 0===o||o.forEach((t=>{const{GroupId:s,NotifyMsgList:o}=t,n=this._parseServerRevokeMessageList({groupID:s,serverRevokeMessageList:o});e.push(...n)})),0!==e.length&&(yield this._emitMessageRevokedEvent(e))}}catch(e){console.error(e)}}))}_parseServerRevokeMessageList(e){const{serverRevokeMessageList:t,groupID:s}=e,o=[];return null==t||t.forEach((e=>{const{ClientTime:t,MsgSeq:n,Random:r,RevokerInfo:{Revoker_Account:i="",Reason:a=""}}=e,c=`GROUP${s}`,d=this._messageHelper.generateRevokeMessage({conversationID:c,sequence:n,random:r,clientTime:t,revoker:i,revokeReason:a});o.push(d)})),o}_filterValidGroupIDList(e){const{constants:{OuterConstant:t}}=this._core,s=this._core.appStore.groupStore.getGroupMap();return(null==e?void 0:e.filter((e=>{if(!s.has(e))return!1;const o=s.get(e);return(null==o?void 0:o.type)!==t.GRP_AVCHATROOM&&!(null==o?void 0:o.isSupportTopic)})))||[]}_emitMessageRevokedEvent(t){return e(this,void 0,void 0,(function*(){const{notificationCenter:e,OuterEvent:s}=this._core;yield this._messageHelper.updateRevokerInfo(t),e.emitOuterEvent(s.MESSAGE_REVOKED,{name:s.MESSAGE_REVOKED,data:t})}))}}class V{constructor(e){this._historyMessageListFetchAnchors=new Map,this._core=e,this._messageHelper=new P(e)}getRoamingMessagesByAnchor(s){return e(this,void 0,void 0,(function*(){var o;try{const{conversationID:n,count:r,messageID:i,time:a,direction:c}=s;let d=a,u="";if(!a){const e=i?this._core.message.messageDataHandler.findMessage(i):null;if(d=(null==e?void 0:e.time)||0,i&&this._historyMessageListFetchAnchors.has(n)){const e=this._historyMessageListFetchAnchors.get(n);d=e.lastMessageTime,u=e.messageKey}}const l=n.replace(M,""),g=yield function(s){return e(this,void 0,void 0,(function*(){const{peerAccount:e,count:o,lastMessageTime:n,messageKey:r,direction:i}=s,a={Peer_Account:e,MaxCnt:o,WithRecalledMsg:1,LastMsgTime:n,MsgKey:r,GetDirection:i};return t.core.common.buildAndSendPacket({servcmd:"openim.getroammsg",data:a})}))}({count:r,lastMessageTime:d,messageKey:u,peerAccount:l,direction:c});if(g){const{MsgList:e=[],Complete:t,MsgKey:s,LastMsgTime:r}=g;this._historyMessageListFetchAnchors.set(n,{messageKey:s,lastMessageTime:r});const i=[];for(let t=0;t<e.length;t++){const s=e[t],o=this._parseMessage(s);i.push(o)}const a=this._messageHelper.filterValidMessages(i);return{messageList:a,nextReqMessageIDFromServer:null===(o=a[0])||void 0===o?void 0:o.ID,lastMessageTime:r,hasNoMoreHistoryMessage:1===t}}}catch(e){throw new this._core.helper.ChatError({code:null==e?void 0:e.code})}}))}_parseMessage(e){const t=M,s=this._core.message.messageHelper.parseServerPushMessage(e),o=this._core.message.messageFactory.createMessage(Object.assign(Object.assign({},s),{conversationType:t,flow:"in"}));return o.setElement(s.elements),o}}var K=new class{constructor(){this._clearedConversations=new Set,this._fetchedCompleteConversations=new Set}init(e){this._core=e,this._groupMessageHistory=new $(e),this._c2cMessageHistory=new V(e),this._messageHelper=new P(e);const{InnerEvent:t,notificationCenter:s,constants:o}=e;e.helper.registerApi({apiName:"getMessageList",context:this}),e.helper.registerApi({apiName:"getMessageListHopping",context:this}),e.helper.registerWorkflowStep(o.WORKFLOW_NAME.SYNC_SERVER_INFO_AFTER_RE_ONLINE,o.WORKFLOW_STEP.HISTORY_MESSAGE_RECOVER,this._recoverHistoryMessage,this),s.subscribeInnerEvent(t.SOCKET_DISCONNECTED,this._handleSocketDisconnected,this)}getMessageList(s){return e(this,void 0,void 0,(function*(){try{const e=this._core.ssoLog.createSSOLogData({method:"getMessageList"});let{conversationID:o,nextReqMessageID:r}=s;const i=y;if("@TIM#SYSTEM"===o)return{code:0,data:{messageList:[],isCompleted:!1,nextMessageSeq:""}};const a=this._getAvailableLocalMessagesCount({conversationID:o,nextReqMessageID:r});if(this._needFetchHistoryMessageList({conversationID:o,availableLocalMessagesCount:a,targetCount:i})){let s=null;if(o.startsWith(f)?s=yield this._groupMessageHistory.getRoamingMessagesByAnchor({conversationID:o,sequence:Number(r),count:i,direction:n.FORWARD}):o.startsWith(M)&&(s=yield this._c2cMessageHistory.getRoamingMessagesByAnchor({conversationID:o,messageID:r,count:i,direction:n.FORWARD})),s){const{nextReqMessageIDFromServer:n,hasNoMoreHistoryMessage:i,messageList:c}=s,d=this._core.message.messageDataHandler.prependLocalMessageList({messageList:c,conversationID:o});!function(e){const{appStore:s,message:o,OuterConstant:n}=t.core,r=s.conversationStore.getConversation(e),i=o.messageDataHandler.getLocalMessageList(e);if(!r||0===i.length||e===n.CONV_SYSTEM)return;const a=[];for(let e=0;e<i.length;e++)"in"!==i[e].flow?"out"!==i[e].flow||i[e].isRead||i[e].setIsRead(!0):a.push(i[e]);let c=0;if(r.type===n.CONV_C2C){const e=a.slice(-r.unreadCount).filter((e=>e.isRevoked)).length;c=a.length-r.unreadCount-e}else c=a.length-r.unreadCount;for(let e=0;e<c&&!a[e].isRead;e++)a[e].setIsRead(!0)}(o),yield C(o),o.startsWith(M)&&(yield I({messageList:c,conversationID:o}));const u=this._core.message.messageDataHandler.getLocalMessageList(o).slice(0,d.length+a),l=u.filter((e=>e.isRevoked));yield this._messageHelper.updateRevokerInfo(l);const g={nextReqMessageID:i?"":String(n),messageList:u,isCompleted:i},m=u.map((e=>e.sequence));return e.setLogInfo({message:`conversationID: ${o} nextReqMessageID: ${r} \n availableLocalMessagesCount: ${a} sequenceList: ${JSON.stringify(m)} `}).end(),{code:0,data:g}}return{code:0,data:{messageList:[],isCompleted:!1,nextMessageSeq:""}}}e.setLogInfo({message:`conversationID: ${o} nextReqMessageID: ${r} availableLocalMessagesCount: ${a}}`}).end();return{code:0,data:yield this._getMessageListFromMemory({conversationID:o,nextReqMessageID:r,count:i})}}catch(e){const t=new this._core.helper.ChatError({code:null==e?void 0:e.code});this._core.ssoLog.getSSOLogData("getMessageList").setError(t).end(),console.debug(t)}}))}getMessageListHopping(t){return e(this,void 0,void 0,(function*(){var e,s;const{conversationID:o,sequence:r,time:i,direction:a=n.FORWARD}=t,{isEmpty:c}=this._core.helper;if(![n.BACKWARD,n.FORWARD].includes(a))throw new this._core.helper.ChatError({message:"direction must be 0 or 1"});let{count:d=y}=t;d=d>y?y:d;let u=null;if(o.startsWith(f)){if(u=yield this._groupMessageHistory.getRoamingMessagesByAnchor({conversationID:o,sequence:r,count:d,direction:a}),u){const{nextReqMessageIDFromServer:t,hasNoMoreHistoryMessage:o,messageList:i,invisibleSequenceList:d}=u;if(this._core.message.messageDataHandler.storeSparseMessageList(i),a===n.FORWARD){const e=o&&t<1;return{code:0,data:{messageList:i,isCompleted:e,nextMessageSeq:e?"":t}}}if(a===n.BACKWARD){if(c(i)&&c(d))return{code:0,data:{messageList:[],isCompleted:!0,nextMessageSeq:""}};const t=(null===(e=null==i?void 0:i[i.length-1])||void 0===e?void 0:e.sequence)||0,o=(null===(s=null==d?void 0:d[d.length-1])||void 0===s?void 0:s.sequence)||0;return{code:0,data:{messageList:i.filter((e=>e.sequence>=r)),isCompleted:!1,nextMessageSeq:Math.max(t,o)+1}}}return{code:0,data:u}}}else if(o.startsWith(M)&&(u=yield this._c2cMessageHistory.getRoamingMessagesByAnchor({conversationID:o,count:d+1,time:i,direction:a}),u)){const{messageList:e,lastMessageTime:t,hasNoMoreHistoryMessage:s}=u;return s||(a===n.FORWARD?e.shift():e.pop()),this._core.message.messageDataHandler.storeSparseMessageList(e),{code:0,data:{messageList:e,isCompleted:s,nextMessageTime:s?"":t}}}}))}_getAvailableLocalMessagesCount({conversationID:e,nextReqMessageID:t}){const s=this._core.message.messageDataHandler.getLocalMessageList(e),{length:o}=s;if(!t)return o;let n=-1;return(null==e?void 0:e.startsWith(M))?n=s.findIndex((e=>e.ID===t)):(null==e?void 0:e.startsWith(f))&&(n=s.findIndex((e=>t.includes("-")?e.ID===t:String(e.sequence)===t))),-1===n?0:n}_needFetchHistoryMessageList({conversationID:e,availableLocalMessagesCount:t,targetCount:s}){return!!this._clearedConversations.has(e)||t<=s&&!this._fetchedCompleteConversations.has(e)}_getMessageListFromMemory(t){return e(this,arguments,void 0,(function*({conversationID:e,nextReqMessageID:t,count:s}){const o=this._core.message.messageDataHandler.getLocalMessageList(e),n=o.length;let r=n,i={isCompleted:!1,nextReqMessageID:"",messageList:[]},a=0,c=n;return t?t&&(c=o.findIndex((s=>e.startsWith(M)?s.ID===t:String(s.sequence)===t)),a=c>s?c-s:0,r=c):a=n>s?n-s:0,i.nextReqMessageID=0===a?"":this._generateNextReqMessageID({conversationID:e,targetIndex:a}),i.messageList=o.slice(a,c),i.isCompleted=r<=s,e.startsWith(M)&&(yield C(e),yield I({messageList:i.messageList,conversationID:e})),i}))}_generateNextReqMessageID({conversationID:e,targetIndex:t}){const s=this._core.message.messageDataHandler.getLocalMessageList(e);return e.startsWith("C2C")?s[t].ID:String(s[t].sequence)}_recoverHistoryMessage(){const{appStore:e,constants:{OuterConstant:{GRP_AVCHATROOM:t}}}=this._core,s=e.conversationStore.getConversationMap()||{};if(s instanceof Map){const e=[...s.values()].filter((e=>e.type===f&&e.groupProfile.type!==t));this._groupMessageHistory.recoverHistoryMessage(e)}}_handleSocketDisconnected(){this._groupMessageHistory.updateLastMessageSequenceMapOnDisconnect()}dispose(){const{notificationCenter:e,InnerEvent:t}=this._core;e.unSubscribeInnerEvent(t.SOCKET_DISCONNECTED,this._handleSocketDisconnected,this)}};var B=new class{constructor(){this._core=null}init(e){this._core=e;const{helper:t}=e;t.registerApi({apiName:"translateText",context:this})}translateText(t){return e(this,void 0,void 0,(function*(){try{const{sourceLanguage:s,sourceTextList:o,targetLanguage:n}=t,r=yield function(t,s){return e(this,void 0,void 0,(function*(){var e,o;const{sourceTextList:n,sourceLanguage:r,targetLanguage:i}=t,{store:a,helper:c,channel:d}=s,u="im_open_translate.ws_batch_trans_text",l={SourceText:n,Source:r,Target:i,FromAccount:null===(e=a.get("login"))||void 0===e?void 0:e.tinyID,SDKAppID:null===(o=a.get("instance"))||void 0===o?void 0:o.sdkAppId},g=c.generateProtocolData({servcmd:u,data:l}),m=`${g.head.seq}${u}`,h=yield d.sendPacket(g,{requestId:m});if(h){const{CmdErrorCode:e,TargetText:t}=h;return{cmdErrorCode:e,translatedTextList:t}}}))}({sourceLanguage:s,sourceTextList:o,targetLanguage:n},this._core);if(r){const{cmdErrorCode:{ErrorCode:e,ErrorInfo:t},translatedTextList:s}=r;if(0===e)return{code:0,data:{translatedTextList:s}};throw{errorCode:e,errorInfo:t,message:t}}}catch(e){const{errorCode:t,errorInfo:s}=e||{};throw new this._core.helper.ChatError({functionName:"translateText",code:t,message:s})}}))}};var W=new class{init(e){this._core=e,e.common.registerApi({apiName:"convertVoiceToText",context:this})}convertVoiceToText(s){return e(this,void 0,void 0,(function*(){var e,o;const{message:n,language:r=c.ZH_PY}=s;let{url:i}=n.payload||{};const a=null===(e=this._core.store.get("login"))||void 0===e?void 0:e.userID;n.from===a&&"out"===n.flow&&(i=n.payload.remoteAudioUrl),this._validateVoiceFormat(i);const d=(null===(o=p.exec(i))||void 0===o?void 0:o[1])||"mp3",u=h[r]||m;try{const e=yield function(e){var s;const{store:o,common:n}=t.core,{url:r,format:i,serverLanguageType:a}=e,c={BytesUrl:r,BytesEngServiceType:a,BytesVoiceFormat:i,Uint32Sdkappid:null===(s=o.get("instance"))||void 0===s?void 0:s.sdkAppId,Uint64SourceType:0};return n.buildAndSendPacket({servcmd:"im_open_speech.ws_sentence_recognition",data:c})}({url:i,format:d,serverLanguageType:u});if(e){const{CmdErrorCode:t,BytesResult:s}=e;if(0===t.ErrorCode)return{code:0,data:{result:s}};throw{code:t.ErrorCode,message:t.ErrorInfo}}}catch(e){const{code:t,message:s}=e||{},o=new this._core.common.ChatError({functionName:"convertVoiceToText",code:t,message:s});console.error(o),this._core.ssoLog.createSSOLogData({method:"convertVoiceToText"}).setError(o).end()}}))}_validateVoiceFormat(e){if(!p.test(e))throw new this._core.common.ChatError({code:2119})}};class j{constructor(e){const{constants:s,common:o,utils:n}=t.core,{CONV_C2C:r,CONV_GROUP:i}=s.OuterConstant,{ID:a,tinyID:c,from:d,to:u,clientTime:l=o.timeManager.getServerTimeSeconds()||0,random:g,sequence:m,cloudCustomData:h="",nick:p="",avatar:_="",clientSequence:v,conversationType:M,groupID:f,_elements:y,time:R}=e;this.ID=a||`${c}-${l}-${g}`,this.messageRandom=g,this.from=d,this.messageSender=d,this.time=R,this.messageSequence=m,this.clientSequence=v||m,this.clientTime=l,this.cloudCustomData=h,this.messageReceiver=u,this.avatar=_,this.nick=p;const E=n.deepCopyWithMethods(y);E.forEach((e=>{e.payload=e.content,delete e.content})),this.messageBody=E,a?M.startsWith(r)?this.receiverUserID=u:M.startsWith(i)&&(this.receiverGroupID=u):f?(this.receiverGroupID=f,this.messageReceiver=f):u&&(this.receiverUserID=u,this.messageReceiver=u)}transformElementsToServerFormat(){return this.messageBody?Array.isArray(this.messageBody)?this.messageBody.map((e=>e.transformToServerFormat({isMergerMessage:!0}))):this.messageBody.transformToServerFormat({isMergerMessage:!0}):null}}class Y{static parseServerPushElement(e){const{MsgContent:t}=e,{MsgList:s=[],CompatibleText:o,AbstractList:n,Title:r,PbMsgKey:i,JsonMsgKey:a}=t||{},c=s.map((e=>A(e)));return new Y({messageList:c,title:r,abstractList:n,compatibleText:o,pbDownloadKey:i,downloadKey:a})}constructor(e){this.type=t.core.constants.OuterConstant.MSG_MERGER;const{messageList:s,title:o,abstractList:n,compatibleText:r,pbDownloadKey:i="",downloadKey:a="",version:c=0,layersOverLimit:d=!1}=e,u=[];s.forEach((e=>{if(e){const t=new j(e);u.push(t)}})),this.content={messageList:u,title:o,abstractList:n,compatibleText:r,version:c,downloadKey:a,pbDownloadKey:i,layersOverLimit:d}}validateBeforeSend(){const{isEmpty:e}=t.core.helper;return e(this.content.messageList)?{isValid:!1,error:{message:"content is invalid"}}:{isValid:!0}}transformToServerFormat(e){const{isMergerMessage:t=!1}=e||{},s=t?this.payload:this.content,{abstractList:o,compatibleText:n,downloadKey:r,layersOverLimit:i,pbDownloadKey:a,title:c,version:d,messageList:u}=s;return{MsgType:this.type,MsgContent:{AbstractList:o,CompatibleText:n,JsonMsgKey:r,LayersOverLimit:i,PbMsgKey:a,Title:c,Version:d,MsgList:D(u)}}}}var J=new class{init(e){this._core=e;const{message:t,helper:s,constants:{OuterConstant:o}}=e;t.messageFactory.registerElementClass(o.MSG_MERGER,Y),s.registerApi({apiName:"createMergerMessage",context:this}),s.registerApi({apiName:"sendMessage",context:this,matcher:e=>e[0].type===o.MSG_MERGER}),s.registerApi({apiName:"downloadMergerMessage",context:this})}createMergerMessage(e){const{common:t}=this._core;if(!e)return null;const s=new Y(e.payload),o=t.getCurrentUserID(),n=this._core.message.messageFactory.createMessage(Object.assign(Object.assign({},e),{from:o}));return n.setRelayFlag(!0),n.setElement(s),n}sendMessage(s,o){return e(this,void 0,void 0,(function*(){var n,r,i;try{const a=function(e){let s="utf-8";t.core.helper.IN_BROWSER&&document&&(s=document.charset.toLowerCase());let o,n=0,r=0;if(r=e.length,"utf-8"===s||"utf8"===s)for(let t=0;t<r;t++)o=e.codePointAt(t),o<=127?n+=1:o<=2047?n+=2:o<=65535?n+=3:(n+=4,t++);else if("utf-16"===s||"utf16"===s)for(let t=0;t<r;t++)o=e.codePointAt(t),o<=65535?n+=2:(n+=4,t++);else n=e.replace(/[^\x00-\xff]/g,"aa").length;return n}(JSON.stringify(s));let c=s,d=null;if(a>11264){c=this._core.utils.deepCopyWithMethods(s);try{const{JsonMsgKey:s,PbMsgKey:o}=yield function(s){return e(this,void 0,void 0,(function*(){const{payload:{messageList:e}}=s,o={MsgList:D(e)};return t.core.common.buildAndSendPacket({servcmd:"im_long_msg.save_relay_json_msg",data:o})}))}(c),{payload:n}=c;d=new Y(Object.assign(Object.assign({},n),{messageList:[],downloadKey:s,pbDownloadKey:o})),c.setElement(d)}catch(e){console.error(e)}}const{data:{message:u}}=yield null===(i=null===(r=null===(n=this._core)||void 0===n?void 0:n.message)||void 0===r?void 0:r.messageSender)||void 0===i?void 0:i.sendMessage(c,o);return d&&u.setElement(s._elements),{code:0,data:{message:u}}}catch(e){throw console.error(e),e}}))}downloadMergerMessage(s){return e(this,void 0,void 0,(function*(){try{const o=s.payload,{downloadKey:n,pbDownload:r,type:i,messageList:a}=o,c=function(e,t){var s={};for(var o in e)Object.prototype.hasOwnProperty.call(e,o)&&t.indexOf(o)<0&&(s[o]=e[o]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var n=0;for(o=Object.getOwnPropertySymbols(e);n<o.length;n++)t.indexOf(o[n])<0&&Object.prototype.propertyIsEnumerable.call(e,o[n])&&(s[o[n]]=e[o[n]])}return s}(o,["downloadKey","pbDownload","type","messageList"]),d=yield function(s){return e(this,void 0,void 0,(function*(){return t.core.common.buildAndSendPacket({servcmd:"im_long_msg.get_relay_json_msg",data:{JsonMsgKey:s}})}))}(n),{MsgList:u}=d||{},l=null==u?void 0:u.map((e=>{const t=A(e);return new j(t)}));return"function"==typeof s.isOnlineMessage?s.setElement({type:s.type,content:Object.assign({messageList:l},c)}):(s.payload.messageList=l,s.payload.downloadKey="",s.payload.pbDownloadKey=""),s}catch(e){console.error(e)}}))}};return new class{install(e){this._core=e,t.init(e),N.init(e),G.init(e),H.init(e),K.init(e),L.init(e),B.init(e),W.init(e),O.init(e),J.init(e),e.helper.registerValidateConfig({auth:q,params:T}),e.notificationCenter.subscribeInnerEvent(e.InnerEvent.DESTROY,this.dispose,this)}dispose(){const{notificationCenter:e,InnerEvent:t}=this._core;e.unSubscribeInnerEvent(t.DESTROY,this.dispose,this),H.dispose(),K.dispose(),O.dispose()}}}));
@@ -1 +1 @@
1
- function e(e,t){var o={};for(var s in e)Object.prototype.hasOwnProperty.call(e,s)&&t.indexOf(s)<0&&(o[s]=e[s]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var i=0;for(s=Object.getOwnPropertySymbols(e);i<s.length;i++)t.indexOf(s[i])<0&&Object.prototype.propertyIsEnumerable.call(e,s[i])&&(o[s[i]]=e[s[i]])}return o}function t(e,t,o,s){return new(o||(o=Promise))((function(i,r){function n(e){try{l(s.next(e))}catch(e){r(e)}}function a(e){try{l(s.throw(e))}catch(e){r(e)}}function l(e){var t;e.done?i(e.value):(t=e.value,t instanceof o?t:new o((function(e){e(t)}))).then(n,a)}l((s=s.apply(e,t||[])).next())}))}"function"==typeof SuppressedError&&SuppressedError;var o=new class{constructor(){this._name="WebRequest"}init(e){this._core=e}request(e,o){return t(this,void 0,void 0,(function*(){var t;const{isEmpty:s}=null===(t=this._core)||void 0===t?void 0:t.utils,{downloadUrl:i="",method:r="PUT",url:n,qs:a,headers:l={},resources:d,dataType:c="text",uploadByIP:h,uploadIP:u}=e;let p=n;if(a){const e=this._queryString(a);e&&(p+=`${p.includes("?")?"&":"?"}${e}`)}const g=new XMLHttpRequest;g.open(r.toUpperCase(),p,!0),g.responseType=c;const m=Object.assign({},l);if(h&&u&&(m.host=u),!s(m))for(const e in m)m.hasOwnProperty(e)&&!["content-length","user-agent","origin","host"].includes(e.toLowerCase())&&g.setRequestHeader(e,m[e]);return g.onload=()=>{const t=this._getResponseBody(g,i,h&&u),s=this._buildResponse(g,t);if(200===g.status)o(null,s);else{if(u&&!p.includes(u))return e.url=this._domainName2IP(p,u),e.uploadByIP=!0,this.request(e,o);o({code:g.status,message:JSON.stringify(g.responseText)},s)}},g.onerror=()=>{const e=this._getResponseBody(g,i,h&&u),t=this._buildResponse(g,e),s={code:g.status,message:0===g.status?"CORS blocked or network error":JSON.stringify(g.responseText)};o(s,t)},e.onProgress&&g.upload&&(g.upload.onprogress=t=>{const{total:o,loaded:s}=t,i=Math.min(Math.floor(100*s/o),100);e.onProgress({total:o,loaded:s,percent:i/100})}),g.send(d),g}))}_buildResponse(e,t){const o={};return e.getAllResponseHeaders().trim().split("\n").forEach((e=>{if(e){const[t,s]=e.split(":").map((e=>e.trim()));o[t.toLowerCase()]=s}})),{statusCode:e.status,statusMessage:e.statusText,headers:o,data:t}}_getResponseBody(e,t,o){return 200===e.status&&t?{location:t,uploadIP:o}:{response:e.responseText,uploadIP:o}}_queryString(e,t="&",o="="){var s;const{isEmpty:i,isPlainObject:r}=null===(s=this._core)||void 0===s?void 0:s.utils;return i(e)?"":r(e)?Object.keys(e).map((s=>{const i=encodeURIComponent(s)+o;return Array.isArray(e[s])?e[s].map((e=>i+encodeURIComponent(e))).join(t):i+encodeURIComponent(e[s])})).filter(Boolean).join(t):void 0}_domainName2IP(e,t){return e.replace(/^http(s)?:\/\/(.*?)\//,`https://${t}/`)}};const s=["unknown","image","video","audio","log"];var i=new class{init(e){this._core=e}request(t,o){var i;const{MINI_APP_NAMESPACE:r,IN_ALIPAY_MINI_APP:n,IN_UNI_IOS_APP:a}=null===(i=this._core)||void 0===i?void 0:i.utils,{resources:l="",headers:d={},url:c,downloadUrl:h=""}=t;let u=c,p=null;const g=h?h.match(/^(https?:\/\/[^/]+\/)([^/]*\/?)(.*)$/):null;if(!g)return void console.warn("message Invalid download URL format");const m=decodeURIComponent(g[3]),f=m.includes("?")?m.split("?")[0]:m||"",_={key:t.fileKey||f,success_action_status:200,"Content-Type":""},v={};if(a){const[e,t]=c.split("?sign=");t&&(u=`${e}?sign=${encodeURIComponent(t)}`,v.sign=decodeURIComponent(t),v.signature=decodeURIComponent(t))}let I={url:u,header:d,name:"file",filePath:l,formData:Object.assign(Object.assign({},_),v),timeout:t.timeout||3e5};if(n){const o=e(I,["name"]);I=Object.assign(Object.assign({},o),{fileName:"file",fileType:t.fileType?s[t.fileType]:"image"})}return p=r.uploadFile(Object.assign(Object.assign({},I),{success:e=>{this._handleResponse({response:e,downloadUrl:h,callback:o})},fail:e=>{this._handleResponse({response:e,downloadUrl:h,callback:o})}})),p.onProgressUpdate&&p.onProgressUpdate((e=>{t.onProgress&&t.onProgress({total:e.totalBytesExpectedToSend||0,loaded:e.totalBytesSent||0,percent:e.progress?Math.floor(e.progress)/100:0})})),p}_handleResponse(e){const{downloadUrl:t,response:o,callback:s}=e,i={};if(o.header)for(const e in o.header)o.header.hasOwnProperty(e)&&(i[e.toLowerCase()]=o.header[e]);const r=+o.statusCode;200===r?s(null,{statusCode:r,headers:i,data:Object.assign(Object.assign({},o.data),{location:t})}):s({code:r,message:JSON.stringify(o.data)},{statusCode:r,headers:i,data:void 0})}};function r(e){return"file"===function(e){return Object.prototype.toString.call(e).match(/^\[object (.*)\]$/)[1].toLowerCase()}(e)}function n(e){const t=e||99999999;return Math.round(Math.random()*t)}function a(e,t=!0,o=!0){const s=Date.now();return t?o?s-e+" ms":`${Math.round((s-e)/1e3)} s`:o?s-e:Math.round((s-e)/1e3)}function l(e){return`${Array.from({length:8},(()=>Math.floor(65536*(1+Math.random())).toString(16).substring(1))).join("")}-${e}`}function d(e,t){return Math.round(Number(e)*10**t)/10**t}function c(e){const t=1024,o=1048576;return e<t?`${e}B`:e<o?`${Math.floor(e/t)}KB`:`${Math.floor(e/o)}MB`}function h(e){if(e<=1048576){return`${d(e/1024,1)}KB/s`}return`${d(e/1048576,1)}MB/s`}const u="TIMImageElem",p="TIMSoundElem",g="TIMFileElem",m="TIMVideoFileElem",f="RichMediaMessagePlugin",_=["rich.my-imcloud.com","imrich.qcloud.com"],v=1,I=2,y=3;var U;!function(e){e.UNSENT="unSend",e.SUCCESS="success",e.FAIL="fail"}(U||(U={}));var w=new class{init(e){this._core=e}addAuthToUrl(e){const t=function(e){return e?e.startsWith("https://")?e:e.startsWith("http://")?e.replace("http://","https://"):e:""}(e);return this.processResourceUrl(t)}removeAuthToUrl(e){return function(e,t){const[o,s]=e.split("?");if(!s)return o;const i=s.split("&").reduce(((e,o)=>{const[s,i]=o.split("=");return s&&s!==t&&(e[s]=i||""),e}),{}),r=Object.keys(i).map((e=>`${e}${i[e]?`=${i[e]}`:""}`)).join("&");return r?`${o}?${r}`:o}(e,"authKey")}extractFileFromInput(e){return r(e)?e:function(e){if("object"!=typeof e||null===e)return!1;const t=Object.getPrototypeOf(e);if(null===t)return!0;let o=t;for(;null!==Object.getPrototypeOf(o);)o=Object.getPrototypeOf(o);return t===o}(e)&&"undefined"!=typeof uni?Array.isArray(e.tempFiles)&&e.tempFiles.length>0?e.tempFiles[0]:null:e instanceof HTMLInputElement&&e.files&&e.files.length>0?e.files[0]:null}probeImageWidthHeight(e){return t(this,void 0,void 0,(function*(){var t;const{IN_MINI_APP:o,IN_BROWSER:s}=(null===(t=this._core)||void 0===t?void 0:t.utils)||{};return this._shouldSkipProbing()?{width:0,height:0}:s?this._probeImageDimensionsWeb(e):o?this._probeImageDimensionsMiniApp(e):void 0}))}isSimpleCos(){var e;const t=(null===(e=this._core)||void 0===e?void 0:e.store.get("cloudConfig"))||{},{simple_cos:o}=t;return"0"!==o}getFileDNList(){var e;let t=_;const o=(null===(e=this._core)||void 0===e?void 0:e.store.get("cloudConfig"))||{},{file_dn_list:s}=o;if(void 0===s)return t;try{JSON.parse(s).forEach((e=>{t.includes(e)||t.push(e)}))}catch(e){console.warn(e),t=_}return t}getPlatform(){var e;return null===(e=this._core)||void 0===e?void 0:e.utils.platform}generateUUID(e,t){let o=`${this.getSDKAppID()}-${this.getCurrentUserID()}-${function(){const e="0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";let t="";for(let o=32;o>0;--o)t+=e[Math.floor(62*Math.random())];return t}()}`;if(t)return`${o}.${t}`;const s=e.name||e.value||e.url||e.tempFilePath,i=s&&s.slice(s.lastIndexOf(".")+1);return i&&(o=`${o}.${i}`),o}processResourceUrl(e){if(!e)return"";let t=e;const o=this.getFileDownloadProxy(),s=this.getAuthKey(),i=this.getFileDNList();o&&(e.startsWith("http://")?t=e.replace(/^http:\/\/[^/]+/,o):e.startsWith("https://")&&(t=e.replace(/^https:\/\/[^/]+/,o)));const r=s&&-1===t.indexOf("authKey=")&&function(e,t){let o=!1;if(e){const s=e.match(/:\/\/([0-9]?\.)?(.[^/:]+)/),i=s&&s[2]||"";if(i.includes("rich-dev"))return!0;for(let e=0;e<t.length;e++)if(i.endsWith(t[e])){o=!0;break}}return o}(t,i);return r&&(t=t.indexOf("?")>-1?`${t}&authKey=${s}`:`${t}?authKey=${s}`),t}getCurrentUserID(){var e,t;return null===(t=null===(e=this._core)||void 0===e?void 0:e.store.get("login"))||void 0===t?void 0:t.userId}getSDKAppID(){var e,t;return null===(t=null===(e=this._core)||void 0===e?void 0:e.store.get("instance"))||void 0===t?void 0:t.sdkAppId}getFileDownloadProxy(){var e,t;return(null===(t=null===(e=this._core)||void 0===e?void 0:e.store.get("instance"))||void 0===t?void 0:t.fileDownloadProxy)||""}getFileUploadProxy(){var e,t;return(null===(t=null===(e=this._core)||void 0===e?void 0:e.store.get("instance"))||void 0===t?void 0:t.fileUploadProxy)||""}getAuthKey(){var e,t;return(null===(t=null===(e=this._core)||void 0===e?void 0:e.store.get("login"))||void 0===t?void 0:t.authKey)||""}isPrivateNetWork(){var e,t;return null===(t=null===(e=this._core)||void 0===e?void 0:e.store.get("instance"))||void 0===t?void 0:t.proxyServer}getPlatformFlags(){var e;const{IN_BROWSER:t,IN_MINI_APP:o,IN_RN_APP:s,IN_UNI_NATIVE_APP:i}=null===(e=this._core)||void 0===e?void 0:e.utils;return{IN_BROWSER:t,IN_MINI_APP:o,IN_RN_APP:s,IN_UNI_NATIVE_APP:i}}isEmpty(e){var t;const{isEmpty:o}=null===(t=this._core)||void 0===t?void 0:t.utils;return o(e)}_probeImageDimensionsMiniApp(e){var t;const{MINI_APP_NAMESPACE:o}=(null===(t=this._core)||void 0===t?void 0:t.utils)||{};return new Promise((t=>{o.getImageInfo({src:e,success:e=>t({width:e.width,height:e.height}),fail:()=>t({width:0,height:0})})}))}_shouldSkipProbing(){var e;const{IN_RN_APP:t,IS_IE:o,IE_VERSION:s}=(null===(e=this._core)||void 0===e?void 0:e.utils)||{};return t||o&&9===s}_probeImageDimensionsWeb(e){return new Promise((t=>{const o=new Image,s=()=>{o.onload=null,o.onerror=null,o.src=""};o.onload=()=>{t({width:o.width,height:o.height}),s()},o.onerror=()=>{t({width:0,height:0}),s()},o.src=e}))}};var S=new class{constructor(){this.uploadFileTryCount=0,this.maxRetries=1,this.systemClockOffset=0,this.httpRequest=null,this.uploadFileType="",this.duration=900,this.fetchCosTryCount=0}init(e){var t;this._core=e;const{IN_MINI_APP:s}=e.utils;this.httpRequest=s?i:o,null===(t=this.httpRequest)||void 0===t||t.init(e)}uploadToCOS(e){return t(this,void 0,void 0,(function*(){const t=`${f} uploadToCOS`,{file:o}=e;this.uploadFileType=e.uploadFileType,console.log(`${t} options:`,e);try{const s=Date.now(),i=yield this._createCosOptions(e),r=yield this._uploadFile(i);this._handleUploadError(r,e);const n=this._createUploadResult(o,r),a=Date.now()-s,l=c(o.size),d=`size:${l} time:${a}ms speed:${h(1e3*o.size/a)}`;return console.log(`${t} ok. name:${o.name} ${d}`),{uploadOptions:i,response:n}}catch(e){throw console.warn(`${t} failed, error:`,e),e}}))}_handleUploadError(e,t){var o,s;const{ChatError:i}=null===(o=this._core)||void 0===o?void 0:o.helper;if(403===e.statusCode)throw a(Date.now(),!1),t.url,(null===(s=null==e?void 0:e.data)||void 0===s?void 0:s.uploadIP)&&e.data.uploadIP,new i({message:"Upload failed with status 403"})}_createUploadResult(e,t){return{fileName:e.name,fileSize:e.size,fileType:e.type.slice(e.type.indexOf("/")+1).toLowerCase(),location:t.data.location||"",uploadTime:a(Date.now(),!1),uploadSpeed:h(1e3*e.size/a(Date.now(),!1))}}_createCosOptions(e){return t(this,void 0,void 0,(function*(){const{fileName:t,resources:o,uploadMethod:s}=this._prepareUploadParams(e),i=this._isC2CConversation(e.message.conversationID)?1:2;try{const r=yield this._fetchCosSignatureUrl({fileType:this.uploadFileType,fileName:t,uploadMethod:s,duration:this.duration,userID:e.message.from,conversationType:i}),{uploadUrl:n,downloadUrl:a,requestSnapshotUrl:l,thumbUrl:d,largeUrl:c,fileKey:h}=r,u=!w.isPrivateNetWork()&&r.uploadIP;return{url:this._getRawOrUploadProxyUrl(n),fileType:this.uploadFileType,fileName:t,resources:o,downloadUrl:a,requestSnapshotUrl:l,thumbUrl:d,largeUrl:c,fileKey:h,uploadIP:u||"",onProgress:t=>this._handleUploadProgress(t,e)}}catch(e){throw console.error("Failed to create COS pre-signed URL options:",e),e}}))}_prepareUploadParams(e){console.log(`${f} prepareUploadParams:`,e);const{file:t}=e,{IN_MINI_APP:o,IN_RN_APP:s}=w.getPlatformFlags(),i=o||s,r=i&&e.message.type!==g,{name:a}=t,d=a.slice(a.lastIndexOf(".")),c=`${n(999999)}${d}`;return{fileName:l(r?t.name:c),resources:i?t.url:t,uploadMethod:i?1:0}}_handleUploadProgress(e,t){if("function"==typeof t.onProgress)try{t.onProgress(e.percent)}catch(e){throw console.warn("Upload progress callback error:",e),e}}_fetchCosSignatureUrl(e){return t(this,void 0,void 0,(function*(){const o=`${f} fetchCosSignatureUrl`,s=w.isSimpleCos(),i=this._prepareCosRequestData(e),r=s?"im_cos_msg.simple_sig":"im_cos_msg.pre_sig";try{const e=yield function(e,o,s){return t(this,void 0,void 0,(function*(){try{const{helper:t,channel:i}=s,r=t.generateCosSpecifiedData({servcmd:e,data:o}),n=`${r.head.seq}${e}`;return yield i.sendPacket(r,{requestId:n})}catch(e){throw console.warn("getCosSig error:",e),e}}))}(r,i,this._core);this.fetchCosTryCount=0;const n=this._processResponse(e);return console.log(`${o} ok. isSimpleCos:${s} data:`,n),n||{}}catch(t){if(console.error(`${o} failed, error:`,t),this.fetchCosTryCount<1)return this.fetchCosTryCount++,this._fetchCosSignatureUrl(e);throw this.fetchCosTryCount=0,t}}))}_processResponse(e){var t;const o=w.isSimpleCos(),s=o?null===(t=null==e?void 0:e.rpt_pre_sig)||void 0===t?void 0:t[0]:e;if(!s)return{};if(o){const{str_final_ip:e,rpt_pre_sig:t,uint32_file_id:o,uint32_exist_flag:i,str_download_url:r,str_upload_url:n,str_snapshot_url:a,str_file_key:l}=s;return{uploadIP:e,preSig:t,fileID:o,existFlag:i,downloadUrl:r,uploadUrl:n,requestSnapshotUrl:a,fileKey:l}}const{upload_url:i,download_url:r,snapshot_url:n,thumb_url:a,large_url:l,file_key:d}=s;return{uploadUrl:i,downloadUrl:r,requestSnapshotUrl:n,thumbUrl:a,largeUrl:l,fileKey:d}}_prepareCosRequestData(e){return w.isSimpleCos()?{uint32_upload_method:e.uploadMethod,uint32_platform:w.getPlatform(),uint32_sdkappid:w.getSDKAppID(),str_user_id:e.userID,uint32_scene:e.conversationType,rpt_upload_object:[{uint32_file_id:1,uint32_file_type:e.fileType,str_file_name:e.fileName}]}:{file_type:e.fileType,file_name:e.fileName,upload_method:e.uploadMethod,Duration:e.duration}}_uploadFile(e){return t(this,void 0,void 0,(function*(){return new Promise(((t,o)=>{this.httpRequest.request(e,((s,i)=>{s&&this.uploadFileTryCount<this.maxRetries&&this.shouldRetry(s)?(this.uploadFileTryCount++,this._uploadFile(e).then(t).catch(o)):(this.uploadFileTryCount=0,s?o(s):t(i))}))}))}))}shouldRetry(e){if(!e)return!1;if(5===Math.floor(e.statusCode/100))return!0;return!(!this.isTimeRelatedError(e)||!this._isClockOutOfSync(e))&&(this._syncSystemClock(e),!0)}isTimeRelatedError(e){var t,o;try{const s=null===(t=e.error)||void 0===t?void 0:t.Code,i=null===(o=e.error)||void 0===o?void 0:o.Message;return"RequestTimeTooSkewed"===s||"AccessDenied"===s&&"Request has expired"===i}catch(e){return!1}}_isClockOutOfSync(e){var t,o,s;const i=(null===(t=e.headers)||void 0===t?void 0:t.date)||(null===(o=e.headers)||void 0===o?void 0:o.Date)||(null===(s=e.error)||void 0===s?void 0:s.ServerTime);if(!i)return!1;const r=Date.now(),n=Date.parse(i);return Math.abs(r+this.systemClockOffset-n)>=3e4}_syncSystemClock(e){var t,o,s;const i=(null===(t=e.headers)||void 0===t?void 0:t.date)||(null===(o=e.headers)||void 0===o?void 0:o.Date)||(null===(s=e.error)||void 0===s?void 0:s.ServerTime);if(i){const e=Date.now(),t=Date.parse(i);this.systemClockOffset=t-e}}_getRawOrUploadProxyUrl(e){const t=w.getFileUploadProxy();let o=e;return t&&(o=e.replace(/^https:\/\/[^/]+/,t)),o}_isC2CConversation(e){return"C2C"===e.slice(0,3)}};const P=2108,F=2251,b=2252,M=["jpg","jpeg","gif","png","bmp","image","webp"],A=20971520,O={JPG:1,JPEG:1,GIF:2,PNG:3,BMP:4,UNKNOWN:255};class T{constructor(e,t){this.instanceID=n(9999999),this.sizeType=e.type||0,this.type=0,this.size=e.size||0,this.width=e.width||0,this.height=e.height||0,this.imageUrl=w.addAuthToUrl(e.imageUrl||e.url||""),this.url=w.addAuthToUrl(e.url||t)}setSizeType(e){this.sizeType=e}setType(e){this.type=e}setImageUrl(e){e&&(this.imageUrl=w.addAuthToUrl(e))}getImageUrl(){return this.imageUrl}}function C(t){const{originUrl:o,originWidth:s,originHeight:i,min:r=198}=t,n=parseInt(s)||0,a=parseInt(i)||0,l={url:void 0,width:0,height:0};if((n<=a?n:a)<=r)l.url=o,l.width=n,l.height=a;else{a<=n?(l.width=Math.ceil(n*r/a),l.height=r):(l.width=r,l.height=Math.ceil(a*r/n));const e=o&&o.indexOf("?")>-1?`${o}&`:`${o}?`;l.url=198===r?`${e}imageView2/3/w/198/h/198`:`${e}imageView2/3/w/720/h/720`}if(void 0===o){return e(l,["url"])}return l}class N{constructor(e){this._imageMemoryURL="",this._percent=0,this.type=u;const{uuid:t,file:o,imageFormat:s,imageInfoArray:i=[]}=e;this._imageMemoryURL=this.createImageDataAsURL(o),this.content={imageFormat:s,uuid:t,imageInfoArray:[]},this.initImageInfoArray(i),this.autoFixUrl()}static parseServerPushElement(e){const{MsgContent:t}=e,{ImageFormat:o,ImageInfoArray:s,UUID:i}=t,r=function(e){return e.map((e=>({size:e.Size,type:e.Type,width:e.Width,height:e.Height,url:e.URL})))}(s);return new N({imageFormat:o,imageInfoArray:r,uuid:i})}createImageDataAsURL(e){let t="";const{IN_MINI_APP:o,IN_RN_APP:s,IN_BROWSER:i}=w.getPlatformFlags();return e?((o||s)&&(t=e.url),i&&(t=window.URL.createObjectURL(e)),t):t}initImageInfoArray(e=[]){const t={type:0,size:0,width:0,height:0,url:""};for(let o=0;o<3;o++){const s=e[o]||Object.assign({},t),i=new T(s,this._imageMemoryURL);i.setSizeType(o+1),i.setType(o),this.addImageInfo(i)}this.updateAccessSideImageInfoArray()}autoFixUrl(){const e=["http","https"];this.content.imageInfoArray.forEach((t=>{if(!t.url||""===t.imageUrl)return;const[o,...s]=t.imageUrl.split("://"),i=s.join("://");e.includes(o)||t.setImageUrl(`https://${i}`)}))}updatePercent(e){this._percent=Math.min(e,1)}updateImageFormat(e){this.content.imageFormat=O[e.toUpperCase()]||O.UNKNOWN}addImageInfo(e){this.content.imageInfoArray.length>=3||this.content.imageInfoArray.push(e)}updateImageInfoArray(e){const t=this.content.imageInfoArray.length;let o;for(let s=0;s<t;s++)o=this.content.imageInfoArray[s],e[s].size&&(o.size=e[s].size),e[s].url&&o.setImageUrl(e[s].url),e[s].width&&(o.width=e[s].width),e[s].height&&(o.height=e[s].height)}updateAccessSideImageInfoArray(){const[e]=this.content.imageInfoArray;e&&0!==e.width&&0!==e.height&&(!function(e){const t=e[2];e[2]=e[1],e[1]=t;for(let t=0;t<e.length;t++)e[t].setType(t)}(this.content.imageInfoArray),Object.assign(this.content.imageInfoArray[2],C({originWidth:e.width,originHeight:e.height,min:720})))}validateBeforeSend(){const[e]=this.content.imageInfoArray,t=!!e&&""!==e.imageUrl&&0!==e.size;return{isValid:t,error:t?null:{message:"content can not be empty"}}}convertToBackendFormat(){const{uuid:e,imageFormat:t,imageInfoArray:o}=this.content;return{MsgType:this.type,MsgContent:{ImageFormat:t,ImageInfoArray:this.parseImageInfoArray(o),UUID:e}}}parseImageInfoArray(e){return e.map((e=>({InstanceId:e.instanceID,Type:e.sizeType,MsgType:e.type,Size:e.size,Width:e.width,Height:e.height,URL:w.removeAuthToUrl(e.imageUrl)})))}}var E=new class{constructor(){this._messageOptionsMap=new Map}init(e){var t;this._core=e;const{notificationCenter:o,helper:s,InnerEvent:i,message:r}=e;s.registerApi("createImageMessage",this),null===(t=null==r?void 0:r.messageFactory)||void 0===t||t.registerElementClass(u,N),o.subscribeInnerEvent(i.DESTROY,this._dispose,this)}createImageMessage(e){var t,o,s,i,r;try{const i=this._core.ssoLog.createSSOLogData({method:"createImageMessage"});console.log(`${f} createImageMessage options:`,e);const r=null===(t=this._core.store.get("login"))||void 0===t?void 0:t.userId,n=null===(s=null===(o=this._core)||void 0===o?void 0:o.message.messageFactory)||void 0===s?void 0:s.createMessage(Object.assign(Object.assign({},e),{from:r})),a=this._processImage(e);e.payload.file=a;const l={imageFormat:O.UNKNOWN,uuid:w.generateUUID(a),file:a,imageInfoArray:[]},d=new N(l);return n.setElement(d),this._messageOptionsMap.set(n.clientSequence,e),console.log(`${f} createImageMessage OK imageMessage:`,n),i.end(),n}catch(e){throw null===(r=(i=this._core.ssoLog.getSSOLogData("createImageMessage")).setError)||void 0===r||r.call(i,e).end(),console.error(`${f} createImageMessage error:`,e),e}}upload(e){return t(this,void 0,void 0,(function*(){console.log(`${f} uploadImage message:`,e);const t=e.getElements()[0],{file:o}=this._messageOptionsMap.get(e.clientSequence).payload;this._validateBeforeUploadImage(o);const s=yield this._performImageUpload(t,e,o),i=this._generateImageInfo(s);return t.updateImageInfoArray(i),e}))}_performImageUpload(e,o,s){return t(this,void 0,void 0,(function*(){const{to:t}=o,i={uploadFileType:v,file:s,to:t,message:o,onProgress:t=>{var s,i;e.updatePercent(t),null===(i=null===(s=this._messageOptionsMap.get(o.clientSequence))||void 0===s?void 0:s.onProgress)||void 0===i||i.call(s,t)}},{uploadOptions:r,response:n}=yield S.uploadToCOS(i);return this._parseResponse(r,n)}))}_generateImageInfo(e){console.log(`${f} generateImageInfo`);const{location:t,fileSize:o,width:s,height:i,smallImageUrl:r,smallImageWidth:n,smallImageHeight:a,largeImageUrl:l,largeImageWidth:d,largeImageHeight:c,imageInfoArray:h}=e,u=w.addAuthToUrl(t),p={size:o,url:u,width:s,height:i};return(null==h?void 0:h.length)>0?this._processImageInfoArray(h,o):r&&l?[Object.assign({},p),{largeImageUrl:l,largeImageWidth:d,largeImageHeight:c},{smallImageUrl:r,smallImageWidth:n,smallImageHeight:a}]:[Object.assign({},p),this._generateThumbInfo(u,s,i,720),this._generateThumbInfo(u,s,i,198)]}_generateThumbInfo(e,t,o,s){return C({originUrl:e,originWidth:t,originHeight:o,min:s})}_processImageInfoArray(e,t){let o,s,i;for(const r of e)1===r.type?(s=r,s.size=t):2===r.type?(i=r,i.size=t):(o=r,o.size=t);return[Object.assign({},o),Object.assign({},i),Object.assign({},s)]}_parseResponse(e,o){return t(this,void 0,void 0,(function*(){console.log(`${f} parseResponse`);try{const{thumbUrl:t,largeUrl:s,downloadUrl:i}=e;t&&s&&(yield this._getImageInfoByUrl(t,o,"thumb"),yield this._getImageInfoByUrl(s,o,"large"));if(w.isSimpleCos()&&!w.isPrivateNetWork()&&(yield this._getImageInfoArray(i,o),null==o?void 0:o.uploadIP)){const e=this._extractDomainFromUrl(i);e&&(yield this._getDownloadIP(e,o))}return o}catch(e){throw console.error("Failed to parse response:",e),e}}))}_extractDomainFromUrl(e){try{const t=e.match(/:\/\/([^\/]+)/);return t?t[1]:null}catch(e){return console.warn("Failed to extract domain from URL:",e),null}}_getImageInfoByUrl(e,o,s){return t(this,void 0,void 0,(function*(){try{const t=w.addAuthToUrl(e),{width:i=0,height:r=0}=yield w.probeImageWidthHeight(t);o.width=i,o.height=r,"thumb"===s?(o.smallImageUrl=e,o.smallImageWidth=i,o.smallImageHeight=r):(o.largeImageUrl=e,o.largeImageWidth=i,o.largeImageHeight=r)}catch(e){console.warn(`Failed to get ${s} image info:`,e)}}))}_validateBeforeUploadImage(e){var t;const{ChatError:o}=null===(t=this._core)||void 0===t?void 0:t.helper;if(!e)throw new o({code:F});this._checkImageType(e),this._checkImageSize(e)}_processImage(e){var t;try{const{IN_MINI_APP:o}=null===(t=this._core)||void 0===t?void 0:t.utils;let{file:s}=e.payload;return s=o?this._processMiniAppImageFile(s):this._processWebImageFile(s),s}catch(e){throw console.warn(`${f} _processImage error:`,e),e}}_processMiniAppImageFile(e){r(e)&&console.warn("FileUnsupportedInMiniApp","createImageMessage");const t=e.tempFiles[0].path||e.tempFiles[0].tempFilePath;return{url:t,name:t.slice(t.lastIndexOf("/")+1),size:e.tempFiles&&e.tempFiles[0].size||1,type:t.slice(t.lastIndexOf(".")+1).toLowerCase()}}_processWebImageFile(e){var t;const{ChatError:o}=null===(t=this._core)||void 0===t?void 0:t.helper,s=w.extractFileFromInput(e);if(!s)throw new o({message:"Invalid file. Pass either `e.target` (from file input) or a File object"});return s}_getDownloadIP(e,o){return t(this,void 0,void 0,(function*(){const s=`${f} getDownloadIP domainName: ${e}`;try{const i=yield function(e,o){return t(this,void 0,void 0,(function*(){try{const{helper:t,channel:s}=o,i="im_cos_msg.get_final_ip",r={str_domain:e},n=t.generateProtocolData({servcmd:i,data:r}),a=`${n.head.seq}${i}`;return yield s.sendPacket(n,{requestId:a})}catch(e){throw console.warn("getFinalIP error:",e),e}}))}(e,this._core);if(!i||!i.str_final_ip)return;console.log(`${s} ok. downloadIP:${i}`);const r=o.location.split("/");r[0]=i.str_final_ip,o.location=r.join("/")}catch(e){console.warn(e)}}))}_getImageInfoArray(e,o){return t(this,void 0,void 0,(function*(){const s=`${f}._getImageInfoArray`;try{const i=yield function(e,o){return t(this,void 0,void 0,(function*(){try{const{helper:t,channel:s}=o,i="im_cos_msg.get_imageinfo",r={str_image_url:e},n=t.generateProtocolData({servcmd:i,data:r}),a=`${n.head.seq}${i}`;return yield s.sendPacket(n,{requestId:a})}catch(e){throw console.warn("getImageInfo error:",e),e}}))}(e,this._core);return o.imageInfoArray=this._processImageInfoResponse(i),console.log(`${s} ok`),o}catch(e){throw o.imageInfoArray=void 0,console.warn(`${s} failed, error:`,e),e}}))}_processImageInfoResponse(e){if(!e)return[];const{rpt_msg_image_info:t}=e;return t.map((e=>({type:e.uint32_image_type,url:e.str_url,width:e.uint32_width,height:e.uint32_height,imageFormat:e.str_image_format})))}_checkImageType(e){const{utils:t,helper:o}=this._core;let s="";if(t.IN_MINI_APP&&(s=e.url.slice(e.url.lastIndexOf(".")+1)),t.IN_BROWSER&&(s=e.name.slice(e.name.lastIndexOf(".")+1)),M.indexOf(s.toLowerCase())<0)throw new o.ChatError({code:b})}_checkImageSize(e){const{utils:t,helper:o}=this._core;let s=0;if(s=(t.IN_MINI_APP,e.size),0===s)throw new o.ChatError({code:P});if(s>=A)throw new o.ChatError({message:`File size exceeds limit: ${c(A)}`})}_reset(){this._messageOptionsMap.clear()}_dispose(){this._reset();const{notificationCenter:e,InnerEvent:t}=this._core;e.unSubscribeInnerEvent(t.DESTROY,this._dispose,this)}};const D=2108,$=2401,R="2.5.0",z="1.18.0",W=104857600;function j(e,t){const o=e.split("."),s=t.split("."),i=Math.max(o.length,s.length);for(;o.length<i;)o.push("0");for(;s.length<i;)s.push("0");for(let e=0;e<i;e++){const t=parseInt(o[e]),i=parseInt(s[e]);if(t>i)return 1;if(t<i)return-1}return 0}class x{constructor(e){this.type=g,this.uploadProgress=0;const t=this._getFileInfo(e);this.content={downloadFlag:2,fileUrl:w.addAuthToUrl(e.url||e.fileUrl)||"",uuid:e.uuid,fileName:t.name||"",fileSize:t.size||0}}static parseServerPushElement(e){const{MsgContent:t}=e,{Download_Flag:o,Url:s,FileName:i,FileSize:r,UUID:n}=t;return new x({downloadFlag:o,url:s,fileName:i,fileSize:r,uuid:n})}updatePercent(e){this.uploadProgress=Math.min(e,1)}updateFileUrl(e){this.content.fileUrl=e}validateBeforeSend(){const e=""!==this.content.fileUrl&&""!==this.content.fileName&&this.content.fileSize>0;return{isValid:e,error:e?null:{message:"content can not be empty"}}}convertToBackendFormat(){const{uuid:e,downloadFlag:t,fileUrl:o,fileName:s,fileSize:i}=this.content;return{MsgType:this.type,MsgContent:{Download_Flag:t,Url:w.removeAuthToUrl(o),FileName:s,FileSize:i,UUID:e}}}_getFileInfo(e){if(e.fileName&&e.fileSize)return{size:e.fileSize,name:e.fileName};const{file:t}=e;return t?(w.getPlatform().IN_UNI_NATIVE_APP&&this._processNativeAppFile(t),{size:t.size,name:t.name}):{size:0,name:""}}_processNativeAppFile(e){if(e.path&&e.path.includes(".")){const t=e.path.slice(e.path.lastIndexOf(".")+1).toLowerCase();e.type=t,e.name||(e.name=`${n(999999)}.${t}`)}e.name||(e.type="",e.name=e.path.slice(e.path.lastIndexOf("/")+1).toLowerCase()),e.suffix&&(e.type=e.suffix),e.url||(e.url=e.path)}}var V=new class{constructor(){this._messageOptionsMap=new Map}init(e){var t;this._core=e;const{notificationCenter:o,helper:s,InnerEvent:i,message:r}=e;s.registerApi("createFileMessage",this),null===(t=null==r?void 0:r.messageFactory)||void 0===t||t.registerElementClass(g,x),o.subscribeInnerEvent(i.DESTROY,this._dispose,this)}createFileMessage(e){var t,o,s,i,r;try{const i=this._core.ssoLog.createSSOLogData({method:"createFileMessage"});console.log(`${f} createFileMessage options:`,e),this._checkVersion();const r=this._processFile(e.payload.file);e.payload.file=r;const n=null===(t=this._core.store.get("login"))||void 0===t?void 0:t.userId,a=null===(s=null===(o=this._core)||void 0===o?void 0:o.message.messageFactory)||void 0===s?void 0:s.createMessage(Object.assign(Object.assign({},e),{from:n})),l={uuid:w.generateUUID(r),file:r},d=new x(l);return a.setElement(d),this._messageOptionsMap.set(a.clientSequence,e),console.log(`${f} createFileMessage success fileMessage:`,a),i.end(),a}catch(e){throw null===(r=(i=this._core.ssoLog.getSSOLogData("createFileMessage")).setError)||void 0===r||r.call(i,e).end(),console.error(`${f} createFileMessage error:`,e),e}}upload(e){return t(this,void 0,void 0,(function*(){console.log(`${f} uploadFile message:`,e);const{file:t}=this._messageOptionsMap.get(e.clientSequence).payload;this._validateBeforeUploadFile(t);const o=e.getElements()[0],s=yield this._performFileUpload(o,e,t),i=w.addAuthToUrl(null==s?void 0:s.location);return o.updateFileUrl(i),e}))}_validateBeforeUploadFile(e){var t;const{ChatError:o}=null===(t=this._core)||void 0===t?void 0:t.helper;if(!e)throw new o({code:$});if(e.size>W)throw new o({message:`File size exceeds limit: ${c(W)}`});if(0===e.size)throw new o({code:D})}_performFileUpload(e,o,s){return t(this,void 0,void 0,(function*(){const{to:t}=o,i={uploadFileType:v,file:s,to:t,message:o,onProgress:t=>{var s,i;e.updatePercent(t),null===(i=null===(s=this._messageOptionsMap.get(o.clientSequence))||void 0===s?void 0:s.onProgress)||void 0===i||i.call(s,t)}},{response:r}=yield S.uploadToCOS(i);return r}))}_processFile(e){var t,o;const{IN_BROWSER:s,IN_RN_APP:i,IN_WX_MINI_APP:r,IN_QQ_MINI_APP:n,IN_UNI_NATIVE_APP:a}=null===(t=this._core)||void 0===t?void 0:t.utils,{ChatError:l}=null===(o=this._core)||void 0===o?void 0:o.helper;if(s||a){const t=w.extractFileFromInput(e);if(!t)throw new l({message:"Invalid file. Pass either `e.target` (from file input) or a File object"});return t}if(r||n){const{tempFiles:t}=e;return Object.assign(Object.assign({},t[0]),{url:t[0].path})}return i?Object.assign(Object.assign({},e),{url:e.uri}):e}_checkVersion(){var e,t;const{MINI_APP_NAMESPACE:o,IN_MINI_APP:s,IN_WX_MINI_APP:i,IN_QQ_MINI_APP:r,IN_UNI_NATIVE_APP:n}=null===(e=this._core)||void 0===e?void 0:e.utils,{ChatError:a}=null===(t=this._core)||void 0===t?void 0:t.helper;if(s){if(!(i||r||n))throw new a({message:"Unsupported mini app environment"});const e=o.getSystemInfoSync().SDKVersion;if(i&&j(e,R)<0){throw new a({message:`WXChooseMessageFile requires SDK version ${R} or higher`})}if(r&&j(e,z)<0){throw new a({message:`QQChooseMessageFile requires SDK version ${z} or higher`})}}}_reset(){this._messageOptionsMap.clear()}_dispose(){this._reset();const{notificationCenter:e,InnerEvent:t}=this._core;e.unSubscribeInnerEvent(t.DESTROY,this._dispose,this)}};const L=2108,q=2352,k=["mp4","quicktime","mov"],B=104857600;class H{constructor(e){this.type=m,this.uploadProgress=0;const t="number"==typeof(null==e?void 0:e.videoSecond)?null==e?void 0:e.videoSecond:0;this.content={remoteVideoUrl:w.addAuthToUrl(e.remoteVideoUrl||e.videoUrl||""),videoFormat:e.videoFormat,videoSecond:parseInt(null==t?void 0:t.toString(),10),videoSize:e.videoSize,videoUrl:w.addAuthToUrl(e.videoUrl),videoDownloadFlag:2,videoUUID:e.videoUUID,thumbUUID:e.thumbUUID,thumbFormat:e.thumbFormat,thumbWidth:e.thumbWidth,snapshotWidth:e.thumbWidth,thumbHeight:e.thumbHeight,snapshotHeight:e.thumbHeight,thumbSize:e.thumbSize,snapshotSize:e.thumbSize,thumbDownloadFlag:2,thumbUrl:w.addAuthToUrl(e.thumbUrl),snapshotUrl:w.addAuthToUrl(e.thumbUrl)}}static parseServerPushElement(e){const{MsgContent:t}=e,{VideoUrl:o,VideoFormat:s,VideoSecond:i,VideoSize:r,VideoDownloadFlag:n,VideoUUID:a,ThumbUUID:l,ThumbFormat:d,ThumbWidth:c,SnapshotWidth:h,ThumbHeight:u,SnapshotHeight:p,ThumbSize:g,SnapshotSize:m,ThumbDownloadFlag:f,ThumbUrl:_,SnapshotUrl:v}=t;return new H({videoUrl:o,videoFormat:s,videoSecond:i,videoSize:r,videoDownloadFlag:n,videoUUID:a,thumbUUID:l,thumbFormat:d,thumbWidth:c,snapshotWidth:h,thumbHeight:u,snapshotHeight:p,thumbSize:g,snapshotSize:m,thumbDownloadFlag:f,thumbUrl:_,snapshotUrl:v})}updatePercent(e){this.uploadProgress=Math.min(e,1)}updateVideoUrl(e){e&&(this.content.remoteVideoUrl=e)}updateSnapshotInfo(e){const{snapshotUrl:t,snapshotWidth:o,snapshotHeight:s}=e;w.isEmpty(t)||(this.content.thumbUrl=this.content.snapshotUrl=t),w.isEmpty(o)||(this.content.thumbWidth=this.content.snapshotWidth=Number(o)),w.isEmpty(s)||(this.content.thumbHeight=this.content.snapshotHeight=Number(s))}validateBeforeSend(){const e=""!==this.content.remoteVideoUrl;return{isValid:e,error:e?null:{message:"content can not be empty"}}}convertToBackendFormat(){const{remoteVideoUrl:e,videoFormat:t,videoSecond:o,videoSize:s,videoDownloadFlag:i,videoUUID:r,thumbUUID:n,thumbFormat:a,thumbWidth:l,snapshotWidth:d,thumbHeight:c,snapshotHeight:h,thumbSize:u,snapshotSize:p,thumbDownloadFlag:g,thumbUrl:m,snapshotUrl:f}=this.content;return{MsgType:this.type,MsgContent:{VideoUrl:w.removeAuthToUrl(e),VideoFormat:t,VideoSecond:o,VideoSize:s,VideoDownloadFlag:i,VideoUUID:r,ThumbUUID:n,ThumbFormat:a,ThumbWidth:l,SnapshotWidth:d,ThumbHeight:c,SnapshotHeight:h,ThumbSize:u,SnapshotSize:p,ThumbDownloadFlag:g,ThumbUrl:w.removeAuthToUrl(m),SnapshotUrl:w.removeAuthToUrl(f)}}}}var K=new class{constructor(){this._messageOptionsMap=new Map}init(e){var t;this._core=e;const{notificationCenter:o,helper:s,InnerEvent:i,message:r}=e;s.registerApi("createVideoMessage",this),null===(t=null==r?void 0:r.messageFactory)||void 0===t||t.registerElementClass(m,H),o.subscribeInnerEvent(i.DESTROY,this._dispose,this)}createVideoMessage(e){var t,o,s,i,r;try{const i=this._core.ssoLog.createSSOLogData({method:"createVideoMessage"});console.log(`${f} createVideoMessage options:`,e);const r=this._processVideo(e);e.payload.file=r;const n=null===(t=this._core.store.get("login"))||void 0===t?void 0:t.userId,a=null===(s=null===(o=this._core)||void 0===o?void 0:o.message.messageFactory)||void 0===s?void 0:s.createMessage(Object.assign(Object.assign({},e),{from:n})),l={videoFormat:r.videoFile.type,videoSecond:d(r.videoFile.second,0),videoSize:r.videoFile.size,remoteVideoUrl:"",videoUrl:r.videoFile.url,videoUUID:w.generateUUID(r.videoFile),thumbUUID:w.generateUUID(r.videoFile,"jpg"),thumbWidth:r.width||200,thumbHeight:r.height||200,thumbUrl:r.thumbUrl,thumbSize:r.thumbSize,thumbFormat:"jpg"},c=new H(l);return a.setElement(c),this._messageOptionsMap.set(a.clientSequence,e),i.end(),a}catch(e){throw null===(r=(i=this._core.ssoLog.getSSOLogData("createVideoMessage")).setError)||void 0===r||r.call(i,e).end(),console.error(`${f} createVideoMessage error:`,e),e}}upload(e){return t(this,void 0,void 0,(function*(){console.log(`${f} uploadVideo message:`,e);const t=e.getElements()[0],{file:o}=this._messageOptionsMap.get(e.clientSequence).payload;this._validateBeforeUploadVideo(o);const s=yield this._performVideoUpload(t,e,o),{location:i,snapshotInfo:r}=s,n=w.addAuthToUrl(i);return t.updateVideoUrl(n),w.isEmpty(r)||t.updateSnapshotInfo(r),e}))}_validateBeforeUploadVideo(e){var t;const{ChatError:o}=null===(t=this._core)||void 0===t?void 0:t.helper;if(e.videoFile.size>B)throw new o({message:`File size exceeds limit: ${c(B)}`});if(0===e.videoFile.size)throw new o({code:L});if(-1===k.indexOf(e.videoFile.type))throw new o({code:q})}_performVideoUpload(e,o,s){return t(this,void 0,void 0,(function*(){const{to:t}=o,i={uploadFileType:I,file:s,to:t,message:o,onProgress:t=>{var s,i;e.updatePercent(t),null===(i=null===(s=this._messageOptionsMap.get(o.clientSequence))||void 0===s?void 0:s.onProgress)||void 0===i||i.call(s,t)}},{response:r,uploadOptions:n}=yield S.uploadToCOS(i);return{snapshotInfo:yield this._getSnapshotInfoByUrl(n.requestSnapshotUrl),location:r.location}}))}_processVideo(e){var t,o;try{const{ChatError:s}=null===(t=this._core)||void 0===t?void 0:t.helper,{IN_MINI_APP:i,IN_BROWSER:r}=null===(o=this._core)||void 0===o?void 0:o.utils;let{file:n}=e.payload,a={};if(i&&(a=this._processMiniVideoFile(n)),r){const e=w.extractFileFromInput(n);if(!e)throw new s({message:"Invalid file. Pass either `e.target` (from file input) or a File object"});n=e,a=this._processWebVideoFile(n)}return n.videoFile=a,n.thumbUrl="",n.thumbSize=0,n}catch(e){throw console.warn(`${f} _processFile error:`,e),e}}_processMiniVideoFile(e){var t,o;const{IN_ALIPAY_MINI_APP:s}=null===(t=this._core)||void 0===t?void 0:t.utils,{ChatError:i}=null===(o=this._core)||void 0===o?void 0:o.helper;if(s)throw new i({message:"VideoUnsupportedInAlipay"});if(r(e))throw new i({message:"FileUnsupportedInMiniApp"});return Array.isArray(e.tempFiles)&&(e=e.tempFiles[0]),{url:e.tempFilePath,name:e.tempFilePath.slice(e.tempFilePath.lastIndexOf("/")+1),size:e.size||1,second:e.duration||0,type:e.tempFilePath.slice(e.tempFilePath.lastIndexOf(".")+1).toLowerCase()}}_processWebVideoFile(e){const{name:t,size:o=1,duration:s=0,type:i}=e,r=i.split("/")[1];return{url:window.URL.createObjectURL(e),name:t,size:o,second:s,type:r}}_getSnapshotInfoByUrl(e){return t(this,void 0,void 0,(function*(){try{console.log(`${f} _getSnapshotInfoByUrl url:`,e);const o={version:1,platform:w.getPlatform(),cover_name:l(n(99999)),snapshot_url:e},s=yield function(e,o){return t(this,void 0,void 0,(function*(){try{const t="im_cos_msg.video_cover",{helper:s,channel:i}=o,r=s.generateCosSpecifiedData({servcmd:t,data:e}),n=`${r.head.seq}${t}`;return yield i.sendPacket(r,{requestId:n})}catch(e){throw console.warn("getSnapshotInfo error:",e),e}}))}(o,this._core),{download_url:i}=s||{};if(console.log(`${f} _getSnapshotInfoByUrl OK snapshotUrl:`,i),w.isEmpty(i))return{};const r=w.addAuthToUrl(i),{width:a=0,height:d=0}=yield w.probeImageWidthHeight(r);return{snapshotUrl:r,snapshotWidth:a,snapshotHeight:d}}catch(e){throw console.error(`${f} _getSnapshotInfoByUrl error:`,e),e}}))}_reset(){this._messageOptionsMap.clear()}_dispose(){this._reset();const{notificationCenter:e,InnerEvent:t}=this._core;e.unSubscribeInnerEvent(t.DESTROY,this._dispose,this)}};class Y{constructor(e){this.uploadProgress=0,this.type=p,this.content={downloadFlag:2,second:e.second,size:e.size,url:w.addAuthToUrl(e.url),remoteAudioUrl:w.addAuthToUrl(e.url||""),uuid:e.uuid}}static parseServerPushElement(e){const{MsgContent:t}=e,{Url:o,Download_Flag:s,Second:i,Size:r,UUID:n}=t;return new Y({url:o,downloadFlag:s,second:i,size:r,uuid:n})}updatePercent(e){this.uploadProgress=Math.min(e,1)}updateAudioUrl(e){this.content.remoteAudioUrl=e}validateBeforeSend(){const e=""!==this.content.remoteAudioUrl;return{isValid:e,error:e?null:{message:"content can not be empty"}}}convertToBackendFormat(){const{uuid:e,downloadFlag:t,remoteAudioUrl:o,size:s,second:i}=this.content;return{MsgType:this.type,MsgContent:{Url:w.removeAuthToUrl(o),Download_Flag:t,Second:i,Size:s,UUID:e}}}}const J=2108,Q=2300,G=20971520;var X=new class{constructor(){this._messageOptionsMap=new Map}init(e){var t;this._core=e;const{notificationCenter:o,helper:s,InnerEvent:i,message:r}=e;s.registerApi("createAudioMessage",this),null===(t=null==r?void 0:r.messageFactory)||void 0===t||t.registerElementClass(p,Y),o.subscribeInnerEvent(i.DESTROY,this._dispose,this)}createAudioMessage(e){var t,o,s,i,r;try{const i=this._core.ssoLog.createSSOLogData({method:"createAudioMessage"});console.log(`${f} createAudioMessage options:`,e);let{file:r}=e.payload;r=this._processAudioFile(e.payload.file),e.payload.file=r;const n=null===(t=this._core.store.get("login"))||void 0===t?void 0:t.userId,a=null===(s=null===(o=this._core)||void 0===o?void 0:o.message.messageFactory)||void 0===s?void 0:s.createMessage(Object.assign(Object.assign({},e),{from:n})),l={second:Math.floor((r.duration||r.second)/1e3),size:r.fileSize||r.size||1,url:r.tempFilePath||r.uri,uuid:w.generateUUID(r)},d=new Y(l);return a.setElement(d),this._messageOptionsMap.set(a.clientSequence,e),i.end(),a}catch(e){throw null===(r=(i=this._core.ssoLog.getSSOLogData("createAudioMessage")).setError)||void 0===r||r.call(i,e).end(),console.error(`${f} createAudioMessage error:`,e),e}}upload(e){return t(this,void 0,void 0,(function*(){console.log(`${f} uploadAudio message:`,e);const{file:t}=this._messageOptionsMap.get(e.clientSequence).payload;this._validateBeforeUploadAudio(t);const o=e.getElements()[0],s=yield this._performAudioUpload(o,e,t),i=w.addAuthToUrl(null==s?void 0:s.location);return o.updateAudioUrl(i),e}))}_validateBeforeUploadAudio(e){var t;const{ChatError:o}=null===(t=this._core)||void 0===t?void 0:t.helper;if(!e)throw new o({code:Q});if(e.size>G)throw new o({message:`File size exceeds limit: ${c(G)}`});if(0===e.size)throw new o({code:J})}_performAudioUpload(e,o,s){return t(this,void 0,void 0,(function*(){const{to:t}=o,i={uploadFileType:y,file:s,to:t,message:o,onProgress:t=>{var s,i;e.updatePercent(t),null===(i=null===(s=this._messageOptionsMap.get(o.clientSequence))||void 0===s?void 0:s.onProgress)||void 0===i||i.call(s,t)}},{response:r}=yield S.uploadToCOS(i);return r}))}_processAudioFile(e){var t;const{IN_MINI_APP:o,IN_BROWSER:s}=null===(t=this._core)||void 0===t?void 0:t.utils;return o?this._processMiniFile(e):s?this._processWebFile(e):void 0}_processMiniFile(e){return{url:e.tempFilePath,name:e.tempFilePath.slice(e.tempFilePath.lastIndexOf("/")+1),size:e.fileSize,second:e.duration,type:e.tempFilePath.slice(e.tempFilePath.lastIndexOf(".")+1).toLowerCase()}}_processWebFile(e){if(e.tempFilePath||e.uri)return e;const t=URL.createObjectURL(e);return e.tempFilePath=t,e}_reset(){this._messageOptionsMap.clear()}_dispose(){this._reset();const{notificationCenter:e,InnerEvent:t}=this._core;e.unSubscribeInnerEvent(t.DESTROY,this._dispose,this)}};const Z={to:{required:!0,rules:["string"],allowEmpty:!1},conversationType:{required:!0,rules:["string"],allowEmpty:!1},payload:{required:!0,rules:["object"],allowEmpty:!1},cloudCustomData:{required:!1,rules:["string"],allowEmpty:!1},priority:{required:!1,rules:["string"],allowEmpty:!1},customModerationConfigurationID:{required:!1,rules:["string"],allowEmpty:!1},onProgress:{required:!1,rules:["function"],allowEmpty:!1}},ee={createImageMessage:Z,createAudioMessage:Z,createVideoMessage:Z,createFileMessage:Z},te={createImageMessage:!0,createAudioMessage:!0,createVideoMessage:!0,createFileMessage:!0},oe={[u]:E,[g]:V,[m]:K,[p]:X};var se=new class{install(e){this._core=e,E.init(e),V.init(e),K.init(e),X.init(e),S.init(e),w.init(e),e.helper.registerApi("sendMessage",this),e.helper.registerValidateConfig({auth:te,params:ee})}sendMessage(e,o){return t(this,void 0,void 0,(function*(){var t,s,i;try{return console.log("sendMessage message:",e),yield this._upload(e),yield null===(i=null===(s=null===(t=this._core)||void 0===t?void 0:t.message)||void 0===s?void 0:s.messageSender)||void 0===i?void 0:i.sendMessage(e,o)}catch(e){throw console.error("sendMessage error:",e),e}}))}_upload(e){return t(this,void 0,void 0,(function*(){var t,o;if(!0!==e._relayFlag)try{const t=oe[e.type];if(t){const o=this._core.ssoLog.createSSOLogData({method:"upload"});o.setLogInfo({message:`type:${e.type}`}),yield t.upload(e),o.end()}}catch(s){throw e.status=U.FAIL,s instanceof Error&&(s.data={message:e}),this._core.message.messageStore.storeConversationMessage(e),null===(o=(t=this._core.ssoLog.getSSOLogData("upload")).setError)||void 0===o||o.call(t,s).end(),s}}))}};export{se as default};
1
+ function e(e,t){var o={};for(var s in e)Object.prototype.hasOwnProperty.call(e,s)&&t.indexOf(s)<0&&(o[s]=e[s]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var i=0;for(s=Object.getOwnPropertySymbols(e);i<s.length;i++)t.indexOf(s[i])<0&&Object.prototype.propertyIsEnumerable.call(e,s[i])&&(o[s[i]]=e[s[i]])}return o}function t(e,t,o,s){return new(o||(o=Promise))((function(i,r){function n(e){try{l(s.next(e))}catch(e){r(e)}}function a(e){try{l(s.throw(e))}catch(e){r(e)}}function l(e){var t;e.done?i(e.value):(t=e.value,t instanceof o?t:new o((function(e){e(t)}))).then(n,a)}l((s=s.apply(e,t||[])).next())}))}"function"==typeof SuppressedError&&SuppressedError;var o=new class{constructor(){this._name="WebRequest"}init(e){this._core=e}request(e,o){return t(this,void 0,void 0,(function*(){var t;const{isEmpty:s}=null===(t=this._core)||void 0===t?void 0:t.utils,{downloadUrl:i="",method:r="PUT",url:n,qs:a,headers:l={},resources:d,dataType:c="text",uploadByIP:h,uploadIP:u}=e;let p=n;if(a){const e=this._queryString(a);e&&(p+=`${p.includes("?")?"&":"?"}${e}`)}const g=new XMLHttpRequest;g.open(r.toUpperCase(),p,!0),g.responseType=c;const m=Object.assign({},l);if(h&&u&&(m.host=u),!s(m))for(const e in m)m.hasOwnProperty(e)&&!["content-length","user-agent","origin","host"].includes(e.toLowerCase())&&g.setRequestHeader(e,m[e]);return g.onload=()=>{const t=this._getResponseBody(g,i,h&&u),s=this._buildResponse(g,t);if(200===g.status)o(null,s);else{if(u&&!p.includes(u))return e.url=this._domainName2IP(p,u),e.uploadByIP=!0,this.request(e,o);o({code:g.status,message:JSON.stringify(g.responseText)},s)}},g.onerror=()=>{const e=this._getResponseBody(g,i,h&&u),t=this._buildResponse(g,e),s={code:g.status,message:0===g.status?"CORS blocked or network error":JSON.stringify(g.responseText)};o(s,t)},e.onProgress&&g.upload&&(g.upload.onprogress=t=>{const{total:o,loaded:s}=t,i=Math.min(Math.floor(100*s/o),100);e.onProgress({total:o,loaded:s,percent:i/100})}),g.send(d),g}))}_buildResponse(e,t){const o={};return e.getAllResponseHeaders().trim().split("\n").forEach((e=>{if(e){const[t,s]=e.split(":").map((e=>e.trim()));o[t.toLowerCase()]=s}})),{statusCode:e.status,statusMessage:e.statusText,headers:o,data:t}}_getResponseBody(e,t,o){return 200===e.status&&t?{location:t,uploadIP:o}:{response:e.responseText,uploadIP:o}}_queryString(e,t="&",o="="){var s;const{isEmpty:i,isPlainObject:r}=null===(s=this._core)||void 0===s?void 0:s.utils;return i(e)?"":r(e)?Object.keys(e).map((s=>{const i=encodeURIComponent(s)+o;return Array.isArray(e[s])?e[s].map((e=>i+encodeURIComponent(e))).join(t):i+encodeURIComponent(e[s])})).filter(Boolean).join(t):void 0}_domainName2IP(e,t){return e.replace(/^http(s)?:\/\/(.*?)\//,`https://${t}/`)}};const s=["unknown","image","video","audio","log"];var i=new class{init(e){this._core=e}request(t,o){var i;const{MINI_APP_NAMESPACE:r,IN_ALIPAY_MINI_APP:n,IN_UNI_IOS_APP:a}=null===(i=this._core)||void 0===i?void 0:i.utils,{resources:l="",headers:d={},url:c,downloadUrl:h=""}=t;let u=c,p=null;const g=h?h.match(/^(https?:\/\/[^/]+\/)([^/]*\/?)(.*)$/):null;if(!g)return void console.warn("message Invalid download URL format");const m=decodeURIComponent(g[3]),f=m.includes("?")?m.split("?")[0]:m||"",_={key:t.fileKey||f,success_action_status:200,"Content-Type":""},v={};if(a){const[e,t]=c.split("?sign=");t&&(u=`${e}?sign=${encodeURIComponent(t)}`,v.sign=decodeURIComponent(t),v.signature=decodeURIComponent(t))}let I={url:u,header:d,name:"file",filePath:l,formData:Object.assign(Object.assign({},_),v),timeout:t.timeout||3e5};if(n){const o=e(I,["name"]);I=Object.assign(Object.assign({},o),{fileName:"file",fileType:t.fileType?s[t.fileType]:"image"})}return p=r.uploadFile(Object.assign(Object.assign({},I),{success:e=>{this._handleResponse({response:e,downloadUrl:h,callback:o})},fail:e=>{this._handleResponse({response:e,downloadUrl:h,callback:o})}})),p.onProgressUpdate&&p.onProgressUpdate((e=>{t.onProgress&&t.onProgress({total:e.totalBytesExpectedToSend||0,loaded:e.totalBytesSent||0,percent:e.progress?Math.floor(e.progress)/100:0})})),p}_handleResponse(e){const{downloadUrl:t,response:o,callback:s}=e,i={};if(o.header)for(const e in o.header)o.header.hasOwnProperty(e)&&(i[e.toLowerCase()]=o.header[e]);const r=+o.statusCode;200===r?s(null,{statusCode:r,headers:i,data:Object.assign(Object.assign({},o.data),{location:t})}):s({code:r,message:JSON.stringify(o.data)},{statusCode:r,headers:i,data:void 0})}};function r(e){return"file"===function(e){return Object.prototype.toString.call(e).match(/^\[object (.*)\]$/)[1].toLowerCase()}(e)}function n(e){const t=e||99999999;return Math.round(Math.random()*t)}function a(e,t=!0,o=!0){const s=Date.now();return t?o?s-e+" ms":`${Math.round((s-e)/1e3)} s`:o?s-e:Math.round((s-e)/1e3)}function l(e){return`${Array.from({length:8},(()=>Math.floor(65536*(1+Math.random())).toString(16).substring(1))).join("")}-${e}`}function d(e,t){return Math.round(Number(e)*10**t)/10**t}function c(e){const t=1024,o=1048576;return e<t?`${e}B`:e<o?`${Math.floor(e/t)}KB`:`${Math.floor(e/o)}MB`}function h(e){if(e<=1048576){return`${d(e/1024,1)}KB/s`}return`${d(e/1048576,1)}MB/s`}const u="TIMImageElem",p="TIMSoundElem",g="TIMFileElem",m="TIMVideoFileElem",f="RichMediaMessagePlugin",_=["rich.my-imcloud.com","imrich.qcloud.com"],v=1,I=2,y=3;var U;!function(e){e.UNSENT="unSend",e.SUCCESS="success",e.FAIL="fail"}(U||(U={}));var w=new class{init(e){this._core=e}addAuthToUrl(e=""){if(this._isMiniProgramTempFile(e))return e;const t=function(e){return e?e.startsWith("https://")?e:e.startsWith("http://")?e.replace("http://","https://"):e:""}(e);return this.processResourceUrl(t)}removeAuthToUrl(e){return function(e,t){const[o,s]=e.split("?");if(!s)return o;const i=s.split("&").reduce(((e,o)=>{const[s,i]=o.split("=");return s&&s!==t&&(e[s]=i||""),e}),{}),r=Object.keys(i).map((e=>`${e}${i[e]?`=${i[e]}`:""}`)).join("&");return r?`${o}?${r}`:o}(e,"authKey")}_isMiniProgramTempFile(e){return!!this.getPlatformFlags().IN_MINI_APP&&Object.values(TEMP_FILE_PATTERNS).some((t=>t.test(e)))}extractFileFromInput(e){return r(e)?e:function(e){if("object"!=typeof e||null===e)return!1;const t=Object.getPrototypeOf(e);if(null===t)return!0;let o=t;for(;null!==Object.getPrototypeOf(o);)o=Object.getPrototypeOf(o);return t===o}(e)&&"undefined"!=typeof uni?Array.isArray(e.tempFiles)&&e.tempFiles.length>0?e.tempFiles[0]:null:e instanceof HTMLInputElement&&e.files&&e.files.length>0?e.files[0]:null}probeImageWidthHeight(e){return t(this,void 0,void 0,(function*(){var t;const{IN_MINI_APP:o,IN_BROWSER:s}=(null===(t=this._core)||void 0===t?void 0:t.utils)||{};return this._shouldSkipProbing()?{width:0,height:0}:s?this._probeImageDimensionsWeb(e):o?this._probeImageDimensionsMiniApp(e):void 0}))}isSimpleCos(){var e;const t=(null===(e=this._core)||void 0===e?void 0:e.store.get("cloudConfig"))||{},{simple_cos:o}=t;return"0"!==o}getFileDNList(){var e;let t=_;const o=(null===(e=this._core)||void 0===e?void 0:e.store.get("cloudConfig"))||{},{file_dn_list:s}=o;if(void 0===s)return t;try{JSON.parse(s).forEach((e=>{t.includes(e)||t.push(e)}))}catch(e){console.warn(e),t=_}return t}getPlatform(){var e;return null===(e=this._core)||void 0===e?void 0:e.utils.platform}generateUUID(e,t){var o;let s=`${this.getSDKAppID()}-${this.getCurrentUserID()}-${null===(o=this._core)||void 0===o?void 0:o.utils.randomString()}`;if(t)return`${s}.${t}`;const i=e.name||e.value||e.url||e.tempFilePath,r=i&&i.slice(i.lastIndexOf(".")+1);return r&&(s=`${s}.${r}`),s}processResourceUrl(e){if(!e)return"";let t=e;const o=this.getFileDownloadProxy(),s=this.getAuthKey(),i=this.getFileDNList();o&&(e.startsWith("http://")?t=e.replace(/^http:\/\/[^/]+/,o):e.startsWith("https://")&&(t=e.replace(/^https:\/\/[^/]+/,o)));const r=s&&-1===t.indexOf("authKey=")&&function(e,t){let o=!1;if(e){const s=e.match(/:\/\/([0-9]?\.)?(.[^/:]+)/),i=s&&s[2]||"";if(i.includes("rich-dev"))return!0;for(let e=0;e<t.length;e++)if(i.endsWith(t[e])){o=!0;break}}return o}(t,i);return r&&(t=t.indexOf("?")>-1?`${t}&authKey=${s}`:`${t}?authKey=${s}`),t}getCurrentUserID(){var e,t;return null===(t=null===(e=this._core)||void 0===e?void 0:e.store.get("login"))||void 0===t?void 0:t.userId}getSDKAppID(){var e,t;return null===(t=null===(e=this._core)||void 0===e?void 0:e.store.get("instance"))||void 0===t?void 0:t.sdkAppId}getFileDownloadProxy(){var e,t;return(null===(t=null===(e=this._core)||void 0===e?void 0:e.store.get("instance"))||void 0===t?void 0:t.fileDownloadProxy)||""}getFileUploadProxy(){var e,t;return(null===(t=null===(e=this._core)||void 0===e?void 0:e.store.get("instance"))||void 0===t?void 0:t.fileUploadProxy)||""}getAuthKey(){var e,t;return(null===(t=null===(e=this._core)||void 0===e?void 0:e.store.get("login"))||void 0===t?void 0:t.authKey)||""}isPrivateNetWork(){var e,t;return null===(t=null===(e=this._core)||void 0===e?void 0:e.store.get("instance"))||void 0===t?void 0:t.proxyServer}getPlatformFlags(){var e;const{IN_BROWSER:t,IN_MINI_APP:o,IN_RN_APP:s,IN_UNI_NATIVE_APP:i}=null===(e=this._core)||void 0===e?void 0:e.utils;return{IN_BROWSER:t,IN_MINI_APP:o,IN_RN_APP:s,IN_UNI_NATIVE_APP:i}}isEmpty(e){var t;const{isEmpty:o}=null===(t=this._core)||void 0===t?void 0:t.utils;return o(e)}_probeImageDimensionsMiniApp(e){var t;const{MINI_APP_NAMESPACE:o}=(null===(t=this._core)||void 0===t?void 0:t.utils)||{};return new Promise((t=>{o.getImageInfo({src:e,success:e=>t({width:e.width,height:e.height}),fail:()=>t({width:0,height:0})})}))}_shouldSkipProbing(){var e;const{IN_RN_APP:t,IS_IE:o,IE_VERSION:s}=(null===(e=this._core)||void 0===e?void 0:e.utils)||{};return t||o&&9===s}_probeImageDimensionsWeb(e){return new Promise((t=>{const o=new Image,s=()=>{o.onload=null,o.onerror=null,o.src=""};o.onload=()=>{t({width:o.width,height:o.height}),s()},o.onerror=()=>{t({width:0,height:0}),s()},o.src=e}))}};var S=new class{constructor(){this.uploadFileTryCount=0,this.maxRetries=1,this.systemClockOffset=0,this.httpRequest=null,this.uploadFileType="",this.duration=900,this.fetchCosTryCount=0}init(e){var t;this._core=e;const{IN_MINI_APP:s}=e.utils;this.httpRequest=s?i:o,null===(t=this.httpRequest)||void 0===t||t.init(e)}uploadToCOS(e){return t(this,void 0,void 0,(function*(){const t=`${f} uploadToCOS`,{file:o}=e;this.uploadFileType=e.uploadFileType,console.log(`${t} options:`,e);try{const s=Date.now(),i=yield this._createCosOptions(e),r=yield this._uploadFile(i);this._handleUploadError(r,e);const n=this._createUploadResult(o,r),a=Date.now()-s,l=c(o.size),d=`size:${l} time:${a}ms speed:${h(1e3*o.size/a)}`;return console.log(`${t} ok. name:${o.name} ${d}`),{uploadOptions:i,response:n}}catch(e){throw console.warn(`${t} failed, error:`,e),e}}))}_handleUploadError(e,t){var o,s;const{ChatError:i}=null===(o=this._core)||void 0===o?void 0:o.helper;if(403===e.statusCode)throw a(Date.now(),!1),t.url,(null===(s=null==e?void 0:e.data)||void 0===s?void 0:s.uploadIP)&&e.data.uploadIP,new i({message:"Upload failed with status 403"})}_createUploadResult(e,t){return{fileName:e.name,fileSize:e.size,fileType:e.type.slice(e.type.indexOf("/")+1).toLowerCase(),location:t.data.location||"",uploadTime:a(Date.now(),!1),uploadSpeed:h(1e3*e.size/a(Date.now(),!1))}}_createCosOptions(e){return t(this,void 0,void 0,(function*(){const{fileName:t,resources:o,uploadMethod:s}=this._prepareUploadParams(e),i=this._isC2CConversation(e.message.conversationID)?1:2;try{const r=yield this._fetchCosSignatureUrl({fileType:this.uploadFileType,fileName:t,uploadMethod:s,duration:this.duration,userID:e.message.from,conversationType:i}),{uploadUrl:n,downloadUrl:a,requestSnapshotUrl:l,thumbUrl:d,largeUrl:c,fileKey:h}=r,u=!w.isPrivateNetWork()&&r.uploadIP;return{url:this._getRawOrUploadProxyUrl(n),fileType:this.uploadFileType,fileName:t,resources:o,downloadUrl:a,requestSnapshotUrl:l,thumbUrl:d,largeUrl:c,fileKey:h,uploadIP:u||"",onProgress:t=>this._handleUploadProgress(t,e)}}catch(e){throw console.error("Failed to create COS pre-signed URL options:",e),e}}))}_prepareUploadParams(e){console.log(`${f} prepareUploadParams:`,e);const{file:t}=e,{IN_MINI_APP:o,IN_RN_APP:s}=w.getPlatformFlags(),i=o||s,r=i&&e.message.type!==g,{name:a}=t,d=a.slice(a.lastIndexOf(".")),c=`${n(999999)}${d}`;return{fileName:l(r?t.name:c),resources:i?t.url:t,uploadMethod:i?1:0}}_handleUploadProgress(e,t){if("function"==typeof t.onProgress)try{t.onProgress(e.percent)}catch(e){throw console.warn("Upload progress callback error:",e),e}}_fetchCosSignatureUrl(e){return t(this,void 0,void 0,(function*(){const o=`${f} fetchCosSignatureUrl`,s=w.isSimpleCos(),i=this._prepareCosRequestData(e),r=s?"im_cos_msg.simple_sig":"im_cos_msg.pre_sig";try{const e=yield function(e,o,s){return t(this,void 0,void 0,(function*(){try{const{helper:t,channel:i}=s,r=t.generateCosSpecifiedData({servcmd:e,data:o}),n=`${r.head.seq}${e}`;return yield i.sendPacket(r,{requestId:n})}catch(e){throw console.warn("getCosSig error:",e),e}}))}(r,i,this._core);this.fetchCosTryCount=0;const n=this._processResponse(e);return console.log(`${o} ok. isSimpleCos:${s} data:`,n),n||{}}catch(t){if(console.error(`${o} failed, error:`,t),this.fetchCosTryCount<1)return this.fetchCosTryCount++,this._fetchCosSignatureUrl(e);throw this.fetchCosTryCount=0,t}}))}_processResponse(e){var t;const o=w.isSimpleCos(),s=o?null===(t=null==e?void 0:e.rpt_pre_sig)||void 0===t?void 0:t[0]:e;if(!s)return{};if(o){const{str_final_ip:e,rpt_pre_sig:t,uint32_file_id:o,uint32_exist_flag:i,str_download_url:r,str_upload_url:n,str_snapshot_url:a,str_file_key:l}=s;return{uploadIP:e,preSig:t,fileID:o,existFlag:i,downloadUrl:r,uploadUrl:n,requestSnapshotUrl:a,fileKey:l}}const{upload_url:i,download_url:r,snapshot_url:n,thumb_url:a,large_url:l,file_key:d}=s;return{uploadUrl:i,downloadUrl:r,requestSnapshotUrl:n,thumbUrl:a,largeUrl:l,fileKey:d}}_prepareCosRequestData(e){return w.isSimpleCos()?{uint32_upload_method:e.uploadMethod,uint32_platform:w.getPlatform(),uint32_sdkappid:w.getSDKAppID(),str_user_id:e.userID,uint32_scene:e.conversationType,rpt_upload_object:[{uint32_file_id:1,uint32_file_type:e.fileType,str_file_name:e.fileName}]}:{file_type:e.fileType,file_name:e.fileName,upload_method:e.uploadMethod,Duration:e.duration}}_uploadFile(e){return t(this,void 0,void 0,(function*(){return new Promise(((t,o)=>{this.httpRequest.request(e,((s,i)=>{s&&this.uploadFileTryCount<this.maxRetries&&this.shouldRetry(s)?(this.uploadFileTryCount++,this._uploadFile(e).then(t).catch(o)):(this.uploadFileTryCount=0,s?o(s):t(i))}))}))}))}shouldRetry(e){if(!e)return!1;if(5===Math.floor(e.statusCode/100))return!0;return!(!this.isTimeRelatedError(e)||!this._isClockOutOfSync(e))&&(this._syncSystemClock(e),!0)}isTimeRelatedError(e){var t,o;try{const s=null===(t=e.error)||void 0===t?void 0:t.Code,i=null===(o=e.error)||void 0===o?void 0:o.Message;return"RequestTimeTooSkewed"===s||"AccessDenied"===s&&"Request has expired"===i}catch(e){return!1}}_isClockOutOfSync(e){var t,o,s;const i=(null===(t=e.headers)||void 0===t?void 0:t.date)||(null===(o=e.headers)||void 0===o?void 0:o.Date)||(null===(s=e.error)||void 0===s?void 0:s.ServerTime);if(!i)return!1;const r=Date.now(),n=Date.parse(i);return Math.abs(r+this.systemClockOffset-n)>=3e4}_syncSystemClock(e){var t,o,s;const i=(null===(t=e.headers)||void 0===t?void 0:t.date)||(null===(o=e.headers)||void 0===o?void 0:o.Date)||(null===(s=e.error)||void 0===s?void 0:s.ServerTime);if(i){const e=Date.now(),t=Date.parse(i);this.systemClockOffset=t-e}}_getRawOrUploadProxyUrl(e){const t=w.getFileUploadProxy();let o=e;return t&&(o=e.replace(/^https:\/\/[^/]+/,t)),o}_isC2CConversation(e){return"C2C"===e.slice(0,3)}};const P=2108,F=2251,M=2252,b=["jpg","jpeg","gif","png","bmp","image","webp"],A=20971520,O={JPG:1,JPEG:1,GIF:2,PNG:3,BMP:4,UNKNOWN:255};class T{constructor(e,t){this.instanceID=n(9999999),this.sizeType=e.type||0,this.type=0,this.size=e.size||0,this.width=e.width||0,this.height=e.height||0,this.imageUrl=w.addAuthToUrl(e.imageUrl||e.url||""),this.url=w.addAuthToUrl(e.url||t)}setSizeType(e){this.sizeType=e}setType(e){this.type=e}setImageUrl(e){e&&(this.imageUrl=w.addAuthToUrl(e))}getImageUrl(){return this.imageUrl}}function N(t){const{originUrl:o,originWidth:s,originHeight:i,min:r=198}=t,n=parseInt(s)||0,a=parseInt(i)||0,l={url:void 0,width:0,height:0};if((n<=a?n:a)<=r)l.url=o,l.width=n,l.height=a;else{a<=n?(l.width=Math.ceil(n*r/a),l.height=r):(l.width=r,l.height=Math.ceil(a*r/n));const e=o&&o.indexOf("?")>-1?`${o}&`:`${o}?`;l.url=198===r?`${e}imageView2/3/w/198/h/198`:`${e}imageView2/3/w/720/h/720`}if(void 0===o){return e(l,["url"])}return l}class C{constructor(e){this._imageMemoryURL="",this._percent=0,this.type=u;const{uuid:t,file:o,imageFormat:s,imageInfoArray:i=[]}=e;this._imageMemoryURL=this.createImageDataAsURL(o),this.content={imageFormat:s,uuid:t,imageInfoArray:[]},this.initImageInfoArray(i),this.autoFixUrl()}static parseServerPushElement(e){const{MsgContent:t}=e,{ImageFormat:o,ImageInfoArray:s,UUID:i}=t,r=function(e){return e.map((e=>({size:e.Size,type:e.Type,width:e.Width,height:e.Height,url:e.URL})))}(s);return new C({imageFormat:o,imageInfoArray:r,uuid:i})}createImageDataAsURL(e){let t="";const{IN_MINI_APP:o,IN_RN_APP:s,IN_BROWSER:i}=w.getPlatformFlags();return e?((o||s)&&(t=e.url),i&&(t=window.URL.createObjectURL(e)),t):t}initImageInfoArray(e=[]){const t={type:0,size:0,width:0,height:0,url:""};for(let o=0;o<3;o++){const s=e[o]||Object.assign({},t),i=new T(s,this._imageMemoryURL);i.setSizeType(o+1),i.setType(o),this.addImageInfo(i)}this.updateAccessSideImageInfoArray()}autoFixUrl(){const e=["http","https"];this.content.imageInfoArray.forEach((t=>{if(!t.url||""===t.imageUrl)return;const[o,...s]=t.imageUrl.split("://"),i=s.join("://");e.includes(o)||t.setImageUrl(`https://${i}`)}))}updatePercent(e){this._percent=Math.min(e,1)}updateImageFormat(e){this.content.imageFormat=O[e.toUpperCase()]||O.UNKNOWN}addImageInfo(e){this.content.imageInfoArray.length>=3||this.content.imageInfoArray.push(e)}updateImageInfoArray(e){const t=this.content.imageInfoArray.length;let o;for(let s=0;s<t;s++)o=this.content.imageInfoArray[s],e[s].size&&(o.size=e[s].size),e[s].url&&o.setImageUrl(e[s].url),e[s].width&&(o.width=e[s].width),e[s].height&&(o.height=e[s].height)}updateAccessSideImageInfoArray(){const[e]=this.content.imageInfoArray;e&&0!==e.width&&0!==e.height&&(!function(e){const t=e[2];e[2]=e[1],e[1]=t;for(let t=0;t<e.length;t++)e[t].setType(t)}(this.content.imageInfoArray),Object.assign(this.content.imageInfoArray[2],N({originWidth:e.width,originHeight:e.height,min:720})))}validateBeforeSend(){const[e]=this.content.imageInfoArray,t=!!e&&""!==e.imageUrl&&0!==e.size;return{isValid:t,error:t?null:{message:"content can not be empty"}}}transformToServerFormat(e){const{isMergerMessage:t=!1}=e||{},o=t?this.payload:this.content,{uuid:s,imageFormat:i,imageInfoArray:r}=o;return{MsgType:this.type,MsgContent:{ImageFormat:i,ImageInfoArray:this.parseImageInfoArray(r),UUID:s}}}parseImageInfoArray(e){return e.map((e=>({InstanceId:e.instanceID,Type:e.sizeType,MsgType:e.type,Size:e.size,Width:e.width,Height:e.height,URL:w.removeAuthToUrl(e.imageUrl)})))}}var E=new class{constructor(){this._messageOptionsMap=new Map}init(e){var t;this._core=e;const{notificationCenter:o,helper:s,InnerEvent:i,message:r}=e;s.registerApi({apiName:"createImageMessage",context:this}),null===(t=null==r?void 0:r.messageFactory)||void 0===t||t.registerElementClass(u,C),o.subscribeInnerEvent(i.DESTROY,this._dispose,this)}createImageMessage(e){var t,o,s,i,r;try{const i=this._core.ssoLog.createSSOLogData({method:"createImageMessage"});console.log(`${f} createImageMessage options:`,e);const r=null===(t=this._core.store.get("login"))||void 0===t?void 0:t.userId,n=null===(s=null===(o=this._core)||void 0===o?void 0:o.message.messageFactory)||void 0===s?void 0:s.createMessage(Object.assign(Object.assign({},e),{from:r})),a=this._processImage(e);e.payload.file=a;const l={imageFormat:O.UNKNOWN,uuid:w.generateUUID(a),file:a,imageInfoArray:[]},d=new C(l);return n.setElement(d),this._messageOptionsMap.set(n.clientSequence,e),console.log(`${f} createImageMessage OK imageMessage:`,n),i.end(),n}catch(e){throw null===(r=(i=this._core.ssoLog.getSSOLogData("createImageMessage")).setError)||void 0===r||r.call(i,e).end(),console.error(`${f} createImageMessage error:`,e),e}}upload(e){return t(this,void 0,void 0,(function*(){console.log(`${f} uploadImage message:`,e);const t=e.getElements()[0],{file:o}=this._messageOptionsMap.get(e.clientSequence).payload;this._validateBeforeUploadImage(o);const s=yield this._performImageUpload(t,e,o),i=this._generateImageInfo(s);return t.updateImageInfoArray(i),e}))}_performImageUpload(e,o,s){return t(this,void 0,void 0,(function*(){const{to:t}=o,i={uploadFileType:v,file:s,to:t,message:o,onProgress:t=>{var s,i;e.updatePercent(t),null===(i=null===(s=this._messageOptionsMap.get(o.clientSequence))||void 0===s?void 0:s.onProgress)||void 0===i||i.call(s,t)}},{uploadOptions:r,response:n}=yield S.uploadToCOS(i);return this._parseResponse(r,n)}))}_generateImageInfo(e){console.log(`${f} generateImageInfo`);const{location:t,fileSize:o,width:s,height:i,smallImageUrl:r,smallImageWidth:n,smallImageHeight:a,largeImageUrl:l,largeImageWidth:d,largeImageHeight:c,imageInfoArray:h}=e,u=w.addAuthToUrl(t),p={size:o,url:u,width:s,height:i};return(null==h?void 0:h.length)>0?this._processImageInfoArray(h,o):r&&l?[Object.assign({},p),{largeImageUrl:l,largeImageWidth:d,largeImageHeight:c},{smallImageUrl:r,smallImageWidth:n,smallImageHeight:a}]:[Object.assign({},p),this._generateThumbInfo(u,s,i,720),this._generateThumbInfo(u,s,i,198)]}_generateThumbInfo(e,t,o,s){return N({originUrl:e,originWidth:t,originHeight:o,min:s})}_processImageInfoArray(e,t){let o,s,i;for(const r of e)1===r.type?(s=r,s.size=t):2===r.type?(i=r,i.size=t):(o=r,o.size=t);return[Object.assign({},o),Object.assign({},i),Object.assign({},s)]}_parseResponse(e,o){return t(this,void 0,void 0,(function*(){console.log(`${f} parseResponse`);try{const{thumbUrl:t,largeUrl:s,downloadUrl:i}=e;t&&s&&(yield this._getImageInfoByUrl(t,o,"thumb"),yield this._getImageInfoByUrl(s,o,"large"));if(w.isSimpleCos()&&!w.isPrivateNetWork()&&(yield this._getImageInfoArray(i,o),null==o?void 0:o.uploadIP)){const e=this._extractDomainFromUrl(i);e&&(yield this._getDownloadIP(e,o))}return o}catch(e){throw console.error("Failed to parse response:",e),e}}))}_extractDomainFromUrl(e){try{const t=e.match(/:\/\/([^\/]+)/);return t?t[1]:null}catch(e){return console.warn("Failed to extract domain from URL:",e),null}}_getImageInfoByUrl(e,o,s){return t(this,void 0,void 0,(function*(){try{const t=w.addAuthToUrl(e),{width:i=0,height:r=0}=yield w.probeImageWidthHeight(t);o.width=i,o.height=r,"thumb"===s?(o.smallImageUrl=e,o.smallImageWidth=i,o.smallImageHeight=r):(o.largeImageUrl=e,o.largeImageWidth=i,o.largeImageHeight=r)}catch(e){console.warn(`Failed to get ${s} image info:`,e)}}))}_validateBeforeUploadImage(e){var t;const{ChatError:o}=null===(t=this._core)||void 0===t?void 0:t.helper;if(!e)throw new o({code:F});this._checkImageType(e),this._checkImageSize(e)}_processImage(e){var t;try{const{IN_MINI_APP:o}=null===(t=this._core)||void 0===t?void 0:t.utils;let{file:s}=e.payload;return s=o?this._processMiniAppImageFile(s):this._processWebImageFile(s),s}catch(e){throw console.warn(`${f} _processImage error:`,e),e}}_processMiniAppImageFile(e){r(e)&&console.warn("FileUnsupportedInMiniApp","createImageMessage");const t=e.tempFiles[0].path||e.tempFiles[0].tempFilePath;return{url:t,name:t.slice(t.lastIndexOf("/")+1),size:e.tempFiles&&e.tempFiles[0].size||1,type:t.slice(t.lastIndexOf(".")+1).toLowerCase()}}_processWebImageFile(e){var t;const{ChatError:o}=null===(t=this._core)||void 0===t?void 0:t.helper,s=w.extractFileFromInput(e);if(!s)throw new o({message:"Invalid file. Pass either `e.target` (from file input) or a File object"});return s}_getDownloadIP(e,o){return t(this,void 0,void 0,(function*(){const s=`${f} getDownloadIP domainName: ${e}`;try{const i=yield function(e,o){return t(this,void 0,void 0,(function*(){try{const{helper:t,channel:s}=o,i="im_cos_msg.get_final_ip",r={str_domain:e},n=t.generateProtocolData({servcmd:i,data:r}),a=`${n.head.seq}${i}`;return yield s.sendPacket(n,{requestId:a})}catch(e){throw console.warn("getFinalIP error:",e),e}}))}(e,this._core);if(!i||!i.str_final_ip)return;console.log(`${s} ok. downloadIP:${i}`);const r=o.location.split("/");r[0]=i.str_final_ip,o.location=r.join("/")}catch(e){console.warn(e)}}))}_getImageInfoArray(e,o){return t(this,void 0,void 0,(function*(){const s=`${f}._getImageInfoArray`;try{const i=yield function(e,o){return t(this,void 0,void 0,(function*(){try{const{helper:t,channel:s}=o,i="im_cos_msg.get_imageinfo",r={str_image_url:e},n=t.generateProtocolData({servcmd:i,data:r}),a=`${n.head.seq}${i}`;return yield s.sendPacket(n,{requestId:a})}catch(e){throw console.warn("getImageInfo error:",e),e}}))}(e,this._core);return o.imageInfoArray=this._processImageInfoResponse(i),console.log(`${s} ok`),o}catch(e){throw o.imageInfoArray=void 0,console.warn(`${s} failed, error:`,e),e}}))}_processImageInfoResponse(e){if(!e)return[];const{rpt_msg_image_info:t}=e;return t.map((e=>({type:e.uint32_image_type,url:e.str_url,width:e.uint32_width,height:e.uint32_height,imageFormat:e.str_image_format})))}_checkImageType(e){const{utils:t,helper:o}=this._core;let s="";if(t.IN_MINI_APP&&(s=e.url.slice(e.url.lastIndexOf(".")+1)),t.IN_BROWSER&&(s=e.name.slice(e.name.lastIndexOf(".")+1)),b.indexOf(s.toLowerCase())<0)throw new o.ChatError({code:M})}_checkImageSize(e){const{utils:t,helper:o}=this._core;let s=0;if(s=(t.IN_MINI_APP,e.size),0===s)throw new o.ChatError({code:P});if(s>=A)throw new o.ChatError({message:`File size exceeds limit: ${c(A)}`})}_reset(){this._messageOptionsMap.clear()}_dispose(){this._reset();const{notificationCenter:e,InnerEvent:t}=this._core;e.unSubscribeInnerEvent(t.DESTROY,this._dispose,this)}};const D=2108,$=2401,R="2.5.0",z="1.18.0",x=104857600;function W(e,t){const o=e.split("."),s=t.split("."),i=Math.max(o.length,s.length);for(;o.length<i;)o.push("0");for(;s.length<i;)s.push("0");for(let e=0;e<i;e++){const t=parseInt(o[e]),i=parseInt(s[e]);if(t>i)return 1;if(t<i)return-1}return 0}class j{constructor(e){this.type=g,this.uploadProgress=0;const t=this._getFileInfo(e);this.content={downloadFlag:2,fileUrl:w.addAuthToUrl(e.url||e.fileUrl)||"",uuid:e.uuid,fileName:t.name||"",fileSize:t.size||0}}static parseServerPushElement(e){const{MsgContent:t}=e,{Download_Flag:o,Url:s,FileName:i,FileSize:r,UUID:n}=t;return new j({downloadFlag:o,url:s,fileName:i,fileSize:r,uuid:n})}updatePercent(e){this.uploadProgress=Math.min(e,1)}updateFileUrl(e){this.content.fileUrl=e}validateBeforeSend(){const e=""!==this.content.fileUrl&&""!==this.content.fileName&&this.content.fileSize>0;return{isValid:e,error:e?null:{message:"content can not be empty"}}}transformToServerFormat(e){const{isMergerMessage:t=!1}=e||{},o=t?this.payload:this.content,{uuid:s,downloadFlag:i,fileUrl:r,fileName:n,fileSize:a}=o;return{MsgType:this.type,MsgContent:{Download_Flag:i,Url:w.removeAuthToUrl(r),FileName:n,FileSize:a,UUID:s}}}_getFileInfo(e){if(e.fileName&&e.fileSize)return{size:e.fileSize,name:e.fileName};const{file:t}=e;return t?(w.getPlatform().IN_UNI_NATIVE_APP&&this._processNativeAppFile(t),{size:t.size,name:t.name}):{size:0,name:""}}_processNativeAppFile(e){if(e.path&&e.path.includes(".")){const t=e.path.slice(e.path.lastIndexOf(".")+1).toLowerCase();e.type=t,e.name||(e.name=`${n(999999)}.${t}`)}e.name||(e.type="",e.name=e.path.slice(e.path.lastIndexOf("/")+1).toLowerCase()),e.suffix&&(e.type=e.suffix),e.url||(e.url=e.path)}}var L=new class{constructor(){this._messageOptionsMap=new Map}init(e){var t;this._core=e;const{notificationCenter:o,helper:s,InnerEvent:i,message:r}=e;s.registerApi({apiName:"createFileMessage",context:this}),null===(t=null==r?void 0:r.messageFactory)||void 0===t||t.registerElementClass(g,j),o.subscribeInnerEvent(i.DESTROY,this._dispose,this)}createFileMessage(e){var t,o,s,i,r;try{const i=this._core.ssoLog.createSSOLogData({method:"createFileMessage"});console.log(`${f} createFileMessage options:`,e),this._checkVersion();const r=this._processFile(e.payload.file);e.payload.file=r;const n=null===(t=this._core.store.get("login"))||void 0===t?void 0:t.userId,a=null===(s=null===(o=this._core)||void 0===o?void 0:o.message.messageFactory)||void 0===s?void 0:s.createMessage(Object.assign(Object.assign({},e),{from:n})),l={uuid:w.generateUUID(r),file:r},d=new j(l);return a.setElement(d),this._messageOptionsMap.set(a.clientSequence,e),console.log(`${f} createFileMessage success fileMessage:`,a),i.end(),a}catch(e){throw null===(r=(i=this._core.ssoLog.getSSOLogData("createFileMessage")).setError)||void 0===r||r.call(i,e).end(),console.error(`${f} createFileMessage error:`,e),e}}upload(e){return t(this,void 0,void 0,(function*(){console.log(`${f} uploadFile message:`,e);const{file:t}=this._messageOptionsMap.get(e.clientSequence).payload;this._validateBeforeUploadFile(t);const o=e.getElements()[0],s=yield this._performFileUpload(o,e,t),i=w.addAuthToUrl(null==s?void 0:s.location);return o.updateFileUrl(i),e}))}_validateBeforeUploadFile(e){var t;const{ChatError:o}=null===(t=this._core)||void 0===t?void 0:t.helper;if(!e)throw new o({code:$});if(e.size>x)throw new o({message:`File size exceeds limit: ${c(x)}`});if(0===e.size)throw new o({code:D})}_performFileUpload(e,o,s){return t(this,void 0,void 0,(function*(){const{to:t}=o,i={uploadFileType:v,file:s,to:t,message:o,onProgress:t=>{var s,i;e.updatePercent(t),null===(i=null===(s=this._messageOptionsMap.get(o.clientSequence))||void 0===s?void 0:s.onProgress)||void 0===i||i.call(s,t)}},{response:r}=yield S.uploadToCOS(i);return r}))}_processFile(e){var t,o;const{IN_BROWSER:s,IN_RN_APP:i,IN_WX_MINI_APP:r,IN_QQ_MINI_APP:n,IN_UNI_NATIVE_APP:a}=null===(t=this._core)||void 0===t?void 0:t.utils,{ChatError:l}=null===(o=this._core)||void 0===o?void 0:o.helper;if(s||a){const t=w.extractFileFromInput(e);if(!t)throw new l({message:"Invalid file. Pass either `e.target` (from file input) or a File object"});return t}if(r||n){const{tempFiles:t}=e;return Object.assign(Object.assign({},t[0]),{url:t[0].path})}return i?Object.assign(Object.assign({},e),{url:e.uri}):e}_checkVersion(){var e,t;const{MINI_APP_NAMESPACE:o,IN_MINI_APP:s,IN_WX_MINI_APP:i,IN_QQ_MINI_APP:r,IN_UNI_NATIVE_APP:n}=null===(e=this._core)||void 0===e?void 0:e.utils,{ChatError:a}=null===(t=this._core)||void 0===t?void 0:t.helper;if(s){if(!(i||r||n))throw new a({message:"Unsupported mini app environment"});const e=o.getSystemInfoSync().SDKVersion;if(i&&W(e,R)<0){throw new a({message:`WXChooseMessageFile requires SDK version ${R} or higher`})}if(r&&W(e,z)<0){throw new a({message:`QQChooseMessageFile requires SDK version ${z} or higher`})}}}_reset(){this._messageOptionsMap.clear()}_dispose(){this._reset();const{notificationCenter:e,InnerEvent:t}=this._core;e.unSubscribeInnerEvent(t.DESTROY,this._dispose,this)}};const V=2108,q=2352,k=["mp4","quicktime","mov"],B=104857600;class H{constructor(e){this.type=m,this.uploadProgress=0;const t="number"==typeof(null==e?void 0:e.videoSecond)?null==e?void 0:e.videoSecond:0;this.content={remoteVideoUrl:w.addAuthToUrl(e.remoteVideoUrl||e.videoUrl||""),videoFormat:e.videoFormat,videoSecond:parseInt(null==t?void 0:t.toString(),10),videoSize:e.videoSize,videoUrl:w.addAuthToUrl(e.videoUrl),videoDownloadFlag:2,videoUUID:e.videoUUID,thumbUUID:e.thumbUUID,thumbFormat:e.thumbFormat,thumbWidth:e.thumbWidth,snapshotWidth:e.thumbWidth,thumbHeight:e.thumbHeight,snapshotHeight:e.thumbHeight,thumbSize:e.thumbSize,snapshotSize:e.thumbSize,thumbDownloadFlag:2,thumbUrl:w.addAuthToUrl(e.thumbUrl),snapshotUrl:w.addAuthToUrl(e.thumbUrl)}}static parseServerPushElement(e){const{MsgContent:t}=e,{VideoUrl:o,VideoFormat:s,VideoSecond:i,VideoSize:r,VideoDownloadFlag:n,VideoUUID:a,ThumbUUID:l,ThumbFormat:d,ThumbWidth:c,SnapshotWidth:h,ThumbHeight:u,SnapshotHeight:p,ThumbSize:g,SnapshotSize:m,ThumbDownloadFlag:f,ThumbUrl:_,SnapshotUrl:v}=t;return new H({videoUrl:o,videoFormat:s,videoSecond:i,videoSize:r,videoDownloadFlag:n,videoUUID:a,thumbUUID:l,thumbFormat:d,thumbWidth:c,snapshotWidth:h,thumbHeight:u,snapshotHeight:p,thumbSize:g,snapshotSize:m,thumbDownloadFlag:f,thumbUrl:_,snapshotUrl:v})}updatePercent(e){this.uploadProgress=Math.min(e,1)}updateVideoUrl(e){e&&(this.content.remoteVideoUrl=e)}updateSnapshotInfo(e){const{snapshotUrl:t,snapshotWidth:o,snapshotHeight:s}=e;w.isEmpty(t)||(this.content.thumbUrl=this.content.snapshotUrl=t),w.isEmpty(o)||(this.content.thumbWidth=this.content.snapshotWidth=Number(o)),w.isEmpty(s)||(this.content.thumbHeight=this.content.snapshotHeight=Number(s))}validateBeforeSend(){const e=""!==this.content.remoteVideoUrl;return{isValid:e,error:e?null:{message:"content can not be empty"}}}transformToServerFormat(e){const{isMergerMessage:t=!1}=e||{},o=t?this.payload:this.content,{remoteVideoUrl:s,videoFormat:i,videoSecond:r,videoSize:n,videoDownloadFlag:a,videoUUID:l,thumbUUID:d,thumbFormat:c,thumbWidth:h,snapshotWidth:u,thumbHeight:p,snapshotHeight:g,thumbSize:m,snapshotSize:f,thumbDownloadFlag:_,thumbUrl:v,snapshotUrl:I}=o;return{MsgType:this.type,MsgContent:{VideoUrl:w.removeAuthToUrl(s),VideoFormat:i,VideoSecond:r,VideoSize:n,VideoDownloadFlag:a,VideoUUID:l,ThumbUUID:d,ThumbFormat:c,ThumbWidth:h,SnapshotWidth:u,ThumbHeight:p,SnapshotHeight:g,ThumbSize:m,SnapshotSize:f,ThumbDownloadFlag:_,ThumbUrl:w.removeAuthToUrl(v),SnapshotUrl:w.removeAuthToUrl(I)}}}}var K=new class{constructor(){this._messageOptionsMap=new Map}init(e){var t;this._core=e;const{notificationCenter:o,helper:s,InnerEvent:i,message:r}=e;s.registerApi({apiName:"createVideoMessage",context:this}),null===(t=null==r?void 0:r.messageFactory)||void 0===t||t.registerElementClass(m,H),o.subscribeInnerEvent(i.DESTROY,this._dispose,this)}createVideoMessage(e){var t,o,s,i,r;try{const i=this._core.ssoLog.createSSOLogData({method:"createVideoMessage"});console.log(`${f} createVideoMessage options:`,e);const r=this._processVideo(e);e.payload.file=r;const n=null===(t=this._core.store.get("login"))||void 0===t?void 0:t.userId,a=null===(s=null===(o=this._core)||void 0===o?void 0:o.message.messageFactory)||void 0===s?void 0:s.createMessage(Object.assign(Object.assign({},e),{from:n})),l={videoFormat:r.videoFile.type,videoSecond:d(r.videoFile.second,0),videoSize:r.videoFile.size,remoteVideoUrl:"",videoUrl:r.videoFile.url,videoUUID:w.generateUUID(r.videoFile),thumbUUID:w.generateUUID(r.videoFile,"jpg"),thumbWidth:r.width||200,thumbHeight:r.height||200,thumbUrl:r.thumbUrl,thumbSize:r.thumbSize,thumbFormat:"jpg"},c=new H(l);return a.setElement(c),this._messageOptionsMap.set(a.clientSequence,e),i.end(),a}catch(e){throw null===(r=(i=this._core.ssoLog.getSSOLogData("createVideoMessage")).setError)||void 0===r||r.call(i,e).end(),console.error(`${f} createVideoMessage error:`,e),e}}upload(e){return t(this,void 0,void 0,(function*(){console.log(`${f} uploadVideo message:`,e);const t=e.getElements()[0],{file:o}=this._messageOptionsMap.get(e.clientSequence).payload;this._validateBeforeUploadVideo(o);const s=yield this._performVideoUpload(t,e,o),{location:i,snapshotInfo:r}=s,n=w.addAuthToUrl(i);return t.updateVideoUrl(n),w.isEmpty(r)||t.updateSnapshotInfo(r),e}))}_validateBeforeUploadVideo(e){var t;const{ChatError:o}=null===(t=this._core)||void 0===t?void 0:t.helper;if(e.videoFile.size>B)throw new o({message:`File size exceeds limit: ${c(B)}`});if(0===e.videoFile.size)throw new o({code:V});if(-1===k.indexOf(e.videoFile.type))throw new o({code:q})}_performVideoUpload(e,o,s){return t(this,void 0,void 0,(function*(){const{to:t}=o,i={uploadFileType:I,file:s,to:t,message:o,onProgress:t=>{var s,i;e.updatePercent(t),null===(i=null===(s=this._messageOptionsMap.get(o.clientSequence))||void 0===s?void 0:s.onProgress)||void 0===i||i.call(s,t)}},{response:r,uploadOptions:n}=yield S.uploadToCOS(i);return{snapshotInfo:yield this._getSnapshotInfoByUrl(n.requestSnapshotUrl),location:r.location}}))}_processVideo(e){var t,o;try{const{ChatError:s}=null===(t=this._core)||void 0===t?void 0:t.helper,{IN_MINI_APP:i,IN_BROWSER:r}=null===(o=this._core)||void 0===o?void 0:o.utils;let{file:n}=e.payload,a={};if(i&&(a=this._processMiniVideoFile(n),n.name=a.name,n.url=a.url),r){const e=w.extractFileFromInput(n);if(!e)throw new s({message:"Invalid file. Pass either `e.target` (from file input) or a File object"});n=e,a=this._processWebVideoFile(n)}return n.videoFile=a,n.thumbUrl="",n.thumbSize=0,n}catch(e){throw console.warn(`${f} _processFile error:`,e),e}}_processMiniVideoFile(e){var t,o;const{IN_ALIPAY_MINI_APP:s}=null===(t=this._core)||void 0===t?void 0:t.utils,{ChatError:i}=null===(o=this._core)||void 0===o?void 0:o.helper;if(s)throw new i({message:"VideoUnsupportedInAlipay"});if(r(e))throw new i({message:"FileUnsupportedInMiniApp"});return Array.isArray(e.tempFiles)&&(e=e.tempFiles[0]),{url:e.tempFilePath,name:e.tempFilePath.slice(e.tempFilePath.lastIndexOf("/")+1),size:e.size||1,second:e.duration||0,type:e.tempFilePath.slice(e.tempFilePath.lastIndexOf(".")+1).toLowerCase()}}_processWebVideoFile(e){const{name:t,size:o=1,duration:s=0,type:i}=e,r=i.split("/")[1];return{url:window.URL.createObjectURL(e),name:t,size:o,second:s,type:r}}_getSnapshotInfoByUrl(e){return t(this,void 0,void 0,(function*(){try{console.log(`${f} _getSnapshotInfoByUrl url:`,e);const o={version:1,platform:w.getPlatform(),cover_name:l(n(99999)),snapshot_url:e},s=yield function(e,o){return t(this,void 0,void 0,(function*(){try{const t="im_cos_msg.video_cover",{helper:s,channel:i}=o,r=s.generateCosSpecifiedData({servcmd:t,data:e}),n=`${r.head.seq}${t}`;return yield i.sendPacket(r,{requestId:n})}catch(e){throw console.warn("getSnapshotInfo error:",e),e}}))}(o,this._core),{download_url:i}=s||{};if(console.log(`${f} _getSnapshotInfoByUrl OK snapshotUrl:`,i),w.isEmpty(i))return{};const r=w.addAuthToUrl(i),{width:a=0,height:d=0}=yield w.probeImageWidthHeight(r);return{snapshotUrl:r,snapshotWidth:a,snapshotHeight:d}}catch(e){throw console.error(`${f} _getSnapshotInfoByUrl error:`,e),e}}))}_reset(){this._messageOptionsMap.clear()}_dispose(){this._reset();const{notificationCenter:e,InnerEvent:t}=this._core;e.unSubscribeInnerEvent(t.DESTROY,this._dispose,this)}};class Y{constructor(e){this.uploadProgress=0,this.type=p,this.content={downloadFlag:2,second:e.second,size:e.size,url:w.addAuthToUrl(e.url),remoteAudioUrl:w.addAuthToUrl(e.url||""),uuid:e.uuid}}static parseServerPushElement(e){const{MsgContent:t}=e,{Url:o,Download_Flag:s,Second:i,Size:r,UUID:n}=t;return new Y({url:o,downloadFlag:s,second:i,size:r,uuid:n})}updatePercent(e){this.uploadProgress=Math.min(e,1)}updateAudioUrl(e){this.content.remoteAudioUrl=e}validateBeforeSend(){const e=""!==this.content.remoteAudioUrl;return{isValid:e,error:e?null:{message:"content can not be empty"}}}transformToServerFormat(e){const{isMergerMessage:t=!1}=e||{},o=t?this.payload:this.content,{uuid:s,downloadFlag:i,remoteAudioUrl:r,size:n,second:a}=o;return{MsgType:this.type,MsgContent:{Url:w.removeAuthToUrl(r),Download_Flag:i,Second:a,Size:n,UUID:s}}}}const G=2108,J=2300,Q=20971520;var X=new class{constructor(){this._messageOptionsMap=new Map}init(e){var t;this._core=e;const{notificationCenter:o,helper:s,InnerEvent:i,message:r}=e;s.registerApi({apiName:"createAudioMessage",context:this}),null===(t=null==r?void 0:r.messageFactory)||void 0===t||t.registerElementClass(p,Y),o.subscribeInnerEvent(i.DESTROY,this._dispose,this)}createAudioMessage(e){var t,o,s,i,r;try{const i=this._core.ssoLog.createSSOLogData({method:"createAudioMessage"});console.log(`${f} createAudioMessage options:`,e);let{file:r}=e.payload;r=this._processAudioFile(e.payload.file),e.payload.file=r;const n=null===(t=this._core.store.get("login"))||void 0===t?void 0:t.userId,a=null===(s=null===(o=this._core)||void 0===o?void 0:o.message.messageFactory)||void 0===s?void 0:s.createMessage(Object.assign(Object.assign({},e),{from:n})),l={second:Math.floor((r.duration||r.second)/1e3),size:r.fileSize||r.size||1,url:r.tempFilePath||r.uri||r.url,uuid:w.generateUUID(r)},d=new Y(l);return a.setElement(d),this._messageOptionsMap.set(a.clientSequence,e),i.end(),a}catch(e){throw null===(r=(i=this._core.ssoLog.getSSOLogData("createAudioMessage")).setError)||void 0===r||r.call(i,e).end(),console.error(`${f} createAudioMessage error:`,e),e}}upload(e){return t(this,void 0,void 0,(function*(){console.log(`${f} uploadAudio message:`,e);const{file:t}=this._messageOptionsMap.get(e.clientSequence).payload;this._validateBeforeUploadAudio(t);const o=e.getElements()[0],s=yield this._performAudioUpload(o,e,t),i=w.addAuthToUrl(null==s?void 0:s.location);return o.updateAudioUrl(i),e}))}_validateBeforeUploadAudio(e){var t;const{ChatError:o}=null===(t=this._core)||void 0===t?void 0:t.helper;if(!e)throw new o({code:J});if(e.size>Q)throw new o({message:`File size exceeds limit: ${c(Q)}`});if(0===e.size)throw new o({code:G})}_performAudioUpload(e,o,s){return t(this,void 0,void 0,(function*(){const{to:t}=o,i={uploadFileType:y,file:s,to:t,message:o,onProgress:t=>{var s,i;e.updatePercent(t),null===(i=null===(s=this._messageOptionsMap.get(o.clientSequence))||void 0===s?void 0:s.onProgress)||void 0===i||i.call(s,t)}},{response:r}=yield S.uploadToCOS(i);return r}))}_processAudioFile(e){var t;const{IN_MINI_APP:o,IN_BROWSER:s}=null===(t=this._core)||void 0===t?void 0:t.utils;return o?this._processMiniFile(e):s?this._processWebFile(e):void 0}_processMiniFile(e){return{url:e.tempFilePath,name:e.tempFilePath.slice(e.tempFilePath.lastIndexOf("/")+1),size:e.fileSize,second:e.duration,type:e.tempFilePath.slice(e.tempFilePath.lastIndexOf(".")+1).toLowerCase()}}_processWebFile(e){if(e.tempFilePath||e.uri)return e;const t=URL.createObjectURL(e);return e.tempFilePath=t,e}_reset(){this._messageOptionsMap.clear()}_dispose(){this._reset();const{notificationCenter:e,InnerEvent:t}=this._core;e.unSubscribeInnerEvent(t.DESTROY,this._dispose,this)}};const Z={to:{required:!0,rules:["string"],allowEmpty:!1},conversationType:{required:!0,rules:["string"],allowEmpty:!1},payload:{required:!0,rules:["object"],allowEmpty:!1},cloudCustomData:{required:!1,rules:["string"],allowEmpty:!1},priority:{required:!1,rules:["string"],allowEmpty:!1},customModerationConfigurationID:{required:!1,rules:["string"],allowEmpty:!1},onProgress:{required:!1,rules:["function"],allowEmpty:!1}},ee={createImageMessage:Z,createAudioMessage:Z,createVideoMessage:Z,createFileMessage:Z},te={createImageMessage:!0,createAudioMessage:!0,createVideoMessage:!0,createFileMessage:!0},oe={[u]:E,[g]:L,[m]:K,[p]:X};var se=new class{install(e){this._core=e;const{constants:{OuterConstant:{MSG_AUDIO:t,MSG_FILE:o,MSG_IMAGE:s,MSG_VIDEO:i}}}=e;E.init(e),L.init(e),K.init(e),X.init(e),S.init(e),w.init(e),e.helper.registerApi({apiName:"sendMessage",context:this,matcher:e=>[t,o,s,i].includes(e[0].type)}),e.helper.registerValidateConfig({auth:te,params:ee})}sendMessage(e,o){return t(this,void 0,void 0,(function*(){var t,s,i;try{return console.log("sendMessage message:",e),yield this._upload(e),yield null===(i=null===(s=null===(t=this._core)||void 0===t?void 0:t.message)||void 0===s?void 0:s.messageSender)||void 0===i?void 0:i.sendMessage(e,o)}catch(e){throw console.error("sendMessage error:",e),e}}))}_upload(e){return t(this,void 0,void 0,(function*(){var t,o;if(!0!==e._relayFlag)try{const t=oe[e.type];if(t){const o=this._core.ssoLog.createSSOLogData({method:"upload"});o.setLogInfo({message:`type:${e.type}`}),yield t.upload(e),o.end()}}catch(s){throw e.status=U.FAIL,s instanceof Error&&(s.data={message:e}),this._core.message.messageDataHandler.storeConversationMessage(e),null===(o=(t=this._core.ssoLog.getSSOLogData("upload")).setError)||void 0===o||o.call(t,s).end(),s}}))}};export{se as default};