@tencentcloud/lite-chat 1.2.1 → 1.4.0

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