@tencentcloud/lite-chat 1.1.1-beta.0 → 1.1.1-beta.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(e,s,t,o){return new(t||(t=Promise))((function(r,n){function i(e){try{c(o.next(e))}catch(e){n(e)}}function a(e){try{c(o.throw(e))}catch(e){n(e)}}function c(e){var s;e.done?r(e.value):(s=e.value,s instanceof t?s:new t((function(e){e(s)}))).then(i,a)}c((o=o.apply(e,s||[])).next())}))}function s(s,t){return e(this,void 0,void 0,(function*(){const{servcmd:e,data:o}=s,r=t.helper.generateProtocolData({servcmd:e,data:o}),n=`${r.head.seq}${e}`;return t.channel.sendPacket(r,{requestId:n})}))}var t,o,r;"function"==typeof SuppressedError&&SuppressedError,function(e){e.MSG_TEXT="TIMTextElem",e.MSG_CUSTOM="TIMCustomElem",e.MSG_LOCATION="TIMLocationElem",e.MSG_FACE="TIMFaceElem"}(t||(t={})),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"}(r||(r={}));const n="MSG_REACTION",i=0,a=1;var c=new class{init(e){this._core=e;const{helper:s}=e;s.registerApi("addMessageReaction",this),s.registerApi("removeMessageReaction",this),s.registerApi("getMessageReactions",this),s.registerApi("getMessageReadReceiptList",this)}addMessageReaction(t,o){return e(this,void 0,void 0,(function*(){const{OuterConstant:r,ssoLog:i,helper:a,constants:c}=this._core;if(!a.checkBusinessCapabilityBits(n))throw new a.ChatError({functionName:"addMessageReaction",code:c.ERROR_CODE.NO_USE,replacement1:"addMessageReaction"});const g=i.createSSOLogData({method:"addMessageReaction"});try{const{conversationID:n,ID:i,conversationType:a,from:c,to:d,clientSequence:u,random:l,time:h,sequence:v}=t;return a===r.CONV_C2C?yield function(t,o){return e(this,void 0,void 0,(function*(){var e;const{from:r,to:n,clientSequence:i,random:a,time:c,reactionID:g}=t;return s({servcmd:"openim_msg_ext_http_svc.reaction_add",data:{From_Account:r,To_Account:n,MsgKey:`${i}_${a}_${c}`,Reaction:g,Add_Account:[null===(e=o.store.get("login"))||void 0===e?void 0:e.userId]}},o)}))}({from:c,to:d,clientSequence:u,random:l,time:h,reactionID:o},this._core):a===r.CONV_GROUP&&(yield function(t,o){return e(this,void 0,void 0,(function*(){var e;const{to:r,reactionID:n,sequence:i}=t;return s({servcmd:"openim_msg_ext_http_svc.group_reaction_add",data:{GroupId:r,MsgSeq:i,Reaction:n,Add_Account:[null===(e=o.store.get("login"))||void 0===e?void 0:e.userId]}},o)}))}({to:d,reactionID:o,sequence:v},this._core)),g.setLogInfo({message:`conversationID:${n} messageID:${i} reactionID:${o}`}).end(),{code:0}}catch(e){const{errorCode:s}=e||{},t=new a.ChatError({functionName:"addMessageReaction",code:s});g.setError(t).end(),console.error("addMessageReaction error: ",e)}}))}removeMessageReaction(t,o){return e(this,void 0,void 0,(function*(){const{OuterConstant:r,ssoLog:i,helper:a,constants:c}=this._core;if(!a.checkBusinessCapabilityBits(n))throw new a.ChatError({functionName:"removeMessageReaction",code:c.ERROR_CODE.NO_USE,replacement1:"removeMessageReaction"});const g=i.createSSOLogData({method:"removeMessageReaction"});try{const{conversationID:n,ID:i,conversationType:a,from:c,to:d,clientSequence:u,random:l,time:h,sequence:v}=t;return a===r.CONV_C2C?yield function(t,o){return e(this,void 0,void 0,(function*(){var e;const{from:r,to:n,clientSequence:i,random:a,time:c,reactionID:g}=t;return s({servcmd:"openim_msg_ext_http_svc.reaction_del",data:{From_Account:r,To_Account:n,MsgKey:`${i}_${a}_${c}`,Reaction:g,Add_Account:[null===(e=o.store.get("login"))||void 0===e?void 0:e.userId]}},o)}))}({from:c,to:d,clientSequence:u,random:l,time:h,reactionID:o},this._core):a===r.CONV_GROUP&&(yield function(t,o){return e(this,void 0,void 0,(function*(){var e;const{from:r,to:n,clientSequence:i,random:a,time:c,reactionID:g}=t;return s({servcmd:"openim_msg_ext_http_svc.group_reaction_del",data:{From_Account:r,To_Account:n,MsgKey:`${i}_${a}_${c}`,Reaction:g,Add_Account:[null===(e=o.store.get("login"))||void 0===e?void 0:e.userId]}},o)}))}({to:d,reactionID:o,sequence:v},this._core)),g.setLogInfo({message:`conversationID:${n} messageID:${i} reactionID:${o}`}).end(),{code:0}}catch(e){const{errorCode:s}=e||{},t=new a.ChatError({functionName:"removeMessageReaction",code:s});g.setError(t).end(),console.error("removeMessageReaction error: ",e)}}))}getMessageReadReceiptList(s){return e(this,void 0,void 0,(function*(){return console.log("getMessageReadReceiptList: options: ",s),{code:0,data:{messageList:[]}}}))}getMessageReactions(s){return e(this,void 0,void 0,(function*(){return console.log("getMessageReactions: options: ",s),{code:0,data:[]}}))}};const g=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 s=function(e){var s;if("string"!=typeof(null==e?void 0:e.text)||"string"==typeof e.text&&0===(null===(s=null==e?void 0:e.text)||void 0===s?void 0:s.length))return"payload.text is invalid.";return!0}(e);return!0!==s?s:!((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}}},{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:!0,rules:["number"],allowEmpty:!1,customValidator:e=>"number"!=typeof e?"maxUserCountPerReaction is invalid.":!(e<0||e>10)||"maxUserCountPerReaction should between [0, 10]."}}}),d=Object.assign({deleteMessage:!0,revokeMessage:!0,resendMessage:!0,getMessageList:!0,getMessageListHopping:!0,createTextAtMessage:!0,findMessage:!0,translateText:!0,createForwardMessage:!0},{addMessageReaction:!0,removeMessageReaction:!0,getMessageReactions:!0});class u{constructor(e){this._core=e}deleteMessage(s){return e(this,void 0,void 0,(function*(){const{to:e,messageIdentifiers:t}=s,o="openim.delete_c2c_msg_ramble",r={From_Account:this._getCurrentUserId(),To_Account:e,MsgKeyList:t},n=this._core.helper.generateProtocolData({servcmd:o,data:r}),i=`${n.head.seq}${o}`;return this._core.channel.sendPacket(n,{requestId:i})}))}revokeMessage(s){return e(this,void 0,void 0,(function*(){const{to:e,from:t,sequence:o,time:r,random:n}=s,i="openim.msgwithdraw",a={MsgInfo:{From_Account:t,To_Account:e,MsgSeq:o,MsgRandom:n,MsgTimeStamp:r}},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 l{constructor(e){this._core=e}deleteMessage(s){return e(this,void 0,void 0,(function*(){const{to:e,messageIdentifiers:t}=s,o="group_open_http_svc.delete_group_ramble_msg_by_seq",r={GroupId:e,Deleter_Account:this._getCurrentUserId(),Seqs:t},n=this._core.helper.generateProtocolData({servcmd:o,data:r}),i=`${n.head.seq}${o}`;return this._core.channel.sendPacket(n,{requestId:i})}))}revokeMessage(s){return e(this,void 0,void 0,(function*(){const{to:e,sequence:t}=s,o="group_open_http_svc.group_msg_recall",r={GroupId:e,MsgSeqList:[{MsgSeq:t}]},n=this._core.helper.generateProtocolData({servcmd:o,data:r}),i=`${n.head.seq}${o}`;return this._core.channel.sendPacket(n,{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 h=2116,v="C2C",_="GROUP",m=20,M=1,p=300;class E{constructor(e){this._core=e}generateRevokeMessage(e){const{conversationID:s,sequence:t,random:o,tinyID:r,clientTime:n,revokeReason:i,revoker:a}=e;let c={};const{messageStore:g}=this._core.message;return c=g.revokeMessage({conversationID:s,sequence:t,random:o}),c||(c={conversationID:s,sequence:t},r&&n&&o&&(c.ID=`${r}-${n}-${o}`)),c=Object.assign(Object.assign({},c),{revoker:a,revokeReason:i,revokerInfo:{userID:a,nick:"",avatar:""}}),c}updateRevokerInfo(s){return e(this,void 0,void 0,(function*(){const e=s.map((e=>e.revoker));try{const t=yield this._fetchUserInfos(e);t&&s.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(s){return e(this,void 0,void 0,(function*(){var e,t;const o=yield null===(e=this._core.user.userProfile)||void 0===e?void 0:e.getUserProfile({userIDList:s});return(null==o?void 0:o.data)?null===(t=o.data)||void 0===t?void 0:t.reduce(((e,{userID:s,nick:t,avatar:o})=>(e[s]={nick:t||"",avatar:o||""},e)),{}):null}))}}var f=new class{constructor(){this._core=null,this._c2cMessageAction=null,this._groupMessageAction=null}init(e){this._core=e,this._groupMessageAction=new l(e),this._c2cMessageAction=new u(e),this._messageHelper=new E(e);const{helper:s}=e;s.registerApi("deleteMessage",this),s.registerApi("revokeMessage",this),s.registerApi("resendMessage",this),s.registerApi("findMessage",this)}deleteMessage(s){return e(this,void 0,void 0,(function*(){let e=[],t=[];const{conversationID:o,conversationType:r}=s[0],n=o.replace(r,"");if("@TIM#SYSTEM"===r)throw new this._core.helper.ChatError({code:h});if(s.forEach((s=>{const{conversationID:n,conversationType:i,status:a,_onlineOnlyFlag:c,sequence:g,random:d,time:u}=s||{};if("success"===a&&n===o&&i===r){if(!c){const s="C2C"===i?`${g}_${d}_${u}`:String(g);e.push(s)}t.push(s)}})),0===e.length)return this._handleDeleteMessageSuccess(t),{code:0,data:{messageList:t}};e.length>30&&(e=e.slice(0,30),t=t.slice(0,30));try{return"C2C"===r?yield this._c2cMessageAction.deleteMessage({to:n,messageIdentifiers:e}):yield this._groupMessageAction.deleteMessage({to:n,messageIdentifiers:e}),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(s){return e(this,void 0,void 0,(function*(){var e;const t=this._core.ssoLog.createSSOLogData({method:"revokeMessage"}),{conversationType:o,isRevoked:r}=s;let n=null;if("@TIM#SYSTEM"===o)throw new this._core.helper.ChatError({message:"system message cannot be revoked"});if(r)throw new this._core.helper.ChatError({message:"message has been revoked"});t.setLogInfo({message:`type:${s.type} from:${s.from} to:${s.to}`});try{if(n="C2C"===o?yield this._c2cMessageAction.revokeMessage(s):yield this._groupMessageAction.revokeMessage(s),n){const{RecallRetList:o}=n,r=(null===(e=null==o?void 0:o[0])||void 0===e?void 0:e.RetCode)||0;if(0!==r)throw new this._core.helper.ChatError({code:r});return t.end(),yield this._handleRevokeMessageSuccess(s),{code:0,data:{message:s}}}}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(s,t){return e(this,void 0,void 0,(function*(){var e,o;return s.isResend=!0,s.status="unSend",null===(o=null===(e=this._core)||void 0===e?void 0:e.apiMap)||void 0===o?void 0:o.sendMessage(s,t)}))}findMessage(e){return this._core.message.messageStore.findMessage(e)}_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(s){return e(this,void 0,void 0,(function*(){var e;s.isRevoked=!0,s.revoker=null===(e=this._core.store.get("login"))||void 0===e?void 0:e.userId,yield this._messageHelper.updateRevokerInfo([s]),this._core.notificationCenter.emitInnerEvent(this._core.InnerEvent.MESSAGE_REVOKED,[s])}))}};class I{static parseServerPushElement(e){const{MsgContent:s={}}=e,{Index:t,Data:o}=s;return new I({index:t,data:o})}constructor(e){this.type=t.MSG_FACE;const{index:s,data:o}=e;this.content={index:s,data:o}}validateBeforeSend(){var e,s;return"number"==typeof(null===(e=this.content)||void 0===e?void 0:e.index)&&"string"==typeof(null===(s=this.content)||void 0===s?void 0:s.data)?{isValid:!0}:{isValid:!1,error:{message:"content is invalid"}}}convertToBackendFormat(){const{index:e,data:s}=this.content;return{MsgType:this.type,MsgContent:{Index:e,Data:s}}}}var y=new class{init(e){this._core=e,e.message.messageFactory.registerElementClass(t.MSG_FACE,I),e.helper.registerApi("createFaceMessage",this),e.helper.registerApi("createTextAtMessage",this),e.helper.registerApi("createForwardMessage",this)}createFaceMessage(e){if(!e)return null;const{index:s,data:t}=(null==e?void 0:e.payload)||{},o=new I({index:s,data:t}),r=this._getCurrentUserId(),n=this._core.message.messageFactory.createMessage(Object.assign(Object.assign({},e),{from:r}));return n.setElement(o),n}createTextAtMessage(e){const{atUserList:s}=(null==e?void 0:e.payload)||{},t=this._core.apiMap.createTextMessage(e),{OuterConstant:o}=this._core;if(!t)return null;if(Array.isArray(s)){const e=[],r=[];s.forEach((s=>{s!==o.MSG_AT_ALL?(e.push({GroupAtAllFlag:i,GroupAt_Account:s}),r.push(s)):(e.push({GroupAtAllFlag:a}),r.push(o.MSG_AT_ALL))})),t._groupAtInfoList=e,t.atUserList=r}return t}createForwardMessage(e){const{helper:s,OuterConstant:t}=this._core,{to:o,conversationType:r,priority:n,payload:i,needReadReceipt:a,receiverList:c,cloudCustomData:g="",isSupportExtension:d=!1}=e;if(!Array.isArray(i._elements))throw new s.ChatError({functionName:"createForwardMessage",code:2454});if(i.type===t.MSG_GRP_TIP)throw new s.ChatError({functionName:"createForwardMessage",code:2453});const u=this._getCurrentUserId(),l=this._core.message.messageFactory.createMessage({to:o,from:u,conversationType:r,isPlaceMessage:0,priority:n,payload:i,needReadReceipt:a,isSupportExtension:d,cloudCustomData:g,receiverList:c,_relayFlag:!0});return l.setElement(i._elements[0]),l}_getCurrentUserId(){var e;return null===(e=this._core.store.get("login"))||void 0===e?void 0:e.userId}};class S{init(e){this._messageHelper=new E(e),this._core=e;const{notificationCenter:s,InnerEvent:{MESSAGE_PUSH:t},InnerEventSubType:{C2C_NOTIFY_MESSAGE:o}}=e;s.subscribeInnerEvent(t,o,this._handleC2CNotifyMessage,this)}_handleC2CNotifyMessage(e){const{C2cNotifyMsgArray:s}=e;null==s||s.forEach((e=>{Object.keys(e).includes("WithdrawC2cMsgNotify")&&this._handleC2CRevokeMessage(e)}))}_handleC2CRevokeMessage(s){return e(this,void 0,void 0,(function*(){try{const{WithdrawC2cMsgNotify:{C2cWithdrawInfoArray:e}}=s,t=[],{notificationCenter:o,OuterEvent:r,InnerEvent:n}=this._core;e.forEach((e=>{const{MsgRand:s,MsgSeq:o,To_Account:r,From_Account:n,RevokerInfo:{Revoker_Account:i,Reason:a}}=e,c=this._getCurrentUserId()===n?`C2C${r}`:`C2C${n}`,g=this._messageHelper.generateRevokeMessage({conversationID:c,sequence:o,random:s,revoker:i,revokeReason:a});t.push(g)})),0!==t.length&&o.emitInnerEvent(n.MESSAGE_REVOKED,{revokedMessages:t,updateUnreadCount:!0}),yield this._messageHelper.updateRevokerInfo(t),o.emitOuterEvent(r.MESSAGE_REVOKED,{name:r.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},InnerEventSubType:{C2C_NOTIFY_MESSAGE:t}}=this._core;e.unSubscribeInnerEvent(s,t,this._handleC2CNotifyMessage,this)}}class R{init(e){this._messageHelper=new E(e),this._core=e;const{notificationCenter:s,InnerEvent:{MESSAGE_PUSH:t,DESTROY:o},InnerEventSubType:{GROUP_NOTIFY_MESSAGE:r}}=e;s.subscribeInnerEvent(t,r,this._handleGroupNotifyMessage,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(s){return e(this,void 0,void 0,(function*(){try{const{RevokerInfo:e,MsgBody:{GroupWithdrawInfoArray:t}}=s,o=[],{notificationCenter:r,OuterEvent:n,InnerEvent:i}=this._core;t.forEach((s=>{const{Random:t,MsgSeq:r,GroupId:n,MsgClientTime:i,TinyId:a,TopicId:c,RevokerInfo:{Revoker_Account:g=(null==e?void 0:e.Revoker_Account)||"",Reason:d=(null==e?void 0:e.Reason)||""}}=s,u=c?`GROUP${c}`:`GROUP${n}`,l=this._messageHelper.generateRevokeMessage({conversationID:u,sequence:r,random:t,tinyID:a,clientTime:i,revoker:g,revokeReason:d});o.push(l)})),0!==o.length&&(r.emitInnerEvent(i.MESSAGE_REVOKED,{revokedMessages:o,updateUnreadCount:!0}),yield this._messageHelper.updateRevokerInfo(o),r.emitOuterEvent(n.MESSAGE_REVOKED,{name:n.MESSAGE_REVOKED,data:o}))}catch(e){console.debug(e)}}))}dispose(){const{notificationCenter:e,InnerEvent:{MESSAGE_PUSH:s},InnerEventSubType:{GROUP_NOTIFY_MESSAGE:t}}=this._core;e.unSubscribeInnerEvent(s,t,this._handleGroupNotifyMessage,this)}}var C=new class{constructor(){this._c2cMessageReceiver=new S,this._groupMessageReceiver=new R}init(e){this._c2cMessageReceiver.init(e),this._groupMessageReceiver.init(e)}dispose(){this._c2cMessageReceiver.dispose(),this._groupMessageReceiver.dispose()}};class D{constructor(e){this._lastMessageSequenceMapOnDisconnect=new Map,this._core=e,this._messageHelper=new E(e)}getRoamingMessagesByAnchor(s){return e(this,void 0,void 0,(function*(){try{const e=this._core.ssoLog.createSSOLogData({method:"getRoamingMessagesByAnchor"}),{conversationID:t,count:n,direction:i,sequence:a}=s,c=t.replace(_,"");let g=a;if(i===r.BACKWARD){if("number"!=typeof a)return{messageList:[],hasNoMoreHistoryMessage:!1,nextReqMessageIDFromServer:""};g=a+n-1}const d={GroupId:c,ReqMsgNumber:n,WithRecalledMsg:1,Version:1};g&&(d.ReqMsgSeq=g);const u="group_open_http_svc.group_msg_get",l=this._core.helper.generateProtocolData({servcmd:u,data:d}),h=`${l.head.seq}${u}`,v=yield this._core.channel.sendPacket(l,{requestId:h});if(v){const{RspMsgList:s,NextReqMsgSeq:t=0,IsFinished:r,InvisibleMsgSeq:n}=v;e.setLogInfo({message:`groupID:${c} sequence:${a} reqSeq:${g} direction:${i}\n complete:${r} nextSequence:${t} remoteMsgCount:${s.length} invisibleSequenceList:${n}`}).end();const d=[];for(let e=0;e<s.length;e++){const t=s[e],o=this._parseMessage(t);d.push(o)}d.reverse();return{messageList:d,invisibleSequenceList:n,nextReqMessageIDFromServer:t,hasNoMoreHistoryMessage:[o.NO_MORE_DATA,o.DATA_HAS_EXPIRED].includes(r)}}}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(s){return e(this,void 0,void 0,(function*(){const{message:{messageReceiver:t,messageStore:o},notificationCenter:n,OuterEvent:i}=this._core;null==s||s.forEach((s=>e(this,void 0,void 0,(function*(){const{conversationID:e,lastMessage:a}=s;let c=this._getLocalLastMessageSequence(e);const g=a.lastSequence;if(this._shouldRecoverHistory({localLastMessageSequence:c,serverLastMessageSequence:g})){const s=g-c;let a=!1;const d=Math.ceil(s/20);for(let s=0;s<d;s++)try{const s=g-c,d=Math.min(20,s),u=yield this.getRoamingMessagesByAnchor({conversationID:e,sequence:c+d,direction:r.FORWARD,count:d}),{nextReqMessageIDFromServer:l,hasNoMoreHistoryMessage:h,messageList:v}=u;a=h&&l<0,c=v[v.length-1].sequence;const _=[];if(Array.isArray(v)&&(v.forEach((e=>{t.groupMessageReceiver.updateMessageProfile(e);o.storeConversationMessage(e)&&_.push(e)})),_.length>0&&n.emitOuterEvent(i.MESSAGE_RECEIVED,{name:i.MESSAGE_RECEIVED,data:_})),a)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 o=t-s;return 0!==t&&s&&(o>=M&&o<p)}_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=_,t=this._core.message.messageHelper.parseServerGroupMessage(e),o=this._core.message.messageFactory.createMessage(Object.assign(Object.assign({},t),{conversationType:s,flow:"in"}));return o.setElement(t.elements),o}}var A=new class{constructor(){this._clearedConversations=new Set,this._fetchedCompleteConversations=new Set}init(e){this._core=e,this._groupMessageHistory=new D(e),this._messageHelper=new E(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)}getMessageList(s){return e(this,void 0,void 0,(function*(){try{const e=this._core.ssoLog.createSSOLogData({method:"getMessageList"});let{conversationID:t,nextReqMessageID:o}=s;const n=m;if("@TIM#SYSTEM"===t)return{code:0,data:{messageList:[],isCompleted:!1,nextMessageSeq:""}};const i=this._getAvailableLocalMessagesCount({conversationID:t,nextReqMessageID:o});if(this._needFetchHistoryMessageList({conversationID:t,availableLocalMessagesCount:i,targetCount:n})){let s=null;if(t.startsWith(_)&&(s=yield this._groupMessageHistory.getRoamingMessagesByAnchor({conversationID:t,sequence:Number(o),count:n,direction:r.FORWARD})),s){const{nextReqMessageIDFromServer:r,hasNoMoreHistoryMessage:n,messageList:a}=s,c=this._messageHelper.filterValidMessages(a),g=this._core.message.messageStore.prependLocalMessageList({messageList:c,conversationID:t}),d=this._core.message.messageStore.getLocalMessageList(t).slice(0,g.length+i),u=d.filter((e=>e.isRevoked));yield this._messageHelper.updateRevokerInfo(u);const l={nextReqMessageID:n?"":String(r),messageList:d,isCompleted:n},h=d.map((e=>e.sequence));return e.setLogInfo({message:`conversationID: ${t} nextReqMessageID: ${o} \n availableLocalMessagesCount: ${i} sequenceList: ${JSON.stringify(h)} `}).end(),{code:0,data:l}}return{code:0,data:{messageList:[],isCompleted:!1,nextMessageSeq:""}}}e.setLogInfo({message:`conversationID: ${t} nextReqMessageID: ${o} availableLocalMessagesCount: ${i}}`}).end();return{code:0,data:this._getMessageListFromMemory({conversationID:t,nextReqMessageID:o,count:n})}}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(s){return e(this,void 0,void 0,(function*(){var e,t;const{conversationID:o,sequence:n,direction:i=r.FORWARD}=s,{isEmpty:a}=this._core.helper;if(![r.BACKWARD,r.FORWARD].includes(i))throw new this._core.helper.ChatError({message:"direction must be 0 or 1"});let{count:c=m}=s;c=c>m?m:c;let g=null;if(o.startsWith(_)&&(g=yield this._groupMessageHistory.getRoamingMessagesByAnchor({conversationID:o,sequence:n,count:c,direction:i})),g){const{nextReqMessageIDFromServer:s,hasNoMoreHistoryMessage:o,messageList:c,invisibleSequenceList:d}=g,u=this._messageHelper.filterValidMessages(c);if(this._core.message.messageStore.storeSparseMessageList(u),i===r.FORWARD){const e=o&&s<1;return{code:0,data:{messageList:u,isCompleted:e,nextMessageSeq:e?"":s}}}if(i===r.BACKWARD){if(a(c)&&a(d))return{code:0,data:{messageList:[],isCompleted:!0,nextMessageSeq:""}};const s=(null===(e=null==c?void 0:c[c.length-1])||void 0===e?void 0:e.sequence)||0,o=(null===(t=null==d?void 0:d[d.length-1])||void 0===t?void 0:t.sequence)||0;return{code:0,data:{messageList:u.filter((e=>e.sequence>=n)),isCompleted:!1,nextMessageSeq:Math.max(s,o)+1}}}return{code:0,data:g}}return{code:0,data:{messageList:[],isCompleted:!1,nextMessageSeq:""}}}))}_getAvailableLocalMessagesCount({conversationID:e,nextReqMessageID:s}){const t=this._core.message.messageStore.getLocalMessageList(e),{length:o}=t;if(!s)return o;let r=-1;return(null==e?void 0:e.startsWith(v))?r=t.findIndex((e=>e.ID===s)):(null==e?void 0:e.startsWith(_))&&(r=t.findIndex((e=>s.includes("-")?e.ID===s:String(e.sequence)===s))),-1===r?0:r}_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 o=this._core.message.messageStore.getLocalMessageList(e),r=o.length;let n=r,i={isCompleted:!1,nextReqMessageID:"",messageList:[]},a=0,c=r;return s?s&&(c=o.findIndex((t=>e.startsWith(v)?t.ID===s:String(t.sequence)===s)),a=c>t?c-t:0,n=c):a=r>t?r-t:0,i.nextReqMessageID=0===a?"":this._generateNextReqMessageID({conversationID:e,targetIndex:a}),i.messageList=o.slice(a,c),i.isCompleted=n<=t,i}_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===_));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)}};var q=new class{constructor(){this._core=null}init(e){this._core=e;const{helper:s}=e;s.registerApi("translateText",this)}translateText(s){return e(this,void 0,void 0,(function*(){try{const{sourceLanguage:t,sourceTextList:o,targetLanguage:r}=s,n=yield function(s,t){return e(this,void 0,void 0,(function*(){var e,o;const{sourceTextList:r,sourceLanguage:n,targetLanguage:i}=s,{store:a,helper:c,channel:g}=t,d="im_open_translate.ws_batch_trans_text",u={SourceText:r,Source:n,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},l=c.generateProtocolData({servcmd:d,data:u}),h=`${l.head.seq}${d}`,v=yield g.sendPacket(l,{requestId:h});if(v){const{CmdErrorCode:e,TargetText:s}=v;return{cmdErrorCode:e,translatedTextList:s}}}))}({sourceLanguage:t,sourceTextList:o,targetLanguage:r},this._core);if(n){const{cmdErrorCode:{ErrorCode:e,ErrorInfo:s},translatedTextList:t}=n;if(0===e)return{code:0,data:{translatedTextList:t}};throw{errorCode:e,errorInfo:s,message:s}}}catch(e){const{errorCode:s,errorInfo:t}=e||{};throw new this._core.helper.ChatError({functionName:"translateText",code:s,message:t})}}))}};var L=new class{install(e){this._core=e,f.init(e),y.init(e),C.init(e),A.init(e),c.init(e),q.init(e),e.helper.registerValidateConfig({auth:d,params:g}),e.notificationCenter.subscribeInnerEvent(e.InnerEvent.DESTROY,this.dispose,this)}dispose(){const{notificationCenter:e,InnerEvent:s}=this._core;e.unSubscribeInnerEvent(s.DESTROY,this.dispose,this),C.dispose(),A.dispose()}};export{L as default};
1
+ 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 S{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 f=new class{constructor(){this._clearedConversations=new Set,this._fetchedCompleteConversations=new Set}install(e){this._core=e,this._groupMessageHistory=new S(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:[]}}))}};function D(t){M.install(t),p.install(t),I.install(t),f.install(t),R.install(t),t.helper.registerValidateConfig({auth:s,params:e})}export{D as default};
@@ -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)["liteChatMessage-enhancer"]=s()}(this,(function(){"use strict";function e(e,s,t,o){return new(t||(t=Promise))((function(r,n){function i(e){try{c(o.next(e))}catch(e){n(e)}}function a(e){try{c(o.throw(e))}catch(e){n(e)}}function c(e){var s;e.done?r(e.value):(s=e.value,s instanceof t?s:new t((function(e){e(s)}))).then(i,a)}c((o=o.apply(e,s||[])).next())}))}function s(s,t){return e(this,void 0,void 0,(function*(){const{servcmd:e,data:o}=s,r=t.helper.generateProtocolData({servcmd:e,data:o}),n=`${r.head.seq}${e}`;return t.channel.sendPacket(r,{requestId:n})}))}var t,o,r;"function"==typeof SuppressedError&&SuppressedError,function(e){e.MSG_TEXT="TIMTextElem",e.MSG_CUSTOM="TIMCustomElem",e.MSG_LOCATION="TIMLocationElem",e.MSG_FACE="TIMFaceElem"}(t||(t={})),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"}(r||(r={}));const n="MSG_REACTION",i=0,a=1;var c=new class{init(e){this._core=e;const{helper:s}=e;s.registerApi("addMessageReaction",this),s.registerApi("removeMessageReaction",this),s.registerApi("getMessageReactions",this),s.registerApi("getMessageReadReceiptList",this)}addMessageReaction(t,o){return e(this,void 0,void 0,(function*(){const{OuterConstant:r,ssoLog:i,helper:a,constants:c}=this._core;if(!a.checkBusinessCapabilityBits(n))throw new a.ChatError({functionName:"addMessageReaction",code:c.ERROR_CODE.NO_USE,replacement1:"addMessageReaction"});const d=i.createSSOLogData({method:"addMessageReaction"});try{const{conversationID:n,ID:i,conversationType:a,from:c,to:g,clientSequence:u,random:l,time:h,sequence:v}=t;return a===r.CONV_C2C?yield function(t,o){return e(this,void 0,void 0,(function*(){var e;const{from:r,to:n,clientSequence:i,random:a,time:c,reactionID:d}=t;return s({servcmd:"openim_msg_ext_http_svc.reaction_add",data:{From_Account:r,To_Account:n,MsgKey:`${i}_${a}_${c}`,Reaction:d,Add_Account:[null===(e=o.store.get("login"))||void 0===e?void 0:e.userId]}},o)}))}({from:c,to:g,clientSequence:u,random:l,time:h,reactionID:o},this._core):a===r.CONV_GROUP&&(yield function(t,o){return e(this,void 0,void 0,(function*(){var e;const{to:r,reactionID:n,sequence:i}=t;return s({servcmd:"openim_msg_ext_http_svc.group_reaction_add",data:{GroupId:r,MsgSeq:i,Reaction:n,Add_Account:[null===(e=o.store.get("login"))||void 0===e?void 0:e.userId]}},o)}))}({to:g,reactionID:o,sequence:v},this._core)),d.setLogInfo({message:`conversationID:${n} messageID:${i} reactionID:${o}`}).end(),{code:0}}catch(e){const{errorCode:s}=e||{},t=new a.ChatError({functionName:"addMessageReaction",code:s});d.setError(t).end(),console.error("addMessageReaction error: ",e)}}))}removeMessageReaction(t,o){return e(this,void 0,void 0,(function*(){const{OuterConstant:r,ssoLog:i,helper:a,constants:c}=this._core;if(!a.checkBusinessCapabilityBits(n))throw new a.ChatError({functionName:"removeMessageReaction",code:c.ERROR_CODE.NO_USE,replacement1:"removeMessageReaction"});const d=i.createSSOLogData({method:"removeMessageReaction"});try{const{conversationID:n,ID:i,conversationType:a,from:c,to:g,clientSequence:u,random:l,time:h,sequence:v}=t;return a===r.CONV_C2C?yield function(t,o){return e(this,void 0,void 0,(function*(){var e;const{from:r,to:n,clientSequence:i,random:a,time:c,reactionID:d}=t;return s({servcmd:"openim_msg_ext_http_svc.reaction_del",data:{From_Account:r,To_Account:n,MsgKey:`${i}_${a}_${c}`,Reaction:d,Add_Account:[null===(e=o.store.get("login"))||void 0===e?void 0:e.userId]}},o)}))}({from:c,to:g,clientSequence:u,random:l,time:h,reactionID:o},this._core):a===r.CONV_GROUP&&(yield function(t,o){return e(this,void 0,void 0,(function*(){var e;const{from:r,to:n,clientSequence:i,random:a,time:c,reactionID:d}=t;return s({servcmd:"openim_msg_ext_http_svc.group_reaction_del",data:{From_Account:r,To_Account:n,MsgKey:`${i}_${a}_${c}`,Reaction:d,Add_Account:[null===(e=o.store.get("login"))||void 0===e?void 0:e.userId]}},o)}))}({to:g,reactionID:o,sequence:v},this._core)),d.setLogInfo({message:`conversationID:${n} messageID:${i} reactionID:${o}`}).end(),{code:0}}catch(e){const{errorCode:s}=e||{},t=new a.ChatError({functionName:"removeMessageReaction",code:s});d.setError(t).end(),console.error("removeMessageReaction error: ",e)}}))}getMessageReadReceiptList(s){return e(this,void 0,void 0,(function*(){return console.log("getMessageReadReceiptList: options: ",s),{code:0,data:{messageList:[]}}}))}getMessageReactions(s){return e(this,void 0,void 0,(function*(){return console.log("getMessageReactions: options: ",s),{code:0,data:[]}}))}};const d=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 s=function(e){var s;if("string"!=typeof(null==e?void 0:e.text)||"string"==typeof e.text&&0===(null===(s=null==e?void 0:e.text)||void 0===s?void 0:s.length))return"payload.text is invalid.";return!0}(e);return!0!==s?s:!((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}}},{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:!0,rules:["number"],allowEmpty:!1,customValidator:e=>"number"!=typeof e?"maxUserCountPerReaction is invalid.":!(e<0||e>10)||"maxUserCountPerReaction should between [0, 10]."}}}),g=Object.assign({deleteMessage:!0,revokeMessage:!0,resendMessage:!0,getMessageList:!0,getMessageListHopping:!0,createTextAtMessage:!0,findMessage:!0,translateText:!0,createForwardMessage:!0},{addMessageReaction:!0,removeMessageReaction:!0,getMessageReactions:!0});class u{constructor(e){this._core=e}deleteMessage(s){return e(this,void 0,void 0,(function*(){const{to:e,messageIdentifiers:t}=s,o="openim.delete_c2c_msg_ramble",r={From_Account:this._getCurrentUserId(),To_Account:e,MsgKeyList:t},n=this._core.helper.generateProtocolData({servcmd:o,data:r}),i=`${n.head.seq}${o}`;return this._core.channel.sendPacket(n,{requestId:i})}))}revokeMessage(s){return e(this,void 0,void 0,(function*(){const{to:e,from:t,sequence:o,time:r,random:n}=s,i="openim.msgwithdraw",a={MsgInfo:{From_Account:t,To_Account:e,MsgSeq:o,MsgRandom:n,MsgTimeStamp:r}},c=this._core.helper.generateProtocolData({servcmd:i,data:a}),d=`${c.head.seq}${i}`;return this._core.channel.sendPacket(c,{requestId:d})}))}_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 l{constructor(e){this._core=e}deleteMessage(s){return e(this,void 0,void 0,(function*(){const{to:e,messageIdentifiers:t}=s,o="group_open_http_svc.delete_group_ramble_msg_by_seq",r={GroupId:e,Deleter_Account:this._getCurrentUserId(),Seqs:t},n=this._core.helper.generateProtocolData({servcmd:o,data:r}),i=`${n.head.seq}${o}`;return this._core.channel.sendPacket(n,{requestId:i})}))}revokeMessage(s){return e(this,void 0,void 0,(function*(){const{to:e,sequence:t}=s,o="group_open_http_svc.group_msg_recall",r={GroupId:e,MsgSeqList:[{MsgSeq:t}]},n=this._core.helper.generateProtocolData({servcmd:o,data:r}),i=`${n.head.seq}${o}`;return this._core.channel.sendPacket(n,{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 h=2116,v="C2C",_="GROUP",m=20,M=1,p=300;class f{constructor(e){this._core=e}generateRevokeMessage(e){const{conversationID:s,sequence:t,random:o,tinyID:r,clientTime:n,revokeReason:i,revoker:a}=e;let c={};const{messageStore:d}=this._core.message;return c=d.revokeMessage({conversationID:s,sequence:t,random:o}),c||(c={conversationID:s,sequence:t},r&&n&&o&&(c.ID=`${r}-${n}-${o}`)),c=Object.assign(Object.assign({},c),{revoker:a,revokeReason:i,revokerInfo:{userID:a,nick:"",avatar:""}}),c}updateRevokerInfo(s){return e(this,void 0,void 0,(function*(){const e=s.map((e=>e.revoker));try{const t=yield this._fetchUserInfos(e);t&&s.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(s){return e(this,void 0,void 0,(function*(){var e,t;const o=yield null===(e=this._core.user.userProfile)||void 0===e?void 0:e.getUserProfile({userIDList:s});return(null==o?void 0:o.data)?null===(t=o.data)||void 0===t?void 0:t.reduce(((e,{userID:s,nick:t,avatar:o})=>(e[s]={nick:t||"",avatar:o||""},e)),{}):null}))}}var E=new class{constructor(){this._core=null,this._c2cMessageAction=null,this._groupMessageAction=null}init(e){this._core=e,this._groupMessageAction=new l(e),this._c2cMessageAction=new u(e),this._messageHelper=new f(e);const{helper:s}=e;s.registerApi("deleteMessage",this),s.registerApi("revokeMessage",this),s.registerApi("resendMessage",this),s.registerApi("findMessage",this)}deleteMessage(s){return e(this,void 0,void 0,(function*(){let e=[],t=[];const{conversationID:o,conversationType:r}=s[0],n=o.replace(r,"");if("@TIM#SYSTEM"===r)throw new this._core.helper.ChatError({code:h});if(s.forEach((s=>{const{conversationID:n,conversationType:i,status:a,_onlineOnlyFlag:c,sequence:d,random:g,time:u}=s||{};if("success"===a&&n===o&&i===r){if(!c){const s="C2C"===i?`${d}_${g}_${u}`:String(d);e.push(s)}t.push(s)}})),0===e.length)return this._handleDeleteMessageSuccess(t),{code:0,data:{messageList:t}};e.length>30&&(e=e.slice(0,30),t=t.slice(0,30));try{return"C2C"===r?yield this._c2cMessageAction.deleteMessage({to:n,messageIdentifiers:e}):yield this._groupMessageAction.deleteMessage({to:n,messageIdentifiers:e}),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(s){return e(this,void 0,void 0,(function*(){var e;const t=this._core.ssoLog.createSSOLogData({method:"revokeMessage"}),{conversationType:o,isRevoked:r}=s;let n=null;if("@TIM#SYSTEM"===o)throw new this._core.helper.ChatError({message:"system message cannot be revoked"});if(r)throw new this._core.helper.ChatError({message:"message has been revoked"});t.setLogInfo({message:`type:${s.type} from:${s.from} to:${s.to}`});try{if(n="C2C"===o?yield this._c2cMessageAction.revokeMessage(s):yield this._groupMessageAction.revokeMessage(s),n){const{RecallRetList:o}=n,r=(null===(e=null==o?void 0:o[0])||void 0===e?void 0:e.RetCode)||0;if(0!==r)throw new this._core.helper.ChatError({code:r});return t.end(),yield this._handleRevokeMessageSuccess(s),{code:0,data:{message:s}}}}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(s,t){return e(this,void 0,void 0,(function*(){var e,o;return s.isResend=!0,s.status="unSend",null===(o=null===(e=this._core)||void 0===e?void 0:e.apiMap)||void 0===o?void 0:o.sendMessage(s,t)}))}findMessage(e){return this._core.message.messageStore.findMessage(e)}_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(s){return e(this,void 0,void 0,(function*(){var e;s.isRevoked=!0,s.revoker=null===(e=this._core.store.get("login"))||void 0===e?void 0:e.userId,yield this._messageHelper.updateRevokerInfo([s]),this._core.notificationCenter.emitInnerEvent(this._core.InnerEvent.MESSAGE_REVOKED,[s])}))}};class I{static parseServerPushElement(e){const{MsgContent:s={}}=e,{Index:t,Data:o}=s;return new I({index:t,data:o})}constructor(e){this.type=t.MSG_FACE;const{index:s,data:o}=e;this.content={index:s,data:o}}validateBeforeSend(){var e,s;return"number"==typeof(null===(e=this.content)||void 0===e?void 0:e.index)&&"string"==typeof(null===(s=this.content)||void 0===s?void 0:s.data)?{isValid:!0}:{isValid:!1,error:{message:"content is invalid"}}}convertToBackendFormat(){const{index:e,data:s}=this.content;return{MsgType:this.type,MsgContent:{Index:e,Data:s}}}}var y=new class{init(e){this._core=e,e.message.messageFactory.registerElementClass(t.MSG_FACE,I),e.helper.registerApi("createFaceMessage",this),e.helper.registerApi("createTextAtMessage",this),e.helper.registerApi("createForwardMessage",this)}createFaceMessage(e){if(!e)return null;const{index:s,data:t}=(null==e?void 0:e.payload)||{},o=new I({index:s,data:t}),r=this._getCurrentUserId(),n=this._core.message.messageFactory.createMessage(Object.assign(Object.assign({},e),{from:r}));return n.setElement(o),n}createTextAtMessage(e){const{atUserList:s}=(null==e?void 0:e.payload)||{},t=this._core.apiMap.createTextMessage(e),{OuterConstant:o}=this._core;if(!t)return null;if(Array.isArray(s)){const e=[],r=[];s.forEach((s=>{s!==o.MSG_AT_ALL?(e.push({GroupAtAllFlag:i,GroupAt_Account:s}),r.push(s)):(e.push({GroupAtAllFlag:a}),r.push(o.MSG_AT_ALL))})),t._groupAtInfoList=e,t.atUserList=r}return t}createForwardMessage(e){const{helper:s,OuterConstant:t}=this._core,{to:o,conversationType:r,priority:n,payload:i,needReadReceipt:a,receiverList:c,cloudCustomData:d="",isSupportExtension:g=!1}=e;if(!Array.isArray(i._elements))throw new s.ChatError({functionName:"createForwardMessage",code:2454});if(i.type===t.MSG_GRP_TIP)throw new s.ChatError({functionName:"createForwardMessage",code:2453});const u=this._getCurrentUserId(),l=this._core.message.messageFactory.createMessage({to:o,from:u,conversationType:r,isPlaceMessage:0,priority:n,payload:i,needReadReceipt:a,isSupportExtension:g,cloudCustomData:d,receiverList:c,_relayFlag:!0});return l.setElement(i._elements[0]),l}_getCurrentUserId(){var e;return null===(e=this._core.store.get("login"))||void 0===e?void 0:e.userId}};class S{init(e){this._messageHelper=new f(e),this._core=e;const{notificationCenter:s,InnerEvent:{MESSAGE_PUSH:t},InnerEventSubType:{C2C_NOTIFY_MESSAGE:o}}=e;s.subscribeInnerEvent(t,o,this._handleC2CNotifyMessage,this)}_handleC2CNotifyMessage(e){const{C2cNotifyMsgArray:s}=e;null==s||s.forEach((e=>{Object.keys(e).includes("WithdrawC2cMsgNotify")&&this._handleC2CRevokeMessage(e)}))}_handleC2CRevokeMessage(s){return e(this,void 0,void 0,(function*(){try{const{WithdrawC2cMsgNotify:{C2cWithdrawInfoArray:e}}=s,t=[],{notificationCenter:o,OuterEvent:r,InnerEvent:n}=this._core;e.forEach((e=>{const{MsgRand:s,MsgSeq:o,To_Account:r,From_Account:n,RevokerInfo:{Revoker_Account:i,Reason:a}}=e,c=this._getCurrentUserId()===n?`C2C${r}`:`C2C${n}`,d=this._messageHelper.generateRevokeMessage({conversationID:c,sequence:o,random:s,revoker:i,revokeReason:a});t.push(d)})),0!==t.length&&o.emitInnerEvent(n.MESSAGE_REVOKED,{revokedMessages:t,updateUnreadCount:!0}),yield this._messageHelper.updateRevokerInfo(t),o.emitOuterEvent(r.MESSAGE_REVOKED,{name:r.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},InnerEventSubType:{C2C_NOTIFY_MESSAGE:t}}=this._core;e.unSubscribeInnerEvent(s,t,this._handleC2CNotifyMessage,this)}}class R{init(e){this._messageHelper=new f(e),this._core=e;const{notificationCenter:s,InnerEvent:{MESSAGE_PUSH:t,DESTROY:o},InnerEventSubType:{GROUP_NOTIFY_MESSAGE:r}}=e;s.subscribeInnerEvent(t,r,this._handleGroupNotifyMessage,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(s){return e(this,void 0,void 0,(function*(){try{const{RevokerInfo:e,MsgBody:{GroupWithdrawInfoArray:t}}=s,o=[],{notificationCenter:r,OuterEvent:n,InnerEvent:i}=this._core;t.forEach((s=>{const{Random:t,MsgSeq:r,GroupId:n,MsgClientTime:i,TinyId:a,TopicId:c,RevokerInfo:{Revoker_Account:d=(null==e?void 0:e.Revoker_Account)||"",Reason:g=(null==e?void 0:e.Reason)||""}}=s,u=c?`GROUP${c}`:`GROUP${n}`,l=this._messageHelper.generateRevokeMessage({conversationID:u,sequence:r,random:t,tinyID:a,clientTime:i,revoker:d,revokeReason:g});o.push(l)})),0!==o.length&&(r.emitInnerEvent(i.MESSAGE_REVOKED,{revokedMessages:o,updateUnreadCount:!0}),yield this._messageHelper.updateRevokerInfo(o),r.emitOuterEvent(n.MESSAGE_REVOKED,{name:n.MESSAGE_REVOKED,data:o}))}catch(e){console.debug(e)}}))}dispose(){const{notificationCenter:e,InnerEvent:{MESSAGE_PUSH:s},InnerEventSubType:{GROUP_NOTIFY_MESSAGE:t}}=this._core;e.unSubscribeInnerEvent(s,t,this._handleGroupNotifyMessage,this)}}var C=new class{constructor(){this._c2cMessageReceiver=new S,this._groupMessageReceiver=new R}init(e){this._c2cMessageReceiver.init(e),this._groupMessageReceiver.init(e)}dispose(){this._c2cMessageReceiver.dispose(),this._groupMessageReceiver.dispose()}};class D{constructor(e){this._lastMessageSequenceMapOnDisconnect=new Map,this._core=e,this._messageHelper=new f(e)}getRoamingMessagesByAnchor(s){return e(this,void 0,void 0,(function*(){try{const e=this._core.ssoLog.createSSOLogData({method:"getRoamingMessagesByAnchor"}),{conversationID:t,count:n,direction:i,sequence:a}=s,c=t.replace(_,"");let d=a;if(i===r.BACKWARD){if("number"!=typeof a)return{messageList:[],hasNoMoreHistoryMessage:!1,nextReqMessageIDFromServer:""};d=a+n-1}const g={GroupId:c,ReqMsgNumber:n,WithRecalledMsg:1,Version:1};d&&(g.ReqMsgSeq=d);const u="group_open_http_svc.group_msg_get",l=this._core.helper.generateProtocolData({servcmd:u,data:g}),h=`${l.head.seq}${u}`,v=yield this._core.channel.sendPacket(l,{requestId:h});if(v){const{RspMsgList:s,NextReqMsgSeq:t=0,IsFinished:r,InvisibleMsgSeq:n}=v;e.setLogInfo({message:`groupID:${c} sequence:${a} reqSeq:${d} direction:${i}\n complete:${r} nextSequence:${t} remoteMsgCount:${s.length} invisibleSequenceList:${n}`}).end();const g=[];for(let e=0;e<s.length;e++){const t=s[e],o=this._parseMessage(t);g.push(o)}g.reverse();return{messageList:g,invisibleSequenceList:n,nextReqMessageIDFromServer:t,hasNoMoreHistoryMessage:[o.NO_MORE_DATA,o.DATA_HAS_EXPIRED].includes(r)}}}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(s){return e(this,void 0,void 0,(function*(){const{message:{messageReceiver:t,messageStore:o},notificationCenter:n,OuterEvent:i}=this._core;null==s||s.forEach((s=>e(this,void 0,void 0,(function*(){const{conversationID:e,lastMessage:a}=s;let c=this._getLocalLastMessageSequence(e);const d=a.lastSequence;if(this._shouldRecoverHistory({localLastMessageSequence:c,serverLastMessageSequence:d})){const s=d-c;let a=!1;const g=Math.ceil(s/20);for(let s=0;s<g;s++)try{const s=d-c,g=Math.min(20,s),u=yield this.getRoamingMessagesByAnchor({conversationID:e,sequence:c+g,direction:r.FORWARD,count:g}),{nextReqMessageIDFromServer:l,hasNoMoreHistoryMessage:h,messageList:v}=u;a=h&&l<0,c=v[v.length-1].sequence;const _=[];if(Array.isArray(v)&&(v.forEach((e=>{t.groupMessageReceiver.updateMessageProfile(e);o.storeConversationMessage(e)&&_.push(e)})),_.length>0&&n.emitOuterEvent(i.MESSAGE_RECEIVED,{name:i.MESSAGE_RECEIVED,data:_})),a)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 o=t-s;return 0!==t&&s&&(o>=M&&o<p)}_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=_,t=this._core.message.messageHelper.parseServerGroupMessage(e),o=this._core.message.messageFactory.createMessage(Object.assign(Object.assign({},t),{conversationType:s,flow:"in"}));return o.setElement(t.elements),o}}var A=new class{constructor(){this._clearedConversations=new Set,this._fetchedCompleteConversations=new Set}init(e){this._core=e,this._groupMessageHistory=new D(e),this._messageHelper=new f(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)}getMessageList(s){return e(this,void 0,void 0,(function*(){try{const e=this._core.ssoLog.createSSOLogData({method:"getMessageList"});let{conversationID:t,nextReqMessageID:o}=s;const n=m;if("@TIM#SYSTEM"===t)return{code:0,data:{messageList:[],isCompleted:!1,nextMessageSeq:""}};const i=this._getAvailableLocalMessagesCount({conversationID:t,nextReqMessageID:o});if(this._needFetchHistoryMessageList({conversationID:t,availableLocalMessagesCount:i,targetCount:n})){let s=null;if(t.startsWith(_)&&(s=yield this._groupMessageHistory.getRoamingMessagesByAnchor({conversationID:t,sequence:Number(o),count:n,direction:r.FORWARD})),s){const{nextReqMessageIDFromServer:r,hasNoMoreHistoryMessage:n,messageList:a}=s,c=this._messageHelper.filterValidMessages(a),d=this._core.message.messageStore.prependLocalMessageList({messageList:c,conversationID:t}),g=this._core.message.messageStore.getLocalMessageList(t).slice(0,d.length+i),u=g.filter((e=>e.isRevoked));yield this._messageHelper.updateRevokerInfo(u);const l={nextReqMessageID:n?"":String(r),messageList:g,isCompleted:n},h=g.map((e=>e.sequence));return e.setLogInfo({message:`conversationID: ${t} nextReqMessageID: ${o} \n availableLocalMessagesCount: ${i} sequenceList: ${JSON.stringify(h)} `}).end(),{code:0,data:l}}return{code:0,data:{messageList:[],isCompleted:!1,nextMessageSeq:""}}}e.setLogInfo({message:`conversationID: ${t} nextReqMessageID: ${o} availableLocalMessagesCount: ${i}}`}).end();return{code:0,data:this._getMessageListFromMemory({conversationID:t,nextReqMessageID:o,count:n})}}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(s){return e(this,void 0,void 0,(function*(){var e,t;const{conversationID:o,sequence:n,direction:i=r.FORWARD}=s,{isEmpty:a}=this._core.helper;if(![r.BACKWARD,r.FORWARD].includes(i))throw new this._core.helper.ChatError({message:"direction must be 0 or 1"});let{count:c=m}=s;c=c>m?m:c;let d=null;if(o.startsWith(_)&&(d=yield this._groupMessageHistory.getRoamingMessagesByAnchor({conversationID:o,sequence:n,count:c,direction:i})),d){const{nextReqMessageIDFromServer:s,hasNoMoreHistoryMessage:o,messageList:c,invisibleSequenceList:g}=d,u=this._messageHelper.filterValidMessages(c);if(this._core.message.messageStore.storeSparseMessageList(u),i===r.FORWARD){const e=o&&s<1;return{code:0,data:{messageList:u,isCompleted:e,nextMessageSeq:e?"":s}}}if(i===r.BACKWARD){if(a(c)&&a(g))return{code:0,data:{messageList:[],isCompleted:!0,nextMessageSeq:""}};const s=(null===(e=null==c?void 0:c[c.length-1])||void 0===e?void 0:e.sequence)||0,o=(null===(t=null==g?void 0:g[g.length-1])||void 0===t?void 0:t.sequence)||0;return{code:0,data:{messageList:u.filter((e=>e.sequence>=n)),isCompleted:!1,nextMessageSeq:Math.max(s,o)+1}}}return{code:0,data:d}}return{code:0,data:{messageList:[],isCompleted:!1,nextMessageSeq:""}}}))}_getAvailableLocalMessagesCount({conversationID:e,nextReqMessageID:s}){const t=this._core.message.messageStore.getLocalMessageList(e),{length:o}=t;if(!s)return o;let r=-1;return(null==e?void 0:e.startsWith(v))?r=t.findIndex((e=>e.ID===s)):(null==e?void 0:e.startsWith(_))&&(r=t.findIndex((e=>s.includes("-")?e.ID===s:String(e.sequence)===s))),-1===r?0:r}_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 o=this._core.message.messageStore.getLocalMessageList(e),r=o.length;let n=r,i={isCompleted:!1,nextReqMessageID:"",messageList:[]},a=0,c=r;return s?s&&(c=o.findIndex((t=>e.startsWith(v)?t.ID===s:String(t.sequence)===s)),a=c>t?c-t:0,n=c):a=r>t?r-t:0,i.nextReqMessageID=0===a?"":this._generateNextReqMessageID({conversationID:e,targetIndex:a}),i.messageList=o.slice(a,c),i.isCompleted=n<=t,i}_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===_));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)}};var q=new class{constructor(){this._core=null}init(e){this._core=e;const{helper:s}=e;s.registerApi("translateText",this)}translateText(s){return e(this,void 0,void 0,(function*(){try{const{sourceLanguage:t,sourceTextList:o,targetLanguage:r}=s,n=yield function(s,t){return e(this,void 0,void 0,(function*(){var e,o;const{sourceTextList:r,sourceLanguage:n,targetLanguage:i}=s,{store:a,helper:c,channel:d}=t,g="im_open_translate.ws_batch_trans_text",u={SourceText:r,Source:n,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},l=c.generateProtocolData({servcmd:g,data:u}),h=`${l.head.seq}${g}`,v=yield d.sendPacket(l,{requestId:h});if(v){const{CmdErrorCode:e,TargetText:s}=v;return{cmdErrorCode:e,translatedTextList:s}}}))}({sourceLanguage:t,sourceTextList:o,targetLanguage:r},this._core);if(n){const{cmdErrorCode:{ErrorCode:e,ErrorInfo:s},translatedTextList:t}=n;if(0===e)return{code:0,data:{translatedTextList:t}};throw{errorCode:e,errorInfo:s,message:s}}}catch(e){const{errorCode:s,errorInfo:t}=e||{};throw new this._core.helper.ChatError({functionName:"translateText",code:s,message:t})}}))}};return new class{install(e){this._core=e,E.init(e),y.init(e),C.init(e),A.init(e),c.init(e),q.init(e),e.helper.registerValidateConfig({auth:g,params:d}),e.notificationCenter.subscribeInnerEvent(e.InnerEvent.DESTROY,this.dispose,this)}dispose(){const{notificationCenter:e,InnerEvent:s}=this._core;e.unSubscribeInnerEvent(s.DESTROY,this.dispose,this),C.dispose(),A.dispose()}}}));
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 +1 @@
1
- !function(e,t){"object"==typeof exports&&"undefined"!=typeof module?module.exports=t():"function"==typeof define&&define.amd?define(t):(e="undefined"!=typeof globalThis?globalThis:e||self)["liteChatRich-media-message"]=t()}(this,(function(){"use strict";function e(e,t){var o={};for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&t.indexOf(i)<0&&(o[i]=e[i]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var s=0;for(i=Object.getOwnPropertySymbols(e);s<i.length;s++)t.indexOf(i[s])<0&&Object.prototype.propertyIsEnumerable.call(e,i[s])&&(o[i[s]]=e[i[s]])}return o}function t(e,t,o,i){return new(o||(o=Promise))((function(s,r){function n(e){try{l(i.next(e))}catch(e){r(e)}}function a(e){try{l(i.throw(e))}catch(e){r(e)}}function l(e){var t;e.done?s(e.value):(t=e.value,t instanceof o?t:new o((function(e){e(t)}))).then(n,a)}l((i=i.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:i}=null===(t=this._core)||void 0===t?void 0:t.utils,{downloadUrl:s="",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),!i(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,s,h&&u),i=this._buildResponse(g,t);if(200===g.status)o(null,i);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)},i)}},g.onerror=()=>{const e=this._getResponseBody(g,s,h&&u),t=this._buildResponse(g,e),i={code:g.status,message:0===g.status?"CORS blocked or network error":JSON.stringify(g.responseText)};o(i,t)},e.onProgress&&g.upload&&(g.upload.onprogress=t=>{const{total:o,loaded:i}=t,s=Math.min(Math.floor(100*i/o),100);e.onProgress({total:o,loaded:i,percent:s/100})}),g.send(d),g}))}_buildResponse(e,t){const o={};return e.getAllResponseHeaders().trim().split("\n").forEach((e=>{if(e){const[t,i]=e.split(":").map((e=>e.trim()));o[t.toLowerCase()]=i}})),{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 i;const{isEmpty:s,isPlainObject:r}=null===(i=this._core)||void 0===i?void 0:i.utils;return s(e)?"":r(e)?Object.keys(e).map((i=>{const s=encodeURIComponent(i)+o;return Array.isArray(e[i])?e[i].map((e=>s+encodeURIComponent(e))).join(t):s+encodeURIComponent(e[i])})).filter(Boolean).join(t):void 0}_domainName2IP(e,t){return e.replace(/^http(s)?:\/\/(.*?)\//,`https://${t}/`)}};const i=["unknown","image","video","audio","log"];var s=new class{init(e){this._core=e}request(t,o){var s;const{MINI_APP_NAMESPACE:r,IN_ALIPAY_MINI_APP:n,IN_UNI_IOS_APP:a}=null===(s=this._core)||void 0===s?void 0:s.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?i[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:i}=e,s={};if(o.header)for(const e in o.header)o.header.hasOwnProperty(e)&&(s[e.toLowerCase()]=o.header[e]);const r=+o.statusCode;200===r?i(null,{statusCode:r,headers:s,data:Object.assign(Object.assign({},o.data),{location:t})}):i({code:r,message:JSON.stringify(o.data)},{statusCode:r,headers:s,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 i=Date.now();return t?o?i-e+" ms":`${Math.round((i-e)/1e3)} s`:o?i-e:Math.round((i-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,i]=e.split("?");if(!i)return o;const s=i.split("&").reduce(((e,o)=>{const[i,s]=o.split("=");return i&&i!==t&&(e[i]=s||""),e}),{}),r=Object.keys(s).map((e=>`${e}${s[e]?`=${s[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:i}=(null===(t=this._core)||void 0===t?void 0:t.utils)||{};return this._shouldSkipProbing()?{width:0,height:0}:i?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:i}=o;if(void 0===i)return t;try{JSON.parse(i).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 i=e.name||e.value||e.url||e.tempFilePath,s=i&&i.slice(i.lastIndexOf(".")+1);return s&&(o=`${o}.${s}`),o}processResourceUrl(e){if(!e)return"";let t=e;const o=this.getFileDownloadProxy(),i=this.getAuthKey(),s=this.getFileDNList();o&&(e.startsWith("http://")?t=e.replace(/^http:\/\/[^/]+/,o):e.startsWith("https://")&&(t=e.replace(/^https:\/\/[^/]+/,o)));const r=i&&-1===t.indexOf("authKey=")&&function(e,t){let o=!1;if(e){const i=e.match(/:\/\/([0-9]?\.)?(.[^/:]+)/),s=i&&i[2]||"";if(s.includes("rich-dev"))return!0;for(let e=0;e<t.length;e++)if(s.endsWith(t[e])){o=!0;break}}return o}(t,s);return r&&(t=t.indexOf("?")>-1?`${t}&authKey=${i}`:`${t}?authKey=${i}`),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:i,IN_UNI_NATIVE_APP:s}=null===(e=this._core)||void 0===e?void 0:e.utils;return{IN_BROWSER:t,IN_MINI_APP:o,IN_RN_APP:i,IN_UNI_NATIVE_APP:s}}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:i}=(null===(e=this._core)||void 0===e?void 0:e.utils)||{};return t||o&&9===i}_probeImageDimensionsWeb(e){return new Promise((t=>{const o=new Image,i=()=>{o.onload=null,o.onerror=null,o.src=""};o.onload=()=>{t({width:o.width,height:o.height}),i()},o.onerror=()=>{t({width:0,height:0}),i()},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:i}=e.utils;this.httpRequest=i?s: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 i=Date.now(),s=yield this._createCosOptions(e),r=yield this._uploadFile(s);this._handleUploadError(r,e);const n=this._createUploadResult(o,r),a=Date.now()-i,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:s,response:n}}catch(e){throw console.warn(`${t} failed, error:`,e),e}}))}_handleUploadError(e,t){var o,i;const{ChatError:s}=null===(o=this._core)||void 0===o?void 0:o.helper;if(403===e.statusCode)throw a(Date.now(),!1),t.url,(null===(i=null==e?void 0:e.data)||void 0===i?void 0:i.uploadIP)&&e.data.uploadIP,new s({message:"Upload failed with status 403"})}_createUploadResult(e,t){return{fileName:e.name,fileSize:e.size,fileType:e.type.slice(e.type.indexOf("/")+1).toLowerCase(),location:t.data.location||"",uploadTime: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:i}=this._prepareUploadParams(e),s=this._isC2CConversation(e.message.conversationID)?1:2;try{const r=yield this._fetchCosSignatureUrl({fileType:this.uploadFileType,fileName:t,uploadMethod:i,duration:this.duration,userID:e.message.from,conversationType:s}),{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:i}=w.getPlatformFlags(),s=o||i,r=s&&e.message.type!==g,{name:a}=t,d=a.slice(a.lastIndexOf(".")),c=`${n(999999)}${d}`;return{fileName:l(r?t.name:c),resources:s?t.url:t,uploadMethod:s?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`,i=w.isSimpleCos(),s=this._prepareCosRequestData(e),r=i?"im_cos_msg.simple_sig":"im_cos_msg.pre_sig";try{const e=yield function(e,o,i){return t(this,void 0,void 0,(function*(){try{const{helper:t,channel:s}=i,r=t.generateCosSpecifiedData({servcmd:e,data:o}),n=`${r.head.seq}${e}`;return yield s.sendPacket(r,{requestId:n})}catch(e){throw console.warn("getCosSig error:",e),e}}))}(r,s,this._core);this.fetchCosTryCount=0;const n=this._processResponse(e);return console.log(`${o} ok. isSimpleCos:${i} 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(),i=o?null===(t=null==e?void 0:e.rpt_pre_sig)||void 0===t?void 0:t[0]:e;if(!i)return{};if(o){const{str_final_ip:e,rpt_pre_sig:t,uint32_file_id:o,uint32_exist_flag:s,str_download_url:r,str_upload_url:n,str_snapshot_url:a,str_file_key:l}=i;return{uploadIP:e,preSig:t,fileID:o,existFlag:s,downloadUrl:r,uploadUrl:n,requestSnapshotUrl:a,fileKey:l}}const{upload_url:s,download_url:r,snapshot_url:n,thumb_url:a,large_url:l,file_key:d}=i;return{uploadUrl:s,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,((i,s)=>{i&&this.uploadFileTryCount<this.maxRetries&&this.shouldRetry(i)?(this.uploadFileTryCount++,this._uploadFile(e).then(t).catch(o)):(this.uploadFileTryCount=0,i?o(i):t(s))}))}))}))}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 i=null===(t=e.error)||void 0===t?void 0:t.Code,s=null===(o=e.error)||void 0===o?void 0:o.Message;return"RequestTimeTooSkewed"===i||"AccessDenied"===i&&"Request has expired"===s}catch(e){return!1}}_isClockOutOfSync(e){var t,o,i;const s=(null===(t=e.headers)||void 0===t?void 0:t.date)||(null===(o=e.headers)||void 0===o?void 0:o.Date)||(null===(i=e.error)||void 0===i?void 0:i.ServerTime);if(!s)return!1;const r=Date.now(),n=Date.parse(s);return Math.abs(r+this.systemClockOffset-n)>=3e4}_syncSystemClock(e){var t,o,i;const s=(null===(t=e.headers)||void 0===t?void 0:t.date)||(null===(o=e.headers)||void 0===o?void 0:o.Date)||(null===(i=e.error)||void 0===i?void 0:i.ServerTime);if(s){const e=Date.now(),t=Date.parse(s);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:i,originHeight:s,min:r=198}=t,n=parseInt(i)||0,a=parseInt(s)||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:i,imageInfoArray:s=[]}=e;this._imageMemoryURL=this.createImageDataAsURL(o),this.content={imageFormat:i,uuid:t,imageInfoArray:[]},this.initImageInfoArray(s),this.autoFixUrl()}static parseServerPushElement(e){const{MsgContent:t}=e,{ImageFormat:o,ImageInfoArray:i,UUID:s}=t,r=function(e){return e.map((e=>({size:e.Size,type:e.Type,width:e.Width,height:e.Height,url:e.URL})))}(i);return new N({imageFormat:o,imageInfoArray:r,uuid:s})}createImageDataAsURL(e){let t="";const{IN_MINI_APP:o,IN_RN_APP:i,IN_BROWSER:s}=w.getPlatformFlags();return e?((o||i)&&(t=e.url),s&&(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 i=e[o]||Object.assign({},t),s=new T(i,this._imageMemoryURL);s.setSizeType(o+1),s.setType(o),this.addImageInfo(s)}this.updateAccessSideImageInfoArray()}autoFixUrl(){const e=["http","https"];this.content.imageInfoArray.forEach((t=>{if(!t.url||""===t.imageUrl)return;const[o,...i]=t.imageUrl.split("://"),s=i.join("://");e.includes(o)||t.setImageUrl(`https://${s}`)}))}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 i=0;i<t;i++)o=this.content.imageInfoArray[i],e[i].size&&(o.size=e[i].size),e[i].url&&o.setImageUrl(e[i].url),e[i].width&&(o.width=e[i].width),e[i].height&&(o.height=e[i].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:i,InnerEvent:s,message:r}=e;i.registerApi("createImageMessage",this),null===(t=null==r?void 0:r.messageFactory)||void 0===t||t.registerElementClass(u,N),o.subscribeInnerEvent(s.DESTROY,this._dispose,this)}createImageMessage(e){var t,o,i,s,r;try{const s=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===(i=null===(o=this._core)||void 0===o?void 0:o.message.messageFactory)||void 0===i?void 0:i.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),s.end(),n}catch(e){throw null===(r=(s=this._core.ssoLog.getSSOLogData("createImageMessage")).setError)||void 0===r||r.call(s,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 i=yield this._performImageUpload(t,e,o),s=this._generateImageInfo(i);return t.updateImageInfoArray(s),e}))}_performImageUpload(e,o,i){return t(this,void 0,void 0,(function*(){const{to:t}=o,s={uploadFileType:v,file:i,to:t,message:o,onProgress:t=>{var i,s;e.updatePercent(t),null===(s=null===(i=this._messageOptionsMap.get(o.clientSequence))||void 0===i?void 0:i.onProgress)||void 0===s||s.call(i,t)}},{uploadOptions:r,response:n}=yield S.uploadToCOS(s);return this._parseResponse(r,n)}))}_generateImageInfo(e){console.log(`${f} generateImageInfo`);const{location:t,fileSize:o,width:i,height:s,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:i,height:s};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,i,s,720),this._generateThumbInfo(u,i,s,198)]}_generateThumbInfo(e,t,o,i){return C({originUrl:e,originWidth:t,originHeight:o,min:i})}_processImageInfoArray(e,t){let o,i,s;for(const r of e)1===r.type?(i=r,i.size=t):2===r.type?(s=r,s.size=t):(o=r,o.size=t);return[Object.assign({},o),Object.assign({},s),Object.assign({},i)]}_parseResponse(e,o){return t(this,void 0,void 0,(function*(){console.log(`${f} parseResponse`);try{const{thumbUrl:t,largeUrl:i,downloadUrl:s}=e;t&&i&&(yield this._getImageInfoByUrl(t,o,"thumb"),yield this._getImageInfoByUrl(i,o,"large"));if(w.isSimpleCos()&&!w.isPrivateNetWork()&&(yield this._getImageInfoArray(s,o),null==o?void 0:o.uploadIP)){const e=this._extractDomainFromUrl(s);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,i){return t(this,void 0,void 0,(function*(){try{const t=w.addAuthToUrl(e),{width:s=0,height:r=0}=yield w.probeImageWidthHeight(t);o.width=s,o.height=r,"thumb"===i?(o.smallImageUrl=e,o.smallImageWidth=s,o.smallImageHeight=r):(o.largeImageUrl=e,o.largeImageWidth=s,o.largeImageHeight=r)}catch(e){console.warn(`Failed to get ${i} 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:i}=e.payload;return i=o?this._processMiniAppImageFile(i):this._processWebImageFile(i),i}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,i=w.extractFileFromInput(e);if(!i)throw new o({message:"Invalid file. Pass either `e.target` (from file input) or a File object"});return i}_getDownloadIP(e,o){return t(this,void 0,void 0,(function*(){const i=`${f} getDownloadIP domainName: ${e}`;try{const s=yield function(e,o){return t(this,void 0,void 0,(function*(){try{const{helper:t,channel:i}=o,s="im_cos_msg.get_final_ip",r={str_domain:e},n=t.generateProtocolData({servcmd:s,data:r}),a=`${n.head.seq}${s}`;return yield i.sendPacket(n,{requestId:a})}catch(e){throw console.warn("getFinalIP error:",e),e}}))}(e,this._core);if(!s||!s.str_final_ip)return;console.log(`${i} ok. downloadIP:${s}`);const r=o.location.split("/");r[0]=s.str_final_ip,o.location=r.join("/")}catch(e){console.warn(e)}}))}_getImageInfoArray(e,o){return t(this,void 0,void 0,(function*(){const i=`${f}._getImageInfoArray`;try{const s=yield function(e,o){return t(this,void 0,void 0,(function*(){try{const{helper:t,channel:i}=o,s="im_cos_msg.get_imageinfo",r={str_image_url:e},n=t.generateProtocolData({servcmd:s,data:r}),a=`${n.head.seq}${s}`;return yield i.sendPacket(n,{requestId:a})}catch(e){throw console.warn("getImageInfo error:",e),e}}))}(e,this._core);return o.imageInfoArray=this._processImageInfoResponse(s),console.log(`${i} ok`),o}catch(e){throw o.imageInfoArray=void 0,console.warn(`${i} 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 i="";if(t.IN_MINI_APP&&(i=e.url.slice(e.url.lastIndexOf(".")+1)),t.IN_BROWSER&&(i=e.name.slice(e.name.lastIndexOf(".")+1)),M.indexOf(i.toLowerCase())<0)throw new o.ChatError({code:b})}_checkImageSize(e){const{utils:t,helper:o}=this._core;let i=0;if(i=(t.IN_MINI_APP,e.size),0===i)throw new o.ChatError({code:P});if(i>=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,R=2401,$="2.5.0",z="1.18.0",W=104857600;function j(e,t){const o=e.split("."),i=t.split("."),s=Math.max(o.length,i.length);for(;o.length<s;)o.push("0");for(;i.length<s;)i.push("0");for(let e=0;e<s;e++){const t=parseInt(o[e]),s=parseInt(i[e]);if(t>s)return 1;if(t<s)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:i,FileName:s,FileSize:r,UUID:n}=t;return new x({downloadFlag:o,url:i,fileName:s,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:i,fileSize:s}=this.content;return{MsgType:this.type,MsgContent:{Download_Flag:t,Url:w.removeAuthToUrl(o),FileName:i,FileSize:s,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:i,InnerEvent:s,message:r}=e;i.registerApi("createFileMessage",this),null===(t=null==r?void 0:r.messageFactory)||void 0===t||t.registerElementClass(g,x),o.subscribeInnerEvent(s.DESTROY,this._dispose,this)}createFileMessage(e){var t,o,i,s,r;try{const s=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===(i=null===(o=this._core)||void 0===o?void 0:o.message.messageFactory)||void 0===i?void 0:i.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),s.end(),a}catch(e){throw null===(r=(s=this._core.ssoLog.getSSOLogData("createFileMessage")).setError)||void 0===r||r.call(s,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],i=yield this._performFileUpload(o,e,t),s=w.addAuthToUrl(null==i?void 0:i.location);return o.updateFileUrl(s),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:R});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,i){return t(this,void 0,void 0,(function*(){const{to:t}=o,s={uploadFileType:v,file:i,to:t,message:o,onProgress:t=>{var i,s;e.updatePercent(t),null===(s=null===(i=this._messageOptionsMap.get(o.clientSequence))||void 0===i?void 0:i.onProgress)||void 0===s||s.call(i,t)}},{response:r}=yield S.uploadToCOS(s);return r}))}_processFile(e){var t,o;const{IN_BROWSER:i,IN_RN_APP:s,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(i||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 s?Object.assign(Object.assign({},e),{url:e.uri}):e}_checkVersion(){var e,t;const{MINI_APP_NAMESPACE:o,IN_MINI_APP:i,IN_WX_MINI_APP:s,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(i){if(!(s||r||n))throw new a({message:"Unsupported mini app environment"});const e=o.getSystemInfoSync().SDKVersion;if(s&&j(e,$)<0){throw new a({message:`WXChooseMessageFile requires SDK version ${$} 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:i,VideoSecond:s,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:i,videoSecond:s,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:i}=e;w.isEmpty(t)||(this.content.thumbUrl=this.content.snapshotUrl=t),w.isEmpty(o)||(this.content.thumbWidth=this.content.snapshotWidth=Number(o)),w.isEmpty(i)||(this.content.thumbHeight=this.content.snapshotHeight=Number(i))}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:i,videoDownloadFlag:s,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:i,VideoDownloadFlag:s,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:i,InnerEvent:s,message:r}=e;i.registerApi("createVideoMessage",this),null===(t=null==r?void 0:r.messageFactory)||void 0===t||t.registerElementClass(m,H),o.subscribeInnerEvent(s.DESTROY,this._dispose,this)}createVideoMessage(e){var t,o,i,s,r;try{const s=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===(i=null===(o=this._core)||void 0===o?void 0:o.message.messageFactory)||void 0===i?void 0:i.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),s.end(),a}catch(e){throw null===(r=(s=this._core.ssoLog.getSSOLogData("createVideoMessage")).setError)||void 0===r||r.call(s,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 i=yield this._performVideoUpload(t,e,o),{location:s,snapshotInfo:r}=i,n=w.addAuthToUrl(s);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,i){return t(this,void 0,void 0,(function*(){const{to:t}=o,s={uploadFileType:I,file:i,to:t,message:o,onProgress:t=>{var i,s;e.updatePercent(t),null===(s=null===(i=this._messageOptionsMap.get(o.clientSequence))||void 0===i?void 0:i.onProgress)||void 0===s||s.call(i,t)}},{response:r,uploadOptions:n}=yield S.uploadToCOS(s);return{snapshotInfo:yield this._getSnapshotInfoByUrl(n.requestSnapshotUrl),location:r.location}}))}_processVideo(e){var t,o;try{const{ChatError:i}=null===(t=this._core)||void 0===t?void 0:t.helper,{IN_MINI_APP:s,IN_BROWSER:r}=null===(o=this._core)||void 0===o?void 0:o.utils;let{file:n}=e.payload,a={};if(s&&(a=this._processMiniVideoFile(n)),r){const e=w.extractFileFromInput(n);if(!e)throw new i({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:i}=null===(t=this._core)||void 0===t?void 0:t.utils,{ChatError:s}=null===(o=this._core)||void 0===o?void 0:o.helper;if(i)throw new s({message:"VideoUnsupportedInAlipay"});if(r(e))throw new s({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:i=0,type:s}=e,r=s.split("/")[1];return{url:window.URL.createObjectURL(e),name:t,size:o,second:i,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},i=yield function(e,o){return t(this,void 0,void 0,(function*(){try{const t="im_cos_msg.video_cover",{helper:i,channel:s}=o,r=i.generateCosSpecifiedData({servcmd:t,data:e}),n=`${r.head.seq}${t}`;return yield s.sendPacket(r,{requestId:n})}catch(e){throw console.warn("getSnapshotInfo error:",e),e}}))}(o,this._core),{download_url:s}=i||{};if(console.log(`${f} _getSnapshotInfoByUrl OK snapshotUrl:`,s),w.isEmpty(s))return{};const r=w.addAuthToUrl(s),{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:i,Second:s,Size:r,UUID:n}=t;return new Y({url:o,downloadFlag:i,second:s,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:i,second:s}=this.content;return{MsgType:this.type,MsgContent:{Url:w.removeAuthToUrl(o),Download_Flag:t,Second:s,Size:i,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:i,InnerEvent:s,message:r}=e;i.registerApi("createAudioMessage",this),null===(t=null==r?void 0:r.messageFactory)||void 0===t||t.registerElementClass(p,Y),o.subscribeInnerEvent(s.DESTROY,this._dispose,this)}createAudioMessage(e){var t,o,i,s,r;try{const s=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===(i=null===(o=this._core)||void 0===o?void 0:o.message.messageFactory)||void 0===i?void 0:i.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),s.end(),a}catch(e){throw null===(r=(s=this._core.ssoLog.getSSOLogData("createAudioMessage")).setError)||void 0===r||r.call(s,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],i=yield this._performAudioUpload(o,e,t),s=w.addAuthToUrl(null==i?void 0:i.location);return o.updateAudioUrl(s),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,i){return t(this,void 0,void 0,(function*(){const{to:t}=o,s={uploadFileType:y,file:i,to:t,message:o,onProgress:t=>{var i,s;e.updatePercent(t),null===(s=null===(i=this._messageOptionsMap.get(o.clientSequence))||void 0===i?void 0:i.onProgress)||void 0===s||s.call(i,t)}},{response:r}=yield S.uploadToCOS(s);return r}))}_processAudioFile(e){var t;const{IN_MINI_APP:o,IN_BROWSER:i}=null===(t=this._core)||void 0===t?void 0:t.utils;return o?this._processMiniFile(e):i?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};return 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,i,s;try{return console.log("sendMessage message:",e),yield this._upload(e),yield null===(s=null===(i=null===(t=this._core)||void 0===t?void 0:t.message)||void 0===i?void 0:i.messageSender)||void 0===s?void 0:s.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(i){throw e.status=U.FAIL,i instanceof Error&&(i.data={message:e}),this._core.message.messageStore.storeConversationMessage(e),null===(o=(t=this._core.ssoLog.getSSOLogData("upload")).setError)||void 0===o||o.call(t,i).end(),i}}))}}}));
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)["TencentCloudChatRich-media-message"]=t()}(this,(function(){"use strict";function e(e,t){var o={};for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&t.indexOf(i)<0&&(o[i]=e[i]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var s=0;for(i=Object.getOwnPropertySymbols(e);s<i.length;s++)t.indexOf(i[s])<0&&Object.prototype.propertyIsEnumerable.call(e,i[s])&&(o[i[s]]=e[i[s]])}return o}function t(e,t,o,i){return new(o||(o=Promise))((function(s,r){function n(e){try{l(i.next(e))}catch(e){r(e)}}function a(e){try{l(i.throw(e))}catch(e){r(e)}}function l(e){var t;e.done?s(e.value):(t=e.value,t instanceof o?t:new o((function(e){e(t)}))).then(n,a)}l((i=i.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:i}=null===(t=this._core)||void 0===t?void 0:t.utils,{downloadUrl:s="",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),!i(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,s,h&&u),i=this._buildResponse(g,t);if(200===g.status)o(null,i);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)},i)}},g.onerror=()=>{const e=this._getResponseBody(g,s,h&&u),t=this._buildResponse(g,e),i={code:g.status,message:0===g.status?"CORS blocked or network error":JSON.stringify(g.responseText)};o(i,t)},e.onProgress&&g.upload&&(g.upload.onprogress=t=>{const{total:o,loaded:i}=t,s=Math.min(Math.floor(100*i/o),100);e.onProgress({total:o,loaded:i,percent:s/100})}),g.send(d),g}))}_buildResponse(e,t){const o={};return e.getAllResponseHeaders().trim().split("\n").forEach((e=>{if(e){const[t,i]=e.split(":").map((e=>e.trim()));o[t.toLowerCase()]=i}})),{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 i;const{isEmpty:s,isPlainObject:r}=null===(i=this._core)||void 0===i?void 0:i.utils;return s(e)?"":r(e)?Object.keys(e).map((i=>{const s=encodeURIComponent(i)+o;return Array.isArray(e[i])?e[i].map((e=>s+encodeURIComponent(e))).join(t):s+encodeURIComponent(e[i])})).filter(Boolean).join(t):void 0}_domainName2IP(e,t){return e.replace(/^http(s)?:\/\/(.*?)\//,`https://${t}/`)}};const i=["unknown","image","video","audio","log"];var s=new class{init(e){this._core=e}request(t,o){var s;const{MINI_APP_NAMESPACE:r,IN_ALIPAY_MINI_APP:n,IN_UNI_IOS_APP:a}=null===(s=this._core)||void 0===s?void 0:s.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?i[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:i}=e,s={};if(o.header)for(const e in o.header)o.header.hasOwnProperty(e)&&(s[e.toLowerCase()]=o.header[e]);const r=+o.statusCode;200===r?i(null,{statusCode:r,headers:s,data:Object.assign(Object.assign({},o.data),{location:t})}):i({code:r,message:JSON.stringify(o.data)},{statusCode:r,headers:s,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 i=Date.now();return t?o?i-e+" ms":`${Math.round((i-e)/1e3)} s`:o?i-e:Math.round((i-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,i]=e.split("?");if(!i)return o;const s=i.split("&").reduce(((e,o)=>{const[i,s]=o.split("=");return i&&i!==t&&(e[i]=s||""),e}),{}),r=Object.keys(s).map((e=>`${e}${s[e]?`=${s[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:i}=(null===(t=this._core)||void 0===t?void 0:t.utils)||{};return this._shouldSkipProbing()?{width:0,height:0}:i?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:i}=o;if(void 0===i)return t;try{JSON.parse(i).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 i=e.name||e.value||e.url||e.tempFilePath,s=i&&i.slice(i.lastIndexOf(".")+1);return s&&(o=`${o}.${s}`),o}processResourceUrl(e){if(!e)return"";let t=e;const o=this.getFileDownloadProxy(),i=this.getAuthKey(),s=this.getFileDNList();o&&(e.startsWith("http://")?t=e.replace(/^http:\/\/[^/]+/,o):e.startsWith("https://")&&(t=e.replace(/^https:\/\/[^/]+/,o)));const r=i&&-1===t.indexOf("authKey=")&&function(e,t){let o=!1;if(e){const i=e.match(/:\/\/([0-9]?\.)?(.[^/:]+)/),s=i&&i[2]||"";if(s.includes("rich-dev"))return!0;for(let e=0;e<t.length;e++)if(s.endsWith(t[e])){o=!0;break}}return o}(t,s);return r&&(t=t.indexOf("?")>-1?`${t}&authKey=${i}`:`${t}?authKey=${i}`),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:i,IN_UNI_NATIVE_APP:s}=null===(e=this._core)||void 0===e?void 0:e.utils;return{IN_BROWSER:t,IN_MINI_APP:o,IN_RN_APP:i,IN_UNI_NATIVE_APP:s}}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:i}=(null===(e=this._core)||void 0===e?void 0:e.utils)||{};return t||o&&9===i}_probeImageDimensionsWeb(e){return new Promise((t=>{const o=new Image,i=()=>{o.onload=null,o.onerror=null,o.src=""};o.onload=()=>{t({width:o.width,height:o.height}),i()},o.onerror=()=>{t({width:0,height:0}),i()},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:i}=e.utils;this.httpRequest=i?s: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 i=Date.now(),s=yield this._createCosOptions(e),r=yield this._uploadFile(s);this._handleUploadError(r,e);const n=this._createUploadResult(o,r),a=Date.now()-i,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:s,response:n}}catch(e){throw console.warn(`${t} failed, error:`,e),e}}))}_handleUploadError(e,t){var o,i;const{ChatError:s}=null===(o=this._core)||void 0===o?void 0:o.helper;if(403===e.statusCode)throw a(Date.now(),!1),t.url,(null===(i=null==e?void 0:e.data)||void 0===i?void 0:i.uploadIP)&&e.data.uploadIP,new s({message:"Upload failed with status 403"})}_createUploadResult(e,t){return{fileName:e.name,fileSize:e.size,fileType:e.type.slice(e.type.indexOf("/")+1).toLowerCase(),location:t.data.location||"",uploadTime: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:i}=this._prepareUploadParams(e),s=this._isC2CConversation(e.message.conversationID)?1:2;try{const r=yield this._fetchCosSignatureUrl({fileType:this.uploadFileType,fileName:t,uploadMethod:i,duration:this.duration,userID:e.message.from,conversationType:s}),{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:i}=w.getPlatformFlags(),s=o||i,r=s&&e.message.type!==g,{name:a}=t,d=a.slice(a.lastIndexOf(".")),c=`${n(999999)}${d}`;return{fileName:l(r?t.name:c),resources:s?t.url:t,uploadMethod:s?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`,i=w.isSimpleCos(),s=this._prepareCosRequestData(e),r=i?"im_cos_msg.simple_sig":"im_cos_msg.pre_sig";try{const e=yield function(e,o,i){return t(this,void 0,void 0,(function*(){try{const{helper:t,channel:s}=i,r=t.generateCosSpecifiedData({servcmd:e,data:o}),n=`${r.head.seq}${e}`;return yield s.sendPacket(r,{requestId:n})}catch(e){throw console.warn("getCosSig error:",e),e}}))}(r,s,this._core);this.fetchCosTryCount=0;const n=this._processResponse(e);return console.log(`${o} ok. isSimpleCos:${i} 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(),i=o?null===(t=null==e?void 0:e.rpt_pre_sig)||void 0===t?void 0:t[0]:e;if(!i)return{};if(o){const{str_final_ip:e,rpt_pre_sig:t,uint32_file_id:o,uint32_exist_flag:s,str_download_url:r,str_upload_url:n,str_snapshot_url:a,str_file_key:l}=i;return{uploadIP:e,preSig:t,fileID:o,existFlag:s,downloadUrl:r,uploadUrl:n,requestSnapshotUrl:a,fileKey:l}}const{upload_url:s,download_url:r,snapshot_url:n,thumb_url:a,large_url:l,file_key:d}=i;return{uploadUrl:s,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,((i,s)=>{i&&this.uploadFileTryCount<this.maxRetries&&this.shouldRetry(i)?(this.uploadFileTryCount++,this._uploadFile(e).then(t).catch(o)):(this.uploadFileTryCount=0,i?o(i):t(s))}))}))}))}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 i=null===(t=e.error)||void 0===t?void 0:t.Code,s=null===(o=e.error)||void 0===o?void 0:o.Message;return"RequestTimeTooSkewed"===i||"AccessDenied"===i&&"Request has expired"===s}catch(e){return!1}}_isClockOutOfSync(e){var t,o,i;const s=(null===(t=e.headers)||void 0===t?void 0:t.date)||(null===(o=e.headers)||void 0===o?void 0:o.Date)||(null===(i=e.error)||void 0===i?void 0:i.ServerTime);if(!s)return!1;const r=Date.now(),n=Date.parse(s);return Math.abs(r+this.systemClockOffset-n)>=3e4}_syncSystemClock(e){var t,o,i;const s=(null===(t=e.headers)||void 0===t?void 0:t.date)||(null===(o=e.headers)||void 0===o?void 0:o.Date)||(null===(i=e.error)||void 0===i?void 0:i.ServerTime);if(s){const e=Date.now(),t=Date.parse(s);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:i,originHeight:s,min:r=198}=t,n=parseInt(i)||0,a=parseInt(s)||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:i,imageInfoArray:s=[]}=e;this._imageMemoryURL=this.createImageDataAsURL(o),this.content={imageFormat:i,uuid:t,imageInfoArray:[]},this.initImageInfoArray(s),this.autoFixUrl()}static parseServerPushElement(e){const{MsgContent:t}=e,{ImageFormat:o,ImageInfoArray:i,UUID:s}=t,r=function(e){return e.map((e=>({size:e.Size,type:e.Type,width:e.Width,height:e.Height,url:e.URL})))}(i);return new N({imageFormat:o,imageInfoArray:r,uuid:s})}createImageDataAsURL(e){let t="";const{IN_MINI_APP:o,IN_RN_APP:i,IN_BROWSER:s}=w.getPlatformFlags();return e?((o||i)&&(t=e.url),s&&(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 i=e[o]||Object.assign({},t),s=new T(i,this._imageMemoryURL);s.setSizeType(o+1),s.setType(o),this.addImageInfo(s)}this.updateAccessSideImageInfoArray()}autoFixUrl(){const e=["http","https"];this.content.imageInfoArray.forEach((t=>{if(!t.url||""===t.imageUrl)return;const[o,...i]=t.imageUrl.split("://"),s=i.join("://");e.includes(o)||t.setImageUrl(`https://${s}`)}))}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 i=0;i<t;i++)o=this.content.imageInfoArray[i],e[i].size&&(o.size=e[i].size),e[i].url&&o.setImageUrl(e[i].url),e[i].width&&(o.width=e[i].width),e[i].height&&(o.height=e[i].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:i,InnerEvent:s,message:r}=e;i.registerApi("createImageMessage",this),null===(t=null==r?void 0:r.messageFactory)||void 0===t||t.registerElementClass(u,N),o.subscribeInnerEvent(s.DESTROY,this._dispose,this)}createImageMessage(e){var t,o,i,s,r;try{const s=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===(i=null===(o=this._core)||void 0===o?void 0:o.message.messageFactory)||void 0===i?void 0:i.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),s.end(),n}catch(e){throw null===(r=(s=this._core.ssoLog.getSSOLogData("createImageMessage")).setError)||void 0===r||r.call(s,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 i=yield this._performImageUpload(t,e,o),s=this._generateImageInfo(i);return t.updateImageInfoArray(s),e}))}_performImageUpload(e,o,i){return t(this,void 0,void 0,(function*(){const{to:t}=o,s={uploadFileType:v,file:i,to:t,message:o,onProgress:t=>{var i,s;e.updatePercent(t),null===(s=null===(i=this._messageOptionsMap.get(o.clientSequence))||void 0===i?void 0:i.onProgress)||void 0===s||s.call(i,t)}},{uploadOptions:r,response:n}=yield S.uploadToCOS(s);return this._parseResponse(r,n)}))}_generateImageInfo(e){console.log(`${f} generateImageInfo`);const{location:t,fileSize:o,width:i,height:s,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:i,height:s};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,i,s,720),this._generateThumbInfo(u,i,s,198)]}_generateThumbInfo(e,t,o,i){return C({originUrl:e,originWidth:t,originHeight:o,min:i})}_processImageInfoArray(e,t){let o,i,s;for(const r of e)1===r.type?(i=r,i.size=t):2===r.type?(s=r,s.size=t):(o=r,o.size=t);return[Object.assign({},o),Object.assign({},s),Object.assign({},i)]}_parseResponse(e,o){return t(this,void 0,void 0,(function*(){console.log(`${f} parseResponse`);try{const{thumbUrl:t,largeUrl:i,downloadUrl:s}=e;t&&i&&(yield this._getImageInfoByUrl(t,o,"thumb"),yield this._getImageInfoByUrl(i,o,"large"));if(w.isSimpleCos()&&!w.isPrivateNetWork()&&(yield this._getImageInfoArray(s,o),null==o?void 0:o.uploadIP)){const e=this._extractDomainFromUrl(s);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,i){return t(this,void 0,void 0,(function*(){try{const t=w.addAuthToUrl(e),{width:s=0,height:r=0}=yield w.probeImageWidthHeight(t);o.width=s,o.height=r,"thumb"===i?(o.smallImageUrl=e,o.smallImageWidth=s,o.smallImageHeight=r):(o.largeImageUrl=e,o.largeImageWidth=s,o.largeImageHeight=r)}catch(e){console.warn(`Failed to get ${i} 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:i}=e.payload;return i=o?this._processMiniAppImageFile(i):this._processWebImageFile(i),i}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,i=w.extractFileFromInput(e);if(!i)throw new o({message:"Invalid file. Pass either `e.target` (from file input) or a File object"});return i}_getDownloadIP(e,o){return t(this,void 0,void 0,(function*(){const i=`${f} getDownloadIP domainName: ${e}`;try{const s=yield function(e,o){return t(this,void 0,void 0,(function*(){try{const{helper:t,channel:i}=o,s="im_cos_msg.get_final_ip",r={str_domain:e},n=t.generateProtocolData({servcmd:s,data:r}),a=`${n.head.seq}${s}`;return yield i.sendPacket(n,{requestId:a})}catch(e){throw console.warn("getFinalIP error:",e),e}}))}(e,this._core);if(!s||!s.str_final_ip)return;console.log(`${i} ok. downloadIP:${s}`);const r=o.location.split("/");r[0]=s.str_final_ip,o.location=r.join("/")}catch(e){console.warn(e)}}))}_getImageInfoArray(e,o){return t(this,void 0,void 0,(function*(){const i=`${f}._getImageInfoArray`;try{const s=yield function(e,o){return t(this,void 0,void 0,(function*(){try{const{helper:t,channel:i}=o,s="im_cos_msg.get_imageinfo",r={str_image_url:e},n=t.generateProtocolData({servcmd:s,data:r}),a=`${n.head.seq}${s}`;return yield i.sendPacket(n,{requestId:a})}catch(e){throw console.warn("getImageInfo error:",e),e}}))}(e,this._core);return o.imageInfoArray=this._processImageInfoResponse(s),console.log(`${i} ok`),o}catch(e){throw o.imageInfoArray=void 0,console.warn(`${i} 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 i="";if(t.IN_MINI_APP&&(i=e.url.slice(e.url.lastIndexOf(".")+1)),t.IN_BROWSER&&(i=e.name.slice(e.name.lastIndexOf(".")+1)),M.indexOf(i.toLowerCase())<0)throw new o.ChatError({code:b})}_checkImageSize(e){const{utils:t,helper:o}=this._core;let i=0;if(i=(t.IN_MINI_APP,e.size),0===i)throw new o.ChatError({code:P});if(i>=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,R=2401,$="2.5.0",z="1.18.0",W=104857600;function j(e,t){const o=e.split("."),i=t.split("."),s=Math.max(o.length,i.length);for(;o.length<s;)o.push("0");for(;i.length<s;)i.push("0");for(let e=0;e<s;e++){const t=parseInt(o[e]),s=parseInt(i[e]);if(t>s)return 1;if(t<s)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:i,FileName:s,FileSize:r,UUID:n}=t;return new x({downloadFlag:o,url:i,fileName:s,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:i,fileSize:s}=this.content;return{MsgType:this.type,MsgContent:{Download_Flag:t,Url:w.removeAuthToUrl(o),FileName:i,FileSize:s,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:i,InnerEvent:s,message:r}=e;i.registerApi("createFileMessage",this),null===(t=null==r?void 0:r.messageFactory)||void 0===t||t.registerElementClass(g,x),o.subscribeInnerEvent(s.DESTROY,this._dispose,this)}createFileMessage(e){var t,o,i,s,r;try{const s=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===(i=null===(o=this._core)||void 0===o?void 0:o.message.messageFactory)||void 0===i?void 0:i.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),s.end(),a}catch(e){throw null===(r=(s=this._core.ssoLog.getSSOLogData("createFileMessage")).setError)||void 0===r||r.call(s,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],i=yield this._performFileUpload(o,e,t),s=w.addAuthToUrl(null==i?void 0:i.location);return o.updateFileUrl(s),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:R});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,i){return t(this,void 0,void 0,(function*(){const{to:t}=o,s={uploadFileType:v,file:i,to:t,message:o,onProgress:t=>{var i,s;e.updatePercent(t),null===(s=null===(i=this._messageOptionsMap.get(o.clientSequence))||void 0===i?void 0:i.onProgress)||void 0===s||s.call(i,t)}},{response:r}=yield S.uploadToCOS(s);return r}))}_processFile(e){var t,o;const{IN_BROWSER:i,IN_RN_APP:s,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(i||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 s?Object.assign(Object.assign({},e),{url:e.uri}):e}_checkVersion(){var e,t;const{MINI_APP_NAMESPACE:o,IN_MINI_APP:i,IN_WX_MINI_APP:s,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(i){if(!(s||r||n))throw new a({message:"Unsupported mini app environment"});const e=o.getSystemInfoSync().SDKVersion;if(s&&j(e,$)<0){throw new a({message:`WXChooseMessageFile requires SDK version ${$} 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:i,VideoSecond:s,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:i,videoSecond:s,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:i}=e;w.isEmpty(t)||(this.content.thumbUrl=this.content.snapshotUrl=t),w.isEmpty(o)||(this.content.thumbWidth=this.content.snapshotWidth=Number(o)),w.isEmpty(i)||(this.content.thumbHeight=this.content.snapshotHeight=Number(i))}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:i,videoDownloadFlag:s,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:i,VideoDownloadFlag:s,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:i,InnerEvent:s,message:r}=e;i.registerApi("createVideoMessage",this),null===(t=null==r?void 0:r.messageFactory)||void 0===t||t.registerElementClass(m,H),o.subscribeInnerEvent(s.DESTROY,this._dispose,this)}createVideoMessage(e){var t,o,i,s,r;try{const s=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===(i=null===(o=this._core)||void 0===o?void 0:o.message.messageFactory)||void 0===i?void 0:i.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),s.end(),a}catch(e){throw null===(r=(s=this._core.ssoLog.getSSOLogData("createVideoMessage")).setError)||void 0===r||r.call(s,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 i=yield this._performVideoUpload(t,e,o),{location:s,snapshotInfo:r}=i,n=w.addAuthToUrl(s);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,i){return t(this,void 0,void 0,(function*(){const{to:t}=o,s={uploadFileType:I,file:i,to:t,message:o,onProgress:t=>{var i,s;e.updatePercent(t),null===(s=null===(i=this._messageOptionsMap.get(o.clientSequence))||void 0===i?void 0:i.onProgress)||void 0===s||s.call(i,t)}},{response:r,uploadOptions:n}=yield S.uploadToCOS(s);return{snapshotInfo:yield this._getSnapshotInfoByUrl(n.requestSnapshotUrl),location:r.location}}))}_processVideo(e){var t,o;try{const{ChatError:i}=null===(t=this._core)||void 0===t?void 0:t.helper,{IN_MINI_APP:s,IN_BROWSER:r}=null===(o=this._core)||void 0===o?void 0:o.utils;let{file:n}=e.payload,a={};if(s&&(a=this._processMiniVideoFile(n)),r){const e=w.extractFileFromInput(n);if(!e)throw new i({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:i}=null===(t=this._core)||void 0===t?void 0:t.utils,{ChatError:s}=null===(o=this._core)||void 0===o?void 0:o.helper;if(i)throw new s({message:"VideoUnsupportedInAlipay"});if(r(e))throw new s({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:i=0,type:s}=e,r=s.split("/")[1];return{url:window.URL.createObjectURL(e),name:t,size:o,second:i,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},i=yield function(e,o){return t(this,void 0,void 0,(function*(){try{const t="im_cos_msg.video_cover",{helper:i,channel:s}=o,r=i.generateCosSpecifiedData({servcmd:t,data:e}),n=`${r.head.seq}${t}`;return yield s.sendPacket(r,{requestId:n})}catch(e){throw console.warn("getSnapshotInfo error:",e),e}}))}(o,this._core),{download_url:s}=i||{};if(console.log(`${f} _getSnapshotInfoByUrl OK snapshotUrl:`,s),w.isEmpty(s))return{};const r=w.addAuthToUrl(s),{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:i,Second:s,Size:r,UUID:n}=t;return new Y({url:o,downloadFlag:i,second:s,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:i,second:s}=this.content;return{MsgType:this.type,MsgContent:{Url:w.removeAuthToUrl(o),Download_Flag:t,Second:s,Size:i,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:i,InnerEvent:s,message:r}=e;i.registerApi("createAudioMessage",this),null===(t=null==r?void 0:r.messageFactory)||void 0===t||t.registerElementClass(p,Y),o.subscribeInnerEvent(s.DESTROY,this._dispose,this)}createAudioMessage(e){var t,o,i,s,r;try{const s=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===(i=null===(o=this._core)||void 0===o?void 0:o.message.messageFactory)||void 0===i?void 0:i.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),s.end(),a}catch(e){throw null===(r=(s=this._core.ssoLog.getSSOLogData("createAudioMessage")).setError)||void 0===r||r.call(s,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],i=yield this._performAudioUpload(o,e,t),s=w.addAuthToUrl(null==i?void 0:i.location);return o.updateAudioUrl(s),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,i){return t(this,void 0,void 0,(function*(){const{to:t}=o,s={uploadFileType:y,file:i,to:t,message:o,onProgress:t=>{var i,s;e.updatePercent(t),null===(s=null===(i=this._messageOptionsMap.get(o.clientSequence))||void 0===i?void 0:i.onProgress)||void 0===s||s.call(i,t)}},{response:r}=yield S.uploadToCOS(s);return r}))}_processAudioFile(e){var t;const{IN_MINI_APP:o,IN_BROWSER:i}=null===(t=this._core)||void 0===t?void 0:t.utils;return o?this._processMiniFile(e):i?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};return 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,i,s;try{return console.log("sendMessage message:",e),yield this._upload(e),yield null===(s=null===(i=null===(t=this._core)||void 0===t?void 0:t.message)||void 0===i?void 0:i.messageSender)||void 0===s?void 0:s.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(i){throw e.status=U.FAIL,i instanceof Error&&(i.data={message:e}),this._core.message.messageStore.storeConversationMessage(e),null===(o=(t=this._core.ssoLog.getSSOLogData("upload")).setError)||void 0===o||o.call(t,i).end(),i}}))}}}));
@@ -1,8 +1,8 @@
1
1
  declare const userEnhancerPlugin: {
2
- [key: string]: any;
3
- };
2
+ [key: string]: any;
3
+ };
4
4
 
5
+ export default userEnhancerPlugin;
6
+ declare module '@tencentcloud/lite-chat/plugins/user-enhancer' {
5
7
  export default userEnhancerPlugin;
6
- declare module '@tencentcloud/lite-chat/plugins/user-enhancer' {
7
- export default userEnhancerPlugin;
8
- }
8
+ }